How to: Perform Actions When an E-Mail Message Is Received
This example uses the Microsoft.Office.Tools.Outlook.Application.NewMail event to perform custom actions when the user receives an e-mail message.
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 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 Office Projects