Python Outlook headers - python

I got a script to extract Gmailheaders. There is a lot of information to extract.
When I try to extract data from outlook it feels like im getting a small part.
The script I currently got is:
import win32com.client
import re
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetFirst()
rec_time = message.CreationTime
body_content = message.body
while message:
To = message.To
Recipients = message.Recipients
Sender = message.Sender
address = message.Sender.Address
cc = message.CC
Importance = message.Importance
LastModificationTime = message.LastModificationTime
It prints the following fields:
print message.subject
print message.CreationTime
print To
print Sender
print address
print cc
print Importance
print LastModificationTime
Is there just a limit amount of Outlook headers you can extract or?
I've tryed to look on sources like:
https://msdn.microsoft.com/en-us/VBA/Outlook-VBA/articles/mailitem-object-outlook
I am missing important information like sender IP-adresses. Is there anyway of extracting more information without using a 3partytool?
Thanks!
Edit:
Works:
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
for message in messages:
msg = message.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001F")

To see all MIME headers, read the PR_TRANSPORT_MESSAGE_HEADERS MAPI property (DASL name http://schemas.microsoft.com/mapi/proptag/0x007D001F) using MailItem.PropertyAccessor.GetProperty.
You can see that property (as well as all other MAPI and OOM properties) using OutlookSpy (I am its author) - click IMessage button.

Related

Get all emails from outlook inbox using Python and save them into a local folder

I want to save all my email messages from the inbox folder of outlook using Python. I can save the First or the last messages but couldn't understand how to get all the messages of the folder. Hence, I was trying to use a loop to iterate the code for all mails. I have tried to use the following code:
from win32com.client import Dispatch
import os
import re
os.chdir("D:\\emails")
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
print(inbox)
messages = inbox.items
message = messages.GetLast()
name = str(message.subject)
name = re.sub('[^A-Za-z0-9]+', '', name)+'.msg'
for message in messages:
message.SaveAs(os.getcwd()+'//'+name)
This is not giving me any errors, but saving only the last mail, instead of saving all emails. Could you please help me to rectify the code. Thanks.
The problem is below
message = messages.GetLast()
name = str(message.subject)
and
message.SaveAs(os.getcwd()+'//'+name)
You calculate the name once (before the loop) and use it in the loop.
You need to calculate the name during the loop.
The full code would look something like this.... (I got this answer from balderman)
from win32com.client import Dispatch
import os
import re
os.chdir("D:\\email")
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.items
for message in messages:
message = messages.GetNext()
name = str(message.subject)
name = re.sub('[^A-Za-z0-9]+', '', name)+'.msg'
message.SaveAs(os.getcwd()+'//'+name)

Python get only the most recent Outlook email from a conversation

I'm using Python 3.5 and iterating through Outlook emails searching by message subject, if a condition is met I Save the mail to desktop. I have a problem because as I iterate through mails, I end up getting all the mails in a conversation (Both original mail and all the responses RE:) when i print the subjects that met the if condition.
On the other hand, when i save them to desktop (message.SaveAs) i get only the first email in a conversation.
What i'm interested in is only the most recent mail from a conversation, because if I save that to desktop i also get all the previous responses, so no need for 30 .msg files. Is there a way to do it? Here's my code:
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders("Main")
subfolder = folder.Folders("Incoming")
inbox = subfolder.Folders("folder1")
for x in IDX:
messages = inbox.Items
message = messages.GetFirst()
for _ in itertools.repeat(None, 100):
try:
Subject = message.subject
if x in Subject:
print(Subject)
message.SaveAs(desktop + '\\' + Subject + ".msg", OlSaveAsType['olMSG'])
message = messages.GetNext()
except:
message = messages.GetNext()
Firstly, do not loop through all items in a folder - call Items.Restrict() passing a restriction like " [Subject] = 'you subject' ", then sort the returned Items collection (Items.Sort) on ReceivedTime.

Filtering Outlook Mails on a date range and downloading attachments that satisfy a given sub condition?

i was trying to make a Python script to automate certain aspects in my outlook account in a manner that:
whenever i receive emails with attachments containing a certain SUBJECT they are automatically downloaded to a folder on my system. Here is my code:
import win32com.client
import os
current_path = os.getcwd()
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
for m in messages:
if m.Subject == "TEST MAIL":
print("message body:", m.body)
attachment = messages.Attachments
for x in attachment:
x.SaveASFile(os.path.join(current_path, x.FileName))
The above code doesen't work and throws an exception:pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)
Replace the line
x.SaveASFile(os.path.join(current_path, "Test1.csv"))
with
x.SaveASFile(os.path.join(current_path, x.FileName))

Check whether the email is a reply or response with Python win32com

I am using Python win32com to parse email from outlook . I am able to fetch email from the outlook folder , but I not able to verify whether the email is a reply or response or a forwarded message , I need to check whether the email reiceved is the reply of the previous mail (if yes then find the original mail) or email is the forwarded message. I am using following code to fetch emails from outlook.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.Folders['xyz#xyz.com'].Folders['Inbox'].Folders['abc']
messagesReach = inbox.Items
for message in messagesReach:
if message.Unread==True:
print(message.body)
Hi the header is ConversationID and can be used as message.ConversationID
refer https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.mailitem_properties.aspx
You could try to read the first three characters of the subject, and determine if it has the "Re:"-prefix and therefore is a reply. This should be the case most times.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders["xyz#xyz.com"].Folders["Inbox"].Folders["abc"]
messagesReach = inbox.Items
for message in messagesReach:
if message.Unread == True:
if message.Subject[:3] == "Re:":
print(message.body)

Extract sender's email address from Outlook Exchange in Python using win32

I am trying to extract the sender's email address from outlook 2013 using win32 package in python. There are two kinds of email address type in my Inbox, exchange and smtp. If I try to print the the sender's email address of Exchange type, I am getting this:
/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP(FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=6F467C825619482293F429C0BDE6F1DB-
I have already gone through this link but couldn't find a function through which I can extract the smtp address.
Below is my code:
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
folders = inbox.Folders
for msg in all_inbox:
print msg.SenderEmailAddress
Currently all the Email Address are coming like this:
/O=EXCHANGELABS/OU=EXCHANGE ADMINISTRATIVE GROUP(FYDIBOHF23SPDLT)/CN=RECIPIENTS/CN=6F467C825619482293F429C0BDE6F1DB-
I found a solution to this in VB.net link but don't know how to rewrite the same thing in Python.
Firstly, your code will fail if you have an item other than MailItem in the folder, such as ReportItem, MeetingItem, etc. You need to check that the Class property is 43 (olMail).
Secondly, you need to check the sender email address type and use the SenderEmailAddress property only for the "SMTP" address type. In VB:
for each msg in all_inbox
if msg.Class = 43 Then
if msg.SenderEmailType = "EX" Then
print msg.Sender.GetExchangeUser().PrimarySmtpAddress
Else
print msg.SenderEmailAddress
End If
End If
next
I am just modifying the program given above in Python.
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
folders = inbox.Folders
for msg in all_inbox:
if msg.Class==43:
if msg.SenderEmailType=='EX':
print msg.Sender.GetExchangeUser().PrimarySmtpAddress
else:
print msg.SenderEmailAddress
This will print out all the sender's email address in your inbox folders only.
I had this same problem workin with win32com today. I found the solution here.
Using your example it would be:
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder("6")
all_inbox = inbox.Items
folders = inbox.Folders
for msg in all_inbox:
if msg.Class==43:
if msg.SenderEmailType=='EX':
if msg.Sender.GetExchangeUser() != None:
print msg.Sender.GetExchangeUser().PrimarySmtpAddress
else:
print msg.Sender.GetExchangeDistributionList().PrimarySmtpAddress
else:
print msg.SenderEmailAddress
This should solve the group mail issue.

Categories