loveforvdubs
loveforvdubs

Reputation: 53

VBA outlook new mail

I am trying to run a function every time a new mail arrives in outlook. I have been doing some searching but I am unable to find I way to fire code every time an email arrives. Is there a new mail event that I could utilize?

I added a simple MsgBox to it to be able to see if the event is firing but it did not seem to be working. I placed this code in the ThisOutlookSession module. Any adivice? Here is my code.

   Public WithEvents myOlApp As Outlook.Application

    Sub Initialize_handler()
        Set myOlApp = CreateObject("Outlook.Application")
    End Sub

    Private Sub myOlApp_NewMail()
        Dim myExplorers As Outlook.Explorers
        Dim myFolder As Outlook.MAPIFolder
        Dim x As Integer
        Set myExplorers = myOlApp.Explorers
        Set myFolder = myOlApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
        If myExplorers.Count <> 0 Then
            For x = 1 To myExplorers.Count
                On Error GoTo skipif
                If myExplorers.Item(x).CurrentFolder.Name = "Inbox" Then
                    MsgBox ("Test")
                    myExplorers.Item(x).Display
                    myExplorers.Item(x).Activate
                    Exit Sub
                End If
    skipif:
            Next x
         End If
         On Error GoTo 0
         myFolder.Display
    End Sub

Upvotes: 0

Views: 6118

Answers (2)

Matt Immer
Matt Immer

Reputation: 60

Try to put:

Private Sub Application_NewMail()
    MsgBox "New mail"
End Sub

In "ThisOutlookSession"

Upvotes: 1

jonsca
jonsca

Reputation: 10381

There's a good example on MSDN showing how to display the inbox when a new mail arrives (using Outlook.Explorers). You can probably adapt it pretty readily for your own program.

Upvotes: 0

Related Questions