Reputation: 15
I want to use the below code to search for all emails that came into "MyInbox" today, with a subject beginning with "Company UK Cash Movement...". Usually the emails will come in with that exact subject but the ending can change. In VBA i would use a wildcard *, but I'm unsure how to implement this in python.
Ive also not yet figured out how to only search the emails received today.
import win32com.client
import datetime
import re
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders("MyInbox")
inbox = folder.Folders.Item("Inbox")
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
for message in messages:
if message.subject == 'Company UK Cash Movement.+':
print("Found message")
else:
print("not found")
Upvotes: 0
Views: 10302
Reputation: 66215
Don't loop though all items in a folder. use Items.Find/FindNext
or Items.Restrict
.
You can pass the following query to Items.Restrict (it will return another Items collection with the marches).
You can create a query on the PR_NORMALIZED_SUBJECT property (DASL name http://schemas.microsoft.com/mapi/proptag/0x0E1D001F
). Note that a restriction on Subject won't work since it is not indexed (only normalized subject is).
set matches = inbox.Items.Restrict("@SQL=""http://schemas.microsoft.com/mapi/proptag/0x0E1D001F"" like '%Company UK Cash Movement%' ")
MsgBox matches.Count
Upvotes: 1
Reputation: 2060
Try .startswith()
:
import win32com.client
import datetime
import re
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders("MyInbox")
inbox = folder.Folders.Item("Inbox")
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
for message in messages:
if message.subject.startswith('Company UK Cash Movement'):
print("Found message")
else:
print("not found")
Upvotes: 1