Share via


How to: Programmatically perform actions when an email message is received

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

This example performs custom actions when the user receives an email message.

Applies to: The information in this topic applies to VSTO Add-in projects for Outlook. For more information, see Features available by Office application and project type.

Example

Dim outlookNameSpace As Outlook.NameSpace
Dim inbox As Outlook.MAPIFolder
Dim WithEvents items As Outlook.Items

Private Sub ThisAddIn_Startup() Handles Me.Startup

    outlookNameSpace = Me.Application.GetNamespace("MAPI")
    inbox = _
        outlookNameSpace.GetDefaultFolder( _
        Outlook.OlDefaultFolders.olFolderInbox)
    items = inbox.Items

End Sub

Private Sub Items_ItemAdd(ByVal item As Object) Handles items.ItemAdd
    Dim filter As String = "USED CARS"
    If TypeOf (item) Is Outlook.MailItem Then
        Dim mail As Outlook.MailItem = item
        If mail.MessageClass = "IPM.Note" And _
 mail.Subject.ToUpper.Contains(filter.ToUpper) Then
            mail.Move(outlookNameSpace.GetDefaultFolder( _
                Outlook.OlDefaultFolders.olFolderJunk))
        End If
    End If

End Sub
Outlook.NameSpace outlookNameSpace;
Outlook.MAPIFolder inbox;
Outlook.Items items;

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    outlookNameSpace = this.Application.GetNamespace("MAPI");
    inbox = outlookNameSpace.GetDefaultFolder(
            Microsoft.Office.Interop.Outlook.
            OlDefaultFolders.olFolderInbox);

    items = inbox.Items;
    items.ItemAdd +=
        new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd);
}

void items_ItemAdd(object Item)
{
    string filter = "USED CARS";
    Outlook.MailItem mail = (Outlook.MailItem)Item;
    if (Item != null)
    {
        if (mail.MessageClass == "IPM.Note" &&
                   mail.Subject.ToUpper().Contains(filter.ToUpper()))
        {
            mail.Move(outlookNameSpace.GetDefaultFolder(
                Microsoft.Office.Interop.Outlook.
                OlDefaultFolders.olFolderJunk));
        }
    }

}

See also