b111y
b111y

Reputation: 41

Unable to read 'Outlook item' object as attachment with win32com

I am attempting to return the filename of any attachment I come across as a string when iterating though a specific folder in Outlook using win32com. I have no issues when returning the filename as a string when the attachment is anything other than a 'Outlook item' ( https://i.sstatic.net/cVK4Z.png ) -- Unfortunately, this is the only type of attachment I actually have to process. The error I am facing is below...

  File "C:/Users/bob/PycharmProjects/program/program.py", line 76, in handle_email
    attachment = attachments.Item(1)
  File "<COMObject <unknown>>", line 2, in Item
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Array index out of bounds.', None, 0, -2147352567), None)

My code is as follows

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
root_folder = outlook.Folders.Item(1)
test = root_folder.Folders['test']
messages = test.items

attachments = message.Attachments
attachment = attachments.Item(1)
name = attachment.FileName

If I print 'attachments' I get <COMObject <unknown>> as well. Which led me to believe I am possibly not approaching the object from the property object hierarchy, as referenced here https://learn.microsoft.com/en-us/office/vba/api/outlook.attachment although AFAIK it seems to be correct but is probably why when I try to comment out attachment and then print name I get the error AttributeError: <unknown>.FileName.

Note: My question is similar to this one --> Filename is returned as null when an outlook item (.msg file) is added as attachment to an outlook email sent

But, I am unable to get far enough to even print a null value and the attachments I am trying to read have filenames anyway.

Thank you.

Upvotes: 3

Views: 2796

Answers (1)

b111y
b111y

Reputation: 41

COM error in downloading attachment from outlook through win32com

^ This was the solution. I was trying to return attachments that didn't always exist in the first place.

New code is below

attachment = message.Attachments
count = message.Attachments.Count
if count > 0:
    attachment = attachment.Item(1)
    print("[+] Begin attachment")
    print(attachment)
    print("[-] End attachment")

Upvotes: 1

Related Questions