如何:在收到电子邮件后执行操作

更新:2011 年 4 月

此示例执行用户收到电子邮件时的自定义操作。

**适用于:**本主题中的信息适用于 Outlook 2007 和 Outlook 2010 的应用程序级项目。有关更多信息,请参见按 Office 应用程序和项目类型提供的功能

示例

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));
        }
    }
}

请参见

任务

如何:在 Office 项目中创建事件处理程序

概念

使用邮件项

应用程序级外接程序编程入门

修订记录

日期

修订记录

原因

2011 年 4 月

根据最近的一些客户反馈更新了代码示例。

客户反馈