COM error in downloading attachment from outlook through win32com

℡╲_俬逩灬. 提交于 2019-12-24 10:45:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!