'Parse the body of attachment in outlook mail with MAPI Python
I am using win32com for parsing emails in my outlook, how can I parse the contents of attachment in mail.
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
accounts= win32com.client.Dispatch("Outlook.Application").Session.Accounts
inbox = outlook.Folders(accounts['<Account-Name>'].DeliveryStore.DisplayName)
messages = inbox.Folders['Inbox'].Items
if len(messages) > 0:
for message2 in messages:
title = message2.Subject
if title == '<Title-of-mail>':
attachment = message2.Attachments.Item(1)
print(attachment)
print(message2.Body)
# print(attachment.Body) //Error
I want to get the contents of attachment, not able to find any proper documentation for this. Any help in guiding me to correct direction is highly appreciated.
Solution 1:[1]
Firstly, you might want to retrieve the Inbox using
accounts['<Account-Name>'].DeliveryStore.GetDefaultFolder(olFolderInbox)
Secondly, looping through all messages in a folder is a terrible idea - use Items.Find/FindNext
or Items.Restrict
with a restriction on the Subject property..
Thirdly, Outlook would not let you directly access attachment contents, you would need to save the attachment as a file (Attachment.SaveAsFile
), and then read the file contents. If you want to access attachment contents directly, you can use Redemption (I am its author) - it exposes Attachment / RDOAttachment.AsText
/ AsArray
/ AsStream
properties.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |