Why is this throwing an exception when I try to save the attachment from Outlook?

Question:

I am trying to iterate through the contents of a subfolder, and if the message contains an .xlsx attachment, download the attachment to a local directory. I have confirmed all other parts of this program work until that line, which throws an exception each time.

I am running the following code in a Jupyter notebook through VSCode:

# import libraries
import win32com.client
import re
import os

# set up connection to outlook

path = os.path.expanduser("~\Desktop\SBD_DB")
print(path)

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
target_folder = inbox.Folders['SBD - Productivity'].Folders['Productivity Data Request']
target_folder.Name

messages = target_folder.Items
message = messages.GetLast()

# while True:
x=0
while x < 100:
  try:
    # print(message.subject) # get the subject of the email
    for attachment in message.attachments:
        if 'xlsx' in attachment.FileName: 
            # print("reached")
            attachment.SaveAsFile(os.path.join(path, str(attachment.FileName)))
            print("found excel:", attachment.FileName)
    message = messages.GetPrevious()
    x+=1
  except:
    print("exception")
    message = messages.GetPrevious()
    x+=1
Asked By: Pawtang

||

Answers:

Looks like the following line of code throws an exception at runtime:

attachment.SaveAsFile(os.path.join(path, str(attachment.FileName)))

First, make sure that you deal with an attached file, not a link to the actual file. The Attachment.Type property returns an OlAttachmentType constant indicating the type of the specified object. You are interested in the olByValue value when the attachment is a copy of the original file and can be accessed even if the original file is removed.

Second, you need to make sure that the file path (especially the FileName property) doesn’t contain forbidden symbols, see What characters are forbidden in Windows and Linux directory names? for more information.

Third, make sure that a target folder exists on the disk and points to the local folder. According to the exception message:

 'Cannot save the attachment. Path does not exist. Verify the path is correct.'

That is it. Try to open the folder manually first, according to the error message the path doesn’t exist. Before calling the SaveAsFile method you need to created the target folder or make sure it exists before.

Answered By: Eugene Astafiev