简体   繁体   中英

Python code to filter mails based on email and subject

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")

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 'eugene@astafiev.com'"

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 'eugene@astafiev.com'" 

You may also consider using the AdvacedSearch method of the Outlook Application class. The key benefits of using the AdvancedSearch method in Outlook are:

  • The search is performed in another thread. You don't need to run another thread manually since the AdvancedSearch method runs it automatically in the background.
  • Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, ie beyond the scope of a certain folder. The Restrict and Find / FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).
  • Full support for DASL queries (custom properties can be used for searching too). To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).
  • You can stop the search process at any moment using the Stop method of the Search class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM