'Trying to read outlook attachments with python
I am working on a script that reads emails from Outlook using Python, I wanted to know if there is any way to read the attachments without downloading them, for example open an attached pdf and capture it in a DataFrame.
This is my code:
import win32com.client
import os
mail ='[email protected]'
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
stores = outlook.Stores
for store in stores:
if store.DisplayName == mail:
inbox = store.GetDefaultFolder(6)
messages = inbox.Items
for attachment in messages[1].Attachments:
print(attachment)
Solution 1:[1]
any way to read the attachments without downloading them
No. You need to save the file on the disk first. Then you can open the just saved file on the disk and process it in your application.
# Creating an object for the message.Attachments.
attachment = message.Attachments
# To check which item is selected among the attacments.
print (message.Attachments.Item(which_item))
# To iterate through email items using message.Attachments object.
for attachment in message.Attachments:
# To save the perticular attachment at the desired location in your hard disk.
attachment.SaveAsFile(os.path.join("D:\Script\Attachments",file_name))
Solution 2:[2]
Outlook Object Model does not provide access to the attachment binary data. The best you can do is save the attachment as a temporary file (Attachment.SaveAsFile
), read file contents, delete the file.
On the MAPI level however (C++ or Delphi only), attachments can only be accessed as blobs or as IStream
(or IStorage
) interface; MAPI knows nothing about files. If using Redemption (I am its author) is an option, it provides access to the attachment data through the AsText
/ AsArray
/ EmbeddedMsg
/ OleStorage
/ AsStream
properties - see https://www.dimastr.com/redemption/RDOAttachment.htm and https://www.dimastr.com/redemption/safe_Attachment.htm
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 | Eugene Astafiev |
Solution 2 |