1

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

0m3r
  • 12,286
  • 15
  • 35
  • 71

2 Answers2

4

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()

Items.ItemAdd event (Outlook)

Example

import pythoncom
from win32com.client import DispatchWithEvents, Dispatch


# Event handler class for outlook events
class OutlookEvent(object):
    @staticmethod
    def OnItemAdd(item):
        """ Name    Required/Optional   Data type   Description
            Item    Required            Object      The item that was added."""
        print(f'The item that was added = {item.Subject}')


if __name__ == "__main__":
    outlook = Dispatch("outlook.Application")
    olNs = outlook.GetNamespace("MAPI")
    inbox = olNs.GetDefaultFolder(6)

    event = DispatchWithEvents(inbox.Items, OutlookEvent)
    pythoncom.PumpMessages()
0m3r
  • 12,286
  • 15
  • 35
  • 71
  • 1
    This is the way to do it. One variation is to use `win32com.gencache.EnsureDispatch()` then `WithEvents()` as a separate call. This will cause gen_py to create the constants, so you can write `win32com.client.constants.olMail` rather than 43. Would then also need to cast `item` using `CastTo(IMailItem)` with this approach. A side-effect is that it also enforces case-sensitivity on methods/properties, which can prevent unexpected behaviour down the line. – DS_London Jun 22 '22 at 09:17
  • https://stackoverflow.com/a/75000015/4539709 – 0m3r Jan 07 '23 at 01:14
0

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.

Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78