sgerbhctim
sgerbhctim

Reputation: 3640

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?

Upvotes: 0

Views: 2665

Answers (1)

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66356

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().

Upvotes: 2

Related Questions