How to: Move Items in Outlook
Applies to |
---|
The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office. Project type
Microsoft Office version
For more information, see Features Available by Application and Project Type. |
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.
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
MessageBox.Show(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