如何:保存 Outlook 电子邮件项的附件

更新:2007 年 11 月

适用对象

本主题中的信息仅适用于指定的 Visual Studio Tools for Office 项目和 Microsoft Office 版本。

项目类型

  • 应用程序级项目

Microsoft Office 版本

  • Outlook 2003

  • Outlook 2007

有关更多信息,请参见按应用程序和项目类型提供的功能

此示例将电子邮件附件保存到指定的文件夹。

示例

Private Sub ThisAddIn_NewMail() Handles Application.NewMail
    Dim inBox As Outlook.MAPIFolder = Me.Application.ActiveExplorer() _
        .Session.GetDefaultFolder(Outlook. _
        OlDefaultFolders.olFolderInbox)
    Dim inBoxItems As Outlook.Items = inBox.Items
    Dim newEmail As Outlook.MailItem
    inBoxItems = inBoxItems.Restrict("[Unread] = true")
    Try
        For Each collectionItem As Object In inBoxItems
            newEmail = TryCast(collectionItem, Outlook.MailItem)
            If newEmail IsNot Nothing Then
                If newEmail.Attachments.Count > 0 Then
                    For i As Integer = 1 To newEmail.Attachments.Count
                        Dim saveAttachment As Outlook.Attachment = _
                            newEmail.Attachments(i)
                        newEmail.Attachments(i).SaveAsFile _
                            ("C:\TestFileSave\" & (newEmail _
                            .Attachments(i).FileName))
                    Next i
                End If
            End If
        Next collectionItem
    Catch ex As Exception
        If Left(ex.Message, 11) = "Cannot save" Then
            MessageBox.Show("Create Folder C:\TestFileSave")
        End If
    End Try
End Sub
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");
        }
    }
}

编译代码

此示例需要:

  • 一个名为 TestFileSave 的文件夹,它位于 C 根目录下。

请参见

任务

如何:按名称检索文件夹

如何:在收到电子邮件后执行操作

如何:在特定文件夹中搜索

概念

使用邮件项