Dela via


How to: Perform Actions When an E-Mail Message Is Received

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Project type

  • Application-level projects

Microsoft Office version

  • Outlook 2003

  • Outlook 2007

For more information, see Features Available by Application and Project Type.

This example uses the Microsoft.Office.Tools.Outlook.Application.NewMail event to perform custom actions when the user receives an e-mail message.

Example

Private Sub ThisAddIn_NewMail() Handles Application.NewMail
    Dim filter As String = "USED CARS" 

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

    items.Restrict("[Unread] = true")

    ' If the mail item matches the specified filter, 
    ' move it to the junk e-mail folder. 
    For Each mail As Outlook.MailItem In items
        If mail.MessageClass = "IPM.Note" And _
            mail.Subject.ToUpper.Contains(filter.ToUpper) Then
            mail.Move(outlookNameSpace.GetDefaultFolder( _
                Outlook.OlDefaultFolders.olFolderJunk))
        End If 
    Next 
End Sub
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    this.Application.NewMail += new Microsoft.Office.Interop.
        Outlook.ApplicationEvents_11_NewMailEventHandler(
        ThisApplication_NewMail);
}

void ThisApplication_NewMail()
{
    string filter = "USED CARS";

    Outlook.NameSpace outlookNameSpace = this.Application.GetNamespace("MAPI");
    Outlook.MAPIFolder inbox = outlookNameSpace.GetDefaultFolder(
        Microsoft.Office.Interop.Outlook.
        OlDefaultFolders.olFolderInbox);

    Outlook.Items items = inbox.Items;
    items.Restrict("[Unread] = true");

    // If the mail item matches the specified filter, 
    // move it to the junk e-mail folder. 
    foreach (Outlook.MailItem mail in items)
    {
        if (mail.MessageClass == "IPM.Note" &&
            mail.Subject.ToUpper().Contains(filter.ToUpper()))
        {
            mail.Move(outlookNameSpace.GetDefaultFolder(
                Microsoft.Office.Interop.Outlook.
                OlDefaultFolders.olFolderJunk));
        }
    }
}

See Also

Tasks

How to: Create Event Handlers in Visual Studio Tools for Office

Concepts

Working with Mail Items

Getting Started Programming Application-Level Add-Ins