0

I am working on a script that is sending all attachments of the e-mails I open to a specific path. To summarize, the main code I am using would be the following:

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem('path to .msg i want to open')
attachments = msg.Attachments
        attachment_no = len([x for x in attachments])
        for x in range(1, attachment_no):
            attachment = attachments.Item(x)
            attachment.SaveASFile('path' + str(attachment))

It works well, I do not get any errors, but not as expected. Instead of saving the attached files, let's say PDFs, the script is saving the files that are embedded in the body of the e-mail, i.e. pictures, the sender signature and so on. So instead of attached PDFs I get some .jpg files.

What I am doing wrong here?

Thank you in advance!

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45

3 Answers3

0

Try

    attachments = msg.Attachments
    for x in range(1, attachments.Count):
        attachment = attachments.Item(x)
        attachment.SaveAsFile('path' + attachment.FileName)
Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78
0

If you need to distinguish hidden attachments (embedded images) and save only attached files you need to check the PR_ATTACH_CONTENT_ID property value and try to search this value in the message body of the email. That is because attachments may always have the MIME content id set (PR_ATTACH_CONTENT_ID), for example, messages from Lotus Notes always have that header. See Distinguish visible and invisible attachments with Outlook VBA for more information.

PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001F"
 
for x in range(1, attachment_no):
      attachment = attachments.Item(x)
      pa = attachment.propertyAccessor
      cid = pa.GetProperty(PR_ATTACH_CONTENT_ID)

      // search the cid value in the message body

      attachment.SaveASFile('path' + attachment.FileName) 
       

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
0

Managed to figured it out.

attachments = msg.Attachments
        attachment_no = len([x for x in attachments])
        for x in range(1, attachment_no + 1):
            attachment = attachments.Item(x)
            attachment.SaveASFile('path' + str(attachment))

Added a "+ 1" after the number of attachments. This is logical because a range from 1 to 3 means that only attachments 1 and 2 are saved. It was misleading for me because if you have only one attachment in the e-mail only the "body attachments" are saved, not the file attachment itself. I was thinking that the files are not saved at all but actually only the last attachment is not saved due to the wrong "for x in range" line. So in order to save all attachments the total number in range should be increased by one.