Home > Back-end >  Excecute Python Script When A New Outlook Email Arrives
Excecute Python Script When A New Outlook Email Arrives

Time:10-31

I have created a python script, which I want to run every time a new email arrives in outlook Inbox. So far I have written this VBA code:

Sub test()
    Shell "C:\Users\dimitrios\Anaconda3\Scripts\activate.bat & python C:\Users\dimitrios\test\outlookconnnectivity.py"
End Sub

The code calls the outlookConnectivity.py script manually. My problem is how I can do that every time a new email arrives.

I found online some solutions, which i tried, but did not work

CodePudding user response:

Try this

Option Explicit

'This "event" runs whenever there is a new email
Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)

    'Declare as generic Object since we don't know what type of NewMail Item we got yet
    Dim entry As Object
    
    'Me refers to ThisOutlookSession, the GetNamespace is just something we always have to do in outlook
    'GetItemFromID gets the mail object which we need to have to check if its an email
    ' or if we want to do something with it like move it to another folder
    Set entry = Me.GetNamespace("MAPI").GetItemFromID(EntryIDCollection)

    'Exit our event handler if this isn't an email - meetings and notifications also may pop up here
    If Not TypeOf entry Is MailItem Then Exit Sub

    'Call the sub that will handle the new email
    ' passing in the email VBA object in case that is important
    OnNewEmail entry
End Sub


'This Sub will be called whenever the Application_NewMailEx event is triggered with a MailItem
Private Sub OnNewEmail(ByVal email As MailItem)
    MsgBox "Email arrived!" & vbNewLine & _
            email.Subject
            
    'Shell "C:\Users\dimitrios\Anaconda3\Scripts\activate.bat & python C:\Users\dimitrios\test\outlookconnnectivity.py"
End Sub

Add that to the ThisOutlookSession Object

enter image description here


Note there are some caveats about when this event runs - see https://learn.microsoft.com/en-us/office/vba/api/outlook.application.newmailex#remarks

CodePudding user response:

You can call your script in the NewMailEx event handler. This event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. Use the Entry ID returned in the EntryIDCollection string to call the NameSpace.GetItemFromID method and process the item if required.

  • Related