Email outlook getting body - python

I am using Microsoft outlook.In outlook I will be having plenty of mails.My task is to read the outlook mail and store that data in an array or any file.I am able to read body of the mail which consists of both text and images. I am able to read the text in the mail but if there is any images in the mail I can't able to read the images. I am using python. Please say me how to get images and text from that body.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print(body_content)

The Body property returns a plain text string that represents the message body. Instead, you can use the following ways:
The HTMLBody property - a string representing the HTML body of the specified item.
The Word editor - the Microsoft Word Document Object Model of the message being displayed. The WordEditor property of the Inspector class returns an instance of the Document class from the Word object model which you can use to set up the message body.
You can read more about all these ways in the Chapter 17: Working with Item Bodies article. It is up to you which way is to choose to deal with the message body.
You can find all img elements in the message body. Be aware, embedded images are stored as attachments in the message. To find them you can use the following code (C#):
Outlook.MailtItem mailItem;
foreach (Outlook.Attachment attachment in mailItem.Attachments)
{
bool attachmentIsInline = false;
string fileName = attachment.FileName;
if (mailItem.HTMLBody.Contains(fileName))
{
attachmentIsInline = true;
}
}
Basically, you just need to find whether a message body contains an attached file's name. Take a look at the following threads for more information:
distinguish between inline images and other attachments in outlook message
How to know if attachment is a signature in an Outlook email

Related

python script that checks column value in excel sheet and sends mail to that particular person in outlook by the name of distribution list(DL)

I want to write a python script that checks a column value in excel sheet and sends mail to that particular person in outlook by the name of distribution list(DL). I am unable to fetch DL with the following code. Please help me on this.
More details:
The sender should be the DL name i.e., DL IQWDL SSDBU NEC Global xyzglobal.abcbu#pqr.com
The receiver should an individual name i.e., rahul.kumar#pqr.com
Code:
import win32com.client as win32
import pandas as pd
#Read the excel file
xl = pd.read_excel('C:\\Users\\rahulk\\Downloads\\corepy\\excel_report.xlsx')
#Select the email addresses from a specific column in the Excel file
email_addresses = xl['Email'].tolist()
#Connect to Outlook and get the distribution list your text
outlook = win32.gencache.EnsureDispatch("Outlook.Application")
dl = outlook.Session.GetDefaultFolder(win32.constants.olFolderContacts).GetDistributionListFromID("xyzglobal.abcbu#pqr.com")
#Loop through the email addresses and send the email your text
for email_address in email_addresses:
email = outlook.CreateItem(win32.constants.olMailItem)
email.To = email_address
email.Subject = "Email Subject"
email.Body = "Email Body"
email.SentOnBehalfOfName = dl.DLName
email.Send()
#Release the Outlook instance
outlook = None
The Outlook object model doesn't provide the GetDistributionListFromID method for the Folder class. To find an item in the folder you need to use the Find/FindNext or Restrict methods of the Items class. Read more about these methods in the articles I wrote for the technical blog:
How To: Retrieve Outlook Contact items using Restrict method
How To: Use Find and FindNext to retrieve Outlook Contact items
Be aware, the To property expects a semicolon-delimited string list of display names for the To recipients for the Outlook item. Otherwise, I'd suggest using the Recipeints.Add method for adding recipients. See How To: Fill TO,CC and BCC fields in Outlook programmatically for more information.

Cannot get the image position in the body from Outlook Python API

I need some help, I am currently trying to do some scripting to automatize some tasks. I would like to fetch the received mail and send the body somewhere.
For that I am using win32.com with the outlook API.
But the issue is that if there is image in the body of the mail. I can't fetch it with the initial body. I Thought about using attachment, which is working but in the end, I have images and the body. But in the body I don't have the image position information... So I can only send the images and cannot set them correctly. Which can be difficult to understand if there is a lot of images...
So far the code looks like something like this :
import os
import win32com.client
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
inbox = mapi.GetDefaultFolder(6)
messages = inbox.Items
message = messages[len(messages) - 1]
body = message.body
attachments = message.attachments
attachment = attachments[0]
file_name = attachment.filename
path = "D:\\Documents\\tmp"
attachment.SaveAsFile(path + os.sep + attachment.FileName)
Do you have any help on this ?
Thanks for your help :)
PS : Do you know where I can find the Python documentation for outlook API, I just find the Rest API one and there is some difference from both. Or if we can get the source code to check directly.
In the message body you may check for <img/> tags. If any of them contains this tag with a file name prefixed with cid: string, for example:
<img src=cid:Filename/>
Then you deal with an embedded image which can be found in attached files.
Also you may check the PR_ATTACH_CONTENT_ID property on the attached files in the following way:
Const PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001F"
Function IsEmbedded(Att As Attachment) As Boolean
Dim PropAccessor As PropertyAccessor
Set PropAccessor = Att.PropertyAccessor
IsEmbedded = (PropAccessor.GetProperty(PR_ATTACH_CONTENT_ID) <> "")
End Function
The PropertyAccessor can help you to deal with low-level MAPI properties in Outlook.

Outlook Check Message Type

I’m using a python package called win32com to directly access and scrape the inboxes from Outlook. As the Outlook application is setup to have multiple email accounts, I’ve had to adapt my code to read messages from multiple email accounts. However, the messages contains calendar invites and I just want email messages to be scraped. Is there a way to filter the messages based on type?
Outlook = client.Dispatch(“Outlook.Application”).GetNameSpace(“MAPI”)
Messages = outlook.Folders(“test#test.com).Folders(“Inbox”)
For msg in messages:
#Do Something
Yes, you need to check if the object is of type OlObjectClass.olMail, which is represented by value 43. You can check all enumerations here.
Outlook = client.Dispatch(“Outlook.Application”).GetNameSpace(“MAPI”)
Messages = outlook.Folders(“test#test.com).Folders(“Inbox”)
for msg in messages:
if msg.Class == 43: # OlObjectClass.olMail
#Do Something

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

How to attach a calendar invite to SES send_raw_email?

I use send_raw_email to send emails with HTML content and file attachments. How do I insert an ical/ics invite to the email?
I use icalendar to generate ics content.
This is what I came up with so far, but it shows in Gmail as a file attachment.
if calendar_reminder_date:
cal = Calendar()
cal.add('prodid', '-//My calendar product//mxm.dk//')
cal.add('version', '2.0')
cal.add('calscale', 'GREGORIAN')
cal.add('method', 'REQUEST')
event = Event()
event['dtstart'] = calendar_reminder_date.strftime("%Y%m%dT%H%M%SZ")
event['dtstamp'] = calendar_reminder_date.strftime("%Y%m%dT%H%M%SZ")
event['summary'] = 'Python meeting about calendaring'
cal.add_component(event)
attachment_part = MIMEText(cal.to_ical())
print repr(cal.to_ical())
del attachment_part['Content-Type']
attachment_part.add_header('Content-Type', 'text/calendar', name='invite.ics')
attachment_part.add_header('Content-Disposition', 'attachment', filename='invite.ics')
msg.attach(attachment_part)
Hard to tell without seeing the actual full MIME message as received on the Google side but there are definitely several things missing here:
a calendar REQUEST must have an ORGANIZER property, as well as at least one ATTENDEE property with a value corresponding to the email address of the gmail user (prefixed with a mailto:).
your content-type is missing a METHOD=REQUEST parameter and you probably do not want to set any content-disposition.
See also Multipart email with text and calendar: Outlook doesn't recognize ics

Categories

Resources