如何将电子邮件附件保存在 Python 或告诉我没有附件?

How to save email attachment in Python or tell me there is no attachment?

这是下面的代码我是运行...我在保存附件时遇到问题--

import win32com.client
import os

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6)

messages = inbox.Items
message = messages.GetFirst()
body_content = message.body
attachment = message.attachments

attachment.SaveASFile(os.getcwd() + '\' + attachment.FileName)

print (body_content)

这是我遇到的错误:

Traceback (most recent call last):
  File "C:/Users/BregmanM/PycharmProjects/test/TkinterApp/test13.py", line 13, in <module>
    attachment.SaveASFile(os.getcwd() + '\' + attachment.FileName)
  File "C:\Users\BregmanM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\win32com\client\dynamic.py", line 527, in __getattr__
    raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.SaveASFile

我该如何解决这个错误?

附件变量指向附件集合(注意复数与单数)。您需要遍历附件集合中的项目,并为每个附件对象调用 SaveAsFile。

其次,您假设 Items.GetLast 指向最新消息。那不是真的。在您实际调用 Items.Sort() 之前,项目集合不会以任何方式排序。