Search code examples
outlookpython-3.4email-attachmentswin32comworking-directory

Python 3.4 - win32com change working directory


I have a simple program that uses win32com.client's Dispatch to connect to an outlook E-mail box, go through emails and save attachments localy.

If I want to save an attachment, I process a path and a file name for it so I can save it localy with the method attachment.SaveAsFile(file). In some cases, the path + file name exceeds the limit of 255 chars (together) so this fails.

I want to know how I can change the working directory for that method. If I try to seperate the path and the file name, use os.chdir() to change my working directory to the path extracted and use SaveAsFile() with only the name of the file, It will save it in a temp folder (meaning the os.chdir() does not effect that method)

the temp folder if it's any help: C:\Users[USERNAME]\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.Outlook\GKSDWWYZ

So, How can I change the default working directory for the SaveAsFile() method?

this is what I'm doing:

def save_attachment_as_file(att, file):
    """
    att - an email attachment
    file - to full path and filename to save the attachment as
    """
    
    # seperate the path and filename
    file_path = file[:file.rfind("\\")]
    file_name = file[file.rfind("\\")+1:]
    
    # check that both seperate lengths does not exceed the limit
    if not check_length(file_path) or not check_length(file_name):
        return
    
    # save the currect working directory
    working_path = getcwd()
    # change the working directory to the provided path
    chdir(file_path)
    # save the attachment
    att.SaveAsFile(file_name)
    # change back the working directory
    chdir(working_path)

    print("Created:", file)

Solution

  • I think the real problem is how do you get Outlook to save an attachment when the path has more than 255 characters. Based on info on Microsoft office website (such as https://support.microsoft.com/en-us/kb/131464, which is for Excel but the essence is the same as your problem, and so the "things to try" apply here), your best bet is to let Outlook save to the temp folder, then use Python shutil.copyfile() to copy the file (since this function honors the current working directory).

    You could also try the 8.3 format as described Unable to locate files with long names on Windows with Python.

    Also take a look at Copy a file with a too long path to another directory in Python and Python: copy long file path Shutil.copyfile for tricks that may be useful.