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

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.

Related

how to use win32com.mapi get new email from outlook in python?

I wanna get a message when a new email into outlook.
I try to use python.
I can find that folders,but can't find the way to get the number of new email.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
accounts = win32com.client.Dispatch("Outlook.Application").Session.Accounts;
inbox = outlook.Folders(accounts[0].DeliveryStore.DisplayName)
for obj in inbox.Folders: #how to know how many new email in this dir?
try:
if hasattr(obj, "__str__"):
dirName = obj.__str__() #as some new email in this obj.
for message in obj.items: # how to know this email is not be read ?
subject = sender = ''
if hasattr(message, "Subject"):
subject = message.Subject
if hasattr(message, "SenderName"):
sender = message.SenderName
print(sender, subject)
except Exception as e:
print(f"i:{obj.__str__()}")
and where can I learn win32com.mapi?
I wanna know what func can I use in mapi.
give me some info,please~
so much thanks!
Are you looking for unread messages? Use MAPIFolder.Items.Restrict("[Unread] = true") to retrieve Items collection with the restriction applied.

How to save MS Outlook attachments from specific sender and date using Python

I am a bit new to coding and I am trying to understand how to get Python to save MS Outlook attachments from a specific sender. I currently receive the same email from the same person each day regarding data that I need to save to a specific folder. Below are the requirements I am trying to meet:
I want to open MS Outlook and search for specific sender
I want to make sure that the email that I am opening from the specific sender is the most current date
I want to save all attached files from this sender to a specific folder on my desktop
I have seen some posts on using win32com.client but have not had much luck getting it to work with MS Outlook. I will attach some code I have tried below. I appreciate any feedback!
import win32com.client
outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox=outlook.GetDefaultFolder(6)
messages=inbox.Items
for message in messages:
attachments = message.attachments
for attachment in attachments:
pass
You almost got it, add filter to the sender email address
import win32com.client
Outlook = win32com.client.Dispatch("Outlook.Application")
olNs = Outlook.GetNamespace("MAPI")
Inbox = olNs.GetDefaultFolder(6)
Filter = "[SenderEmailAddress] = '0m3r#email.com'"
Items = Inbox.Items.Restrict(Filter)
Item = Items.GetFirst()
for attachment in Item.Attachments:
print(attachment.FileName)
attachment.SaveAsFile(r"C:\path\to\my\folder\Attachment.xlsx")
Python 3.8 on windows
def saveAttachments(email:object):
for attachedFile in email.Attachments: #iterate over the attachments
try:
filename = attachedFile.FileName
attachedFile.SaveAsFile("C:\\EmailAttachmentDump\\"+filename) #Filepath must exist already
except Exception as e:
print(e)
for mailItem in inbox.Items:
#Here you just need to bould your own conditions
if mailItem.Sender == "x" or mailItem.SenderName == "y":
saveAttachments(mailItem)
The actual conditions you can change to your liking. I would recommend referring to the Object model for Outlook MailItem objects: https://learn.microsoft.com/en-gb/office/vba/api/outlook.mailitem
Specifically its Properties

Read outlook 365 email using python and get sender email (exchange or SMTP)

I have a python script to read emails from the inbox folder in outlook, and retrive the email id of the sender.
outlook = win32com.client.Dispatch(
"Outlook.Application").GetNamespace("MAPI")
print("Reading Mails")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
for msg in messages:
print(msg.SenderEmailAddress)
prints '/o=ExchangeLabs/ou=Exchange Administrative Group (FYDIBONPDLT)/cn=Recipients/cn=80cf94566sdfhve819ddaede72dc842-Sender Name'
instead of a email ID that the script can work on.
The printed statement is actually a Exchange address. This returned when the email is received from within a company. The best way to handle this is to identify if the SenderEmailType is Exchange.
if (msg.SenderEmailType = "EX"):
print(msg.Sender.GetExchangeUser().PrimarySmtpAddress)
else #email type SMTP
print(msg.SenderEmailAddress)

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)

Python Outlook headers

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.

Categories