Share via


How to: Programmatically save attachments from Outlook email items

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 saves e-mail attachments to a specified folder when the mail is received in the inbox.

Important

This example works only if you add a folder named TestFileSave at the root of the C directory.

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

private void ThisApplication_NewMail()
{
    Outlook.MAPIFolder inBox = this.Application.ActiveExplorer()
        .Session.GetDefaultFolder(Outlook
        .OlDefaultFolders.olFolderInbox);
    Outlook.Items inBoxItems = inBox.Items;
    Outlook.MailItem newEmail = null;
    inBoxItems = inBoxItems.Restrict("[Unread] = true");
    try
    {
        foreach (object collectionItem in inBoxItems)
        {
            newEmail = collectionItem as Outlook.MailItem;
            if (newEmail != null)
            {
                if (newEmail.Attachments.Count > 0)
                {
                    for (int i = 1; i <= newEmail
                       .Attachments.Count; i++)
                    {
                        newEmail.Attachments[i].SaveAsFile
                            (@"C:\TestFileSave\" +
                            newEmail.Attachments[i].FileName);
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        string errorInfo = (string)ex.Message
            .Substring(0, 11);
        if (errorInfo == "Cannot save")
        {
            MessageBox.Show(@"Create Folder C:\TestFileSave");
        }
    }
}

See also