0

I have the following which calls a Python script after receiving any email:

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)

Shell "C:\Program Files\Python310\python.exe C:\Users\lradico\Desktop\WWP\waites_slack.py"
End Sub

I want it to only trigger if the new email has a few specific words in the subject. The subject will be different every time, but a few words in it will remain the same.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
L Radico
  • 23
  • 4

2 Answers2

1
If InStr(1, email.subject, yourString) > 0 Then
    'code to execute if mail has yourString in subject (for more than 1 String just nest Ifs or use And
End If
Lord-JulianXLII
  • 1,031
  • 1
  • 6
  • 16
0

First of all, there is no need to handle the NewMail and NewMailEx events of the Application class separately. You need to run the python script only if items with specific keywords are detected in the code. For that task you need to handle the NewMailEx event where you could check the Subject property and then if required run the script:

Option Explicit

Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
  Dim entry As Object
  Set entry = Me.GetNamespace("MAPI").GetItemFromID(EntryIDCollection)
  
  If Not TypeOf entry Is MailItem Then Exit Sub

  ' A textual comparison starting at position 1
  If InStr(1, entry.subject, keyword) > 0 Then
    Shell "C:\Program Files\Python310\python.exe C:\Users\lradico\Desktop\WWP\waites_slack.py"
  End If
  
End Sub

The easiest solution is to use the InStr function which returns an integer specifying the position of the first occurrence of one string within another.

Also you may consider using regular expressions to apply more complex patterns to the subject string, see RegEx in Outlook VBA to get text from Email Body for more information and code samples.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45