COM error in downloading attachment from outlook t

2019-07-29 03:49发布

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条回答
再贱就再见
2楼-- · 2019-07-29 04:28

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.

查看更多
登录 后发表回答