I want to check for a particular sender email and process it automatically wherever it arrives
However, there may be some situation where my outlook was restarted, mean while i received mail from sender and marked as unread
For continuous monitor for a new mail for a specific subject i have found the following code
import win32com.client
import pythoncom
import re
class Handler_Class(object):
def OnNewMailEx(self, receivedItemsIDs):
# RecrivedItemIDs is a collection of mail IDs separated by a ",".
# You know, sometimes more than 1 mail is received at the same moment.
for ID in receivedItemsIDs.split(","):
mail = outlook.Session.GetItemFromID(ID)
subject = mail.Subject
print subject
try:
command = re.search(r"%(.*?)%", subject).group(1)
print command # Or whatever code you wish to execute.
except:
pass
outlook = win32com.client.DispatchWithEvents("Outlook.Application",Handler_Class)
#and then an infinit loop that waits from events.
pythoncom.PumpMessages()
Even i want to go through all the unread mails to check whether a mail from a sender has came and process it( if found)
Is there any function to check for unread mails to add within handler_class
Or let me know for any alternate procedure
So if you restart your python script every time your Outlook restart, then add these lines to your code to check unread emails in your Inbox:
Put this code before your definition of
outlook
in your codeEDIT
For me, the code you posted works great until I close Outlook and then even if I reopen it, I don't get anything when a new message is received (see one of my comments). I guess the fact of closing Outlook "unlink" with
pythoncom.PumpMessages()
. Anyway, I come around to do both your checking for unread email in the classHandler_Class
and restart the monitoring in case you restart Outlook.Not sure it is the best way, but it seems to work the way you look for.