简体   繁体   中英

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

This is the following code I am running... I am having trouble saving the 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)

This is the error I am getting:

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

How can I go about fixing this error?

attachment variable points to the Attachments collection (note plural vs singular). You need to loop through the items in the Attachments collection, and for each Attachment object call SaveAsFile.

Secondly, you are assuming that Items.GetLast points to the latest message. That is not true. Items collection is not sorted in any way until you actually call Items.Sort().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM