How to: Programmatically Move Items in Outlook

 

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.

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

This example requires:

  • An Outlook mail folder named Test.

  • An e-mail message that arrives with the word Test in the Subject field.

Working with Folders
How to: Programmatically Retrieve a Folder by Name
How to: Programmatically Search Within a Specific Folder
How to: Programmatically Perform Actions When an E-Mail Message Is Received

Show: