通过Win32com从Outlook下载附件时出现COM错误 [英] COM error in downloading attachment from outlook through win32com

查看:250
本文介绍了通过Win32com从Outlook下载附件时出现COM错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

尝试从Outlook下载附件时出现错误

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) 

推荐答案

您的代码假定收件箱"文件夹中的每封邮件都至少具有一个附件.该假设显然是无效的.

You code assumes every message in the Inbox folder has at least one attachment. That assumption is clearly invalid.

请检查Attachments.Count > 0或实际上遍历附件集合,而不是简单地检索邮件的第一个附件(attachments.Item(1))是否包含附件.

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.

还请记住,messages.GetFirst()将返回一些随机项,因为您绝不会以任何方式对集合进行排序.您很可能会收到最早创建的消息.不要假设Outlook显示的邮件的排序顺序与您的邮件排序相同.

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.

这篇关于通过Win32com从Outlook下载附件时出现COM错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆