Search code examples
vbaoutlookmailitem

Show MsgBox upon receiving email with specified subject or sender


How do I show a MsgBox or alert upon receiving a message with a specified subject or sender?

I put this procedure in ThisOutlookSession block.

Private Sub olInboxItems_ItemAdd(ByVal Item As Object)
    Dim myMail As MailItem
    Dim name As String

    If TypeOf Item Is MailItem Then
        Set myMail = Item
        If myMail.Subject Like "*Hello world*" And myMail.Categories = "" Then
            MsgBox "Message", vbInformation, "approved"
            MailDate = myMail.ReceivedTime
            myMail.Categories = "CZEART"
            myMail.MarkAsTask (olMarkNoDate)
            myMail.Save
        End If
    End If
End Sub

Solution

  • To test the code, open a mailitem with the required conditions then step through this.

    Option Explicit
    
    Private Sub test()
        Dim currItem As MailItem
        Set currItem = ActiveInspector.currentItem
        olInboxItems_ItemAdd currItem
    End Sub
    

    Likely though you need this in the ThisOutlookSession module.

    Option Explicit
    
    Private WithEvents olInboxItems As Items
    
    Private Sub Application_Startup()
      Dim objNS As NameSpace
      Set objNS = Application.Session
      ' instantiate objects declared WithEvents
      Set olInboxItems = objNS.GetDefaultFolder(olFolderInbox).Items
      Set objNS = Nothing
    End Sub
    

    http://www.outlookcode.com/article.aspx?id=62