Поделиться через


How to: Set Flags on Incoming E-Mail Items

This example sets flags on unread messages from a specific sender as they arrive in the user's Outlook Inbox.

Applies to: The information in this topic applies to application-level projects for Outlook 2007 and Outlook 2010. For more information, see Features Available by Office Application and Project Type.

Example

Private Sub ThisAddIn_NewMail() Handles Application.NewMail
    Dim outlookNameSpace As Outlook.NameSpace = Me.Application.GetNamespace("MAPI")
    Dim inbox As Outlook.MAPIFolder = _
    outlookNameSpace.GetDefaultFolder( _
    Outlook.OlDefaultFolders.olFolderInbox)

    ' Mark each unread message from Jeff Hay with a yellow flag icon.
    Dim unreadMailItems As Outlook.Items = _
        inbox.Items.Restrict("[Unread]= true")

    For Each omailItem As Object In unreadMailItems
        Dim unreadMailItem As Outlook.MailItem = Nothing
        unreadMailItem = TryCast(omailItem, Outlook.MailItem)
        If (unreadMailItem IsNot Nothing) Then
            If (unreadMailItem.SenderName = "Jeff Hay") Then
                unreadMailItem.FlagIcon = _
                    Outlook.OlFlagIcon.olYellowFlagIcon
                unreadMailItem.Save()
            End If
        End If
    Next
End Sub
private void ThisAddIn_Startup(object sender,
    System.EventArgs e)
{
    this.Application.NewMail +=
        new Outlook.ApplicationEvents_11_NewMailEventHandler
        (ThisAddIn_NewMail);
}

void ThisAddIn_NewMail()
{
    Outlook.NameSpace outlookNameSpace = this.Application.GetNamespace("MAPI");

    Outlook.MAPIFolder inbox = outlookNameSpace.GetDefaultFolder
        (Outlook.OlDefaultFolders.olFolderInbox);

    // Mark each unread message from Jeff Hay with a yellow flag icon.
    Outlook.Items unreadMailItems =
        inbox.Items.Restrict("[Unread]= true");

    foreach (Object omailItem in unreadMailItems)
    {
        Outlook.MailItem unreadMailItem =
            omailItem as Outlook.MailItem;

        if (unreadMailItem != null)
        {
            if (unreadMailItem.SenderName == "Jeff Hay")
            {
                unreadMailItem.FlagIcon =
                    Outlook.OlFlagIcon.olYellowFlagIcon;
                unreadMailItem.Save();
            }
        }
    }
}

See Also

Concepts

Working with Mail Items

Getting Started Programming Application-Level Add-Ins