从Outlook获取附件

Ras*_*A M 0 c# outlook

我是新的2 C#,我已经完成了一项任务......我必须编写一个C#代码,将发送的电子邮件附件和Outlook 2007中的电子邮件主题下载到本地驱动器或任何指定位置.我怎么做?我能够获取收件箱中的附件.任何人都可以帮我收看通过Outlook发送的邮件吗?

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 SentMail = this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
    Outlook.Items SentMailItems = SentMail.Items;
    Outlook.MailItem newEmail = null;
    //SentMailItems = SentMailItems.Restrict("[Unread] = true");
    try
    {
        foreach (object collectionItem in SentMailItems)
        {
            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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Ser*_*nov 5

我已经测试了你的代码,类实例抛出的SaveAsFile()方法Attachment:

{System.IO.DirectoryNotFoundException:无法保存附件.路径不存在.验证路径是否正确.在Microsoft.Office.Interop.Outlook.Attachment.SaveAsFile(String Path)...}

因此,有必要确保存在用于保存附件的目录.

private void ThisApplication_NewMail()
{
    const string destinationDirectory = @"C:\TestFileSave";

    if (!Directory.Exists(destinationDirectory))
    {
        Directory.CreateDirectory(destinationDirectory);
    }

    MAPIFolder sentMail = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
    Items sentMailItems = sentMail.Items;
    try
    {
        foreach (object collectionItem in sentMailItems)
        {
            MailItem newEmail = collectionItem as MailItem;
            if (newEmail == null) continue;

            if (newEmail.Attachments.Count > 0)
            {
                for (int i = 1; i <= newEmail.Attachments.Count; i++)
                {
                    string filePath = Path.Combine(destinationDirectory, newEmail.Attachments[i].FileName);
                    newEmail.Attachments[i].SaveAsFile(filePath);
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.