Home > Software engineering >  trigger an action on new email using the python win32com module with outlook
trigger an action on new email using the python win32com module with outlook

Time:06-22

is it possible to trigger some action when a new mail arrives in outlook using the python module win32com

pseudocode

 while 1
        if a mail arrives
            do x

Edit: I'm not allowed to use "run script" rule

CodePudding user response:

use DispatchWithEvents function for Outlook NewMailEx event

Example

import pythoncom
from win32com.client import DispatchWithEvents


# Event handler class for Outlook events
class OutlookEventHandler(object):
    @staticmethod
    def OnNewMailEx(EntryIDCollection):
        for ID in EntryIDCollection.split(","):
            item = Outlook.Session.GetItemFromID(ID)
            # check item class, 43 = MailItem
            if item.Class == 43:
                print(" Subj: "   item.Subject)


if __name__ == "__main__":
    Outlook = DispatchWithEvents("Outlook.Application", OutlookEventHandler)
    olNs = Outlook.GetNamespace("MAPI")
    Inbox = olNs.GetDefaultFolder(6)
    pythoncom.PumpMessages()

CodePudding user response:

You can create a rule that runs a VBA script. That script can do anything you want it to do, including running your Python code.

  • Related