VBA Outlook macro automatically execute on email receipt

VBA - Visual Basic for Application

If you want to process an e-mail directly in Outlook with VBA, for example, move it after it has arrived in the inbox, you can often use Outlook’s rules for this.

However, for special requirements, such as automatic saving of attachments, the Outlook rules quickly reach their limits. This is because a VBA macro is usually used for such functionalities.

In earlier versions of Outlook, it was still possible to set Execute a script in the Outlook rules after receiving a message from. But this has been done away with for security reasons. According to some forums, you can enable this again by going to the registry editor and setting the EnableUnsafeClientMailRules key to 1.

DWORD: EnableUnsafeClientMailRules
Value: 1

With my Outlook365, however, this solution was already no longer available.

Execute macro after email arrives in inbox

Microsoft recommends at this point to rely on the NewMail event or better yet NewMailEx event. This will allow you to process e-mails automatically using VBA when they are received in the inbox. For example, it is possible to automatically print an email attachment if it comes from a certain sender, immediately the moment the e-mail arrives.

This can be used to solve many automation tasks without having to make umpteen clicks.

Using VBA Application_NewMailEx()

In the VBA code below is the basic framework for running a macro when an email arrives. Care should be taken to implement the Application_NewMailEx method within ThisOutlookSession.

Screenshort Visual Basic Editor Outlook
Insert Application_NewMailEx method into ThisOutlookSession

Both methods Application_NewMail and Application_NewMailEx are still executed before the defined Outlook rules.

In the example, a check of the sender address takes place with the property Item.SenderEmailAddress. Many other checks, such as for the subject (Item.Subject), are conceivable. Within this If statement, one can then execute further code or execute macros from other modules.

Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
Dim Item As Object.
Dim Email As String
Set Item = Session.GetItemFromID(EntryIDCollection)
'Get sender email address.
Email = Item.SenderEmailAddress
'Check if email from specific sender.
If email = "vorname.nachname@ekiwi.de" Then
'run more code and macros here.
Debug.Print "The correct mail is: " + Email.
Debug.Print "Wrong mail is: " + Email.
End If.
End Sub

If you want to execute methods from other modules at this point, you have to make sure that they are declared as public.

Note: If you use Debug.Print for testing, you must use View => Direct Window (Ctrl+G) to show the output window in the VBA editor. For programmers of other programming languages certainly an unfamiliar wording.

Bestseller No. 1
Bestseller No. 2

Leave a Reply

Your email address will not be published. Required fields are marked *