How to trigger Python script when sending an Outlook email?

Question:

I would like to trigger a Python script when I send an email through Outlook.

So far I have only seen solutions to trigger a Python script when an email is received but not when sending an email.

Asked By: ronmakh

||

Answers:

The ItemSend event of the Outlook Application class is fired for outgoing items, whenever an Microsoft Outlook item is sent, either by the user through an Inspector (before the inspector is closed, but after the user clicks the Send button) or when the Send method for an Outlook item, such as MailItem, is used in a program.

Be aware, Outlook should be opened and connected to your code (a valid Application instance retrieved). The event is not fired when Outlook is not running.

Answered By: Eugene Astafiev

Try ItemSend event

import pythoncom
from win32com.client import DispatchWithEvents


# Event handler class for outlook events
class OutlookEvent(object):
    @staticmethod
    def OnItemSend(item, cancel):
        """
        Name    Required/Optional   Data type   Description
        Item    Required            Object      The item being sent.
        Cancel  Required            Boolean     
        
        cancel = False when the event occurs. 
        If the event procedure sets this argument to True, 
        the send action is not completed and the inspector is left open.
        """
        print(f'The item being sent = {item.Subject}')
            # # do something with Item


if __name__ == "__main__":
    Outlook = DispatchWithEvents("outlook.Application", OutlookEvent)
    pythoncom.PumpMessages()
    
Answered By: 0m3r