Reputation: 83
I am trying to write a python code that can help me filter the latest emails based on the Subject and Sender's Email address and then save its body in a txt file and extract its attachments in the current directory.
Here is the code snippet that I've started writing which pulls emails based on subject and extracts only attachments but can anyone help me filter it by the Sender email id and save the body in a txt file as well?
import win32com.client
#other libraries to be used in this script
import os
get_path = os.getcwd()
from datetime import datetime, timedelta
#Open Outlook Application
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
inbox = mapi.GetDefaultFolder(6)
messages = inbox.Items
message2 = messages.GetLast()
subject = message2.Subject
print(subject)
body = message2.body
sender = message2.Sender
print(sender)
attachments = message2.Attachments
for m in messages:
#print(m)
if m.Subject == "Test Mail":
for x in message2.Attachments:
x.SaveASFile(os.path.join(get_path,x.FileName))
print("successfully downloaded attachments")
Upvotes: 0
Views: 1767
Reputation: 49397
can help me filter the latest emails based on the Subject and Sender's Email address
You need to use the Find
/FindNext
or Restrict
methods of the Items class to filter items according your search criteria. They allow dealing with items that correspond to your conditions only. Read more about them in the articles I wrote for the technical blog:
To search items with a specific subject line or keyword you may consider using the following search criteria (in VBA syntax):
criteria = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " ci_phrasematch 'question'"
Or more straight solution is using the DASL syntax:
criteria = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " ci_phrasematch 'question'"
DASL filters perform string equivalence comparison by using the equal (=
) operator. The value of the string property must be equivalent to the comparison string, with the exception of prefixes "RE: " and "FW: ".
In the same way you may filter on the sender email address:
criteria = "@SQL=" & Chr(34) & "urn:schemas:httpmail:senderemail" & Chr(34) & " ci_phrasematch '[email protected]'"
Note, you can use local operators to combine multiple search criteria:
criteria = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " ci_phrasematch 'question' AND " & Chr(34) & "urn:schemas:httpmail:senderemail" & Chr(34) & " ci_phrasematch '[email protected]'"
You may also consider using the AdvacedSearch
method of the Outlook Application
class. The key benefits of using the AdvancedSearch
method in Outlook are:
AdvancedSearch
method runs it automatically in the background.Restrict
and Find
/FindNext
methods can be applied to a particular Items
collection (see the Items
property of the Folder
class in Outlook).IsInstantSearchEnabled
property of the Store
class).Stop
method of the Search
class.Upvotes: 1