0

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
Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
Pawtang
  • 35
  • 7
  • What exception are you getting? – takendarkk Nov 21 '22 at 22:42
  • @takendarkk I don't know, I am not getting any error code, it just executes the "except" part of the "try-except" block and then continues to the next iteration. If I remove the attachment.SaveAsFile line, it executes the "try" portion every time with no exceptions. – Pawtang Nov 21 '22 at 22:45
  • Your except block is throwing away the exception for some reason. You should get it and log it. – takendarkk Nov 21 '22 at 22:52
  • @takendarkk nice, I did not know about logger. ERROR:root:message Traceback (most recent call last): File "C:\Users\bdibuz01\AppData\Local\Temp\ipykernel_23704\3137415355.py", line 28, in attachment.SaveAsFile(os.path.join(path, str(attachment.FileName))) File ">", line 2, in SaveAsFile pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Cannot save the attachment. Path does not exist. Verify the path is correct.', None, 0, -2147024893), None) ERROR:root:message – Pawtang Nov 21 '22 at 23:03
  • Are you sure the target folder exists on the disk? Did you try to create the folder before calling the SaveAsFile method? – Eugene Astafiev Nov 21 '22 at 23:06

1 Answers1

1

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.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • 1
    Bingo - I assumed it would create & move into the directory when the path was specified, but I had to manually create the folder first. Thanks. – Pawtang Nov 21 '22 at 23:11