我尝试使用win32com遍历Outlook中的特定文件夹时,以字符串形式返回遇到的任何附件的文件名。当附件不是'Outlook项目'(https://i.imgur.com/UauktNV.png)以外的其他文件时,以字符串形式返回文件名时,我没有任何问题-不幸的是,这是我实际上必须处理的唯一附件类型。我面临的错误如下...
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)
我的代码如下
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
如果我打印“附件”,我也会得到<COMObject <unknown>>
。这使我相信我可能不会从属性对象层次结构中接近该对象,如此处https://docs.microsoft.com/en-us/office/vba/api/outlook.attachment所示,尽管AFAIK似乎是正确的,但可能是为什么我尝试注释attachment
和< em>然后打印name
,我得到了错误AttributeError: <unknown>.FileName
。
注意:我的问题与此类似-> Filename is returned as null when an outlook item (.msg file) is added as attachment to an outlook email sent
但是,我什至无法打印一个空值,而且我尝试读取的附件仍然具有文件名。
谢谢。
答案 0 :(得分:0)
COM error in downloading attachment from outlook through win32com
^这就是解决方案。我试图返回最初并不总是存在的附件。
下面是新代码
attachment = message.Attachments
count = message.Attachments.Count
if count > 0:
attachment = attachment.Item(1)
print("[+] Begin attachment")
print(attachment)
print("[-] End attachment")