How to: 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 application-level projects for Outlook 2007 and Outlook 2010. For more information, see Features Available by Office Application and Project Type.

Example

Private Sub ThisApplication_NewMail() Handles Application.NewMail
    Dim inBox As Outlook.MAPIFolder = Me.Application.ActiveExplorer() _
        .Session.GetDefaultFolder(Outlook _
        .OlDefaultFolders.olFolderInbox)
    Dim items As Outlook.Items = inBox.Items
    Dim moveMail As Outlook.MailItem = Nothing
    items.Restrict("[UnRead] = true")
    Dim destFolder As Outlook.MAPIFolder = inBox.Folders("Test")
    Try
        For Each eMail As Object In items
            moveMail = TryCast(eMail, Outlook.MailItem)
            If Not moveMail Is Nothing Then
                If InStr(moveMail.Subject, "Test") > 0 Then
                    moveMail.Move(destFolder)
                End If
            End If
        Next eMail
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub
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);
        }
    }
}

Compiling the Code

This example requires:

  • An Outlook mail folder named Test.

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

See Also

Tasks

How to: Retrieve a Folder by Name

How to: Search Within a Specific Folder

How to: Perform Actions When an E-Mail Message Is Received

Concepts

Working with Folders