Search code examples
pythonoutlookemail-attachmentswin32comoffice-automation

Wincom32 Safetly Restrict email in group outlook before searching on subject


I have the following Python code which loops through emails in a group shared outlook mailbox and then saves attachments. However this will do a scan of the entire inbox.

I have seen in other answers that this is understandably a terrible idea although the third answer isn't clear to me how to go about it:

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

I wish to restrict the inbox to only emails sent by a specific person with keywords in the subject. My pseudo-code is below which i have been working on today

# new outlook object
import win32com.client as win32com
outlook = win32com.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders.Item("[email protected]").Folders.Item("Inbox")

# Here we apply the filter above and then print out the attachment name
# After the file is downloaded we mark the mail as read
Items = inbox.Items
for item in Items:
    
# Check if the item is unread and has the desired sender and subject
    if item.UnRead and item.Sender.GetExchangeUser().PrimarySmtpAddress == "[email protected]" and item.subject.contains("FM1, Football, results"):
        # Loop through all the attachments in the item
        for attachment in item.Attachments:
            try:
                save_path = (os.getcwd() + "\\email_attachments\\" +
                             attachment.FileName)

                # Save the File and mark the email as unread
                attachment.SaveAsFile(save_path)
                item.UnRead = False

            except:
                print('Error:', attachment.FileName)

Solution

  • You are on the right avenue - use the Find/FindNext or Restrict methods of the Items class, they allow getting items that correspond to the specified search criteria only. You can read more about these methods in the articles that I wrote for the technical blog:

    DASL supports the matching of prefixes, phrases, and substrings in a string property using content indexer keywords ci_startswith and ci_phrasematch, and the keyword like. If a store is indexed, searching with content indexer keywords is more efficient than with like. If your search scenarios include substring matching (which content indexer keywords don't support), use the like keyword in a DASL query. For example, to search items with a specific keyword in the Subject line you can use the following search criteria string (VBA syntax):

    criteria = "@SQL=" & Chr(34) _ 
    & "urn:schemas:httpmail:subject" & Chr(34) _ 
    & " ci_phrasematch 'question'" 
    

    where Chr is the VBA function and returns the character from the ASCII table. For example, Chr(34) returns the 34th character, which is the sign.

    I wish to restrict the inbox to only emails sent by a specific person with keywords in the subject.

    You may combine conditions using AND keyword in the search string.

    To search for items. For example, to search for items from a specific email address you can use:

    criteria = "@SQL=" & Chr(34) _ 
    & "urn:schemas:httpmail:senderemail" & Chr(34) _ 
    & " ci_phrasematch '[email protected]'"