Share via


How to: Programmatically move items in Outlook

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 moves unread e-mail messages from the Inbox to a folder named Test. The example only moves messages that have the word Test in the Subject field.

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

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    this.Application.NewMail += new Microsoft.Office.Interop.Outlook.
        ApplicationEvents_11_NewMailEventHandler
        (ThisAddIn_NewMail);

}

private void ThisAddIn_NewMail()
{
    Outlook.MAPIFolder inBox = (Outlook.MAPIFolder)this.Application.
        ActiveExplorer().Session.GetDefaultFolder
        (Outlook.OlDefaultFolders.olFolderInbox);
    Outlook.Items items = (Outlook.Items)inBox.Items;
    Outlook.MailItem moveMail = null;
    items.Restrict("[UnRead] = true");
    Outlook.MAPIFolder destFolder = inBox.Folders["Test"];
    foreach (object eMail in items)
    {
        try
        {
            moveMail = eMail as Outlook.MailItem;
            if (moveMail != null)
            {
                string titleSubject = (string)moveMail.Subject;
                if (titleSubject.IndexOf("Test") > 0)
                {
                    moveMail.Move(destFolder);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

Compile the code

This example requires:

  • An Outlook mail folder named Test.

  • An email message that arrives with the word Test in the Subject field.

See also