问题
import win32com.client
import os
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetFirst()
attachments = message.Attachments
for i in messages:
if(i.UnRead==True):
attachment = attachments.Item(1)
attachment.SaveASFile(os.getcwd() + '\\' + str(attachment))
else:
pass
I am getting below error when trying to download the attachment from outlook
Error: com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Array index out of bounds.', None, 0, -2147352567), None)
回答1:
You code assumes every message in the Inbox folder has at least one attachment. That assumption is clearly invalid.
Either check that Attachments.Count > 0
or actually loop over the attachments collection instead of simply retrieving the very first attachment (attachments.Item(1)
) whether the message has attachments or nor.
Also keep in mind messages.GetFirst()
will return some random item since you never sort the collection in any way. Most likely you will get the oldest created message. Do not assume that the sort order of the messages shown by Outlook will be the same as what you have.
来源:https://stackoverflow.com/questions/51748028/com-error-in-downloading-attachment-from-outlook-through-win32com