How to fix OSError: [Errno 22] Invalid argument

Question:

Problem: Getting an error code OSError: [Errno 22] Invalid argument: when running my code.

Intended purpose of the code: Download all attachements from one sender in gmail using python.

Type of files beeing downloaded: .DBF files

ACTUAL names of the files: C:SOMETHINGSOMETHING.DBF (old path is part of the name of the file)

Script:

import os
import traceback

from imbox import Imbox 

host = "imap.gmail.com"
username = "[email protected]"
password = 'PASSWORD'
download_folder = r'C:UserDataUSERFOLDERFOLDER'

if not os.path.isdir(download_folder):
    os.makedirs(download_folder, exist_ok=True)
    
mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)
messages = mail.messages(unread=True, sent_from='[email protected]')


for (uid, message) in messages:
    mail.mark_seen(uid) # optional, mark message as read

    for idx, attachment in enumerate(message.attachments):
        try:
            att_fn = attachment.get('filename')
            download_path = f"{download_folder}/{att_fn}"
            print(download_path)
            with open(download_path, "wb") as fp:
                fp.write(attachment.get('content').read())
        except:
            print(traceback.print_exc())

mail.logout()

Error message:

C:UserDataUSERFOLDERFOLDER/C:SOMETHINGSOMETHING.DBF
Traceback (most recent call last):
  File "c:UserDataSOMETHING.py", line 29, in <module>
    with open(download_path, "wb") as fp:
OSError: [Errno 22] Invalid argument: 'C:\UserData\USER\FOLDER\FOLDER/C:\SOMETHING\SOMETHING.DBF'
None

Question: How do I make this script work?

Asked By: Jan Přívětivý

||

Answers:

You need to split off the filename from the full path that is listed as the attachment path:

for (uid, message) in messages:
    mail.mark_seen(uid) # optional, mark message as read

    for idx, attachment in enumerate(message.attachments):
        try:
            # Here
            _, att_fn = os.path.split(attachment.get('filename'))

            download_path = f"{download_folder}/{att_fn}"
            print(download_path)
            with open(download_path, "wb") as fp:
                fp.write(attachment.get('content').read())
        except:
            print(traceback.print_exc())
Answered By: C.Nivs

You need to set the OpenOptions to enable ‘read’.
I’m guessing that the error ‘Open option action is not specified’

I had

let r = OpenOptions::new().open(filename);

and changed it to

let r = OpenOptions::new().read(true).open(filename);

and the problem was solved

Answered By: user3593503