Search code examples
pythonoutlookactivexwin32comdispatch

Monitor for category/folder change in Outlook with Python


I am looking to build a Python tool that monitors category and folder changes in Outlook.

So far I managed to hook into the OnNewMailEx event and monitor for all incoming emails using the code below:

import win32com.client
import pythoncom
import re

def getPath(folder, path=[]):
    if folder.parent.parent.parent:
        path.append(folder.name)
        getPath(folder.parent, path)
    return "\\".join(reversed(path))

class Handler_Class(object):
    def OnNewMailEx(self, receivedItemsIDs):
        for ID in receivedItemsIDs.split(","):
            mailItem = outlook.Session.GetItemFromID(ID)
            if re.search("(TS)|(ST)", mailItem.Parent.FolderPath) != None:
                print "Subj: " + mailItem.Subject
                print "Time: " + str(mailItem.ReceivedTime)
                print "Parent: " + str(mailItem.Parent.FolderPath)
                # print "Body: " + mailItem.Body.encode( 'ascii', 'ignore' )
                print "========"

outlook = win32com.client.DispatchWithEvents("Outlook.Application", Handler_Class)
pythoncom.PumpMessages()

Now I am trying to expand this to hook into the events that monitor category changes. MSDN has this on the subject: https://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.olkcategory.aspx

However, when I tried the code below (with the correct names from http://svn.cy55.de/changeset/1896?format=diff&new=1896), nothing happens:

class Handler_Class(object):
    def OnChange(self):
        print("Hook successful!")    

category = win32com.client.DispatchWithEvents("Outlook.OlkCategoryStrip", Handler_Class)
pythoncom.PumpMessages()

Furthermore, I can't find any documentation for events that monitor if an email was moved to a different folder. Any ideas??


Solution

  • The OlkCategory interface you are referencing is tied to the Categories control that is used in Outlook Form Regions; it's useless by itself. To monitor property changes (including Categories) of an item you need to hook into the MailItem.PropertyChange event: https://msdn.microsoft.com/en-us/library/ff866739.aspx.

    To monitor when an item is added to a folder you need to trap the Items.ItemAdd event for any given folder: https://msdn.microsoft.com/en-us/library/ff869609.aspx.