【问题标题】:How to make outlook mail attachment from memory?如何从内存中制作outlook邮件附件?
【发布时间】:2019-07-08 18:05:17
【问题描述】:

通过Attachments.Add() 将新的System.Net.Mail.Attachment 添加到Outlook.MailItem.Attachments 会导致System.ArgumentException: 'Sorry, something went wrong. You may want to try again.'

尝试将 Base64 编码的 JPEG 图像作为附件添加到 Outlook 中的邮件项目。我将编码图像存储为变量,将其转换为内存流,然后转换为附件。

public void CreateMessageWithAttachment() {
    Outlook.MailItem mailIttem = thisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);
    string base64Attachment = "/...base64 gibberish";
    MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64Attachment));
    ContentType ct = new ContentType(MediaTypeNames.Image.Jpeg);
    Attachment attachment = new Attachment(ms, ct);

    attachment.ContentDisposition.FileName = "look_at_dis.jpg";
    mailIttem.Subject = "Test e-mail message with attachment";
    mailIttem.To = "friend@company.com";
    mailIttem.Body = "This message has been generated programmatically";
    mailIttem.Attachments.Add(attachment); // This raises "Sorry..." expression
    mailIttem.Display(true);
}

引发System.ArgumentException: 'Sorry, something went wrong. You may want to try again.',它什么也没告诉我:-/

【问题讨论】:

    标签: c# .net outlook-addin


    【解决方案1】:

    在将内存流附加到消息之前,我相信您必须将其位置重置为零:

    MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64Attachment));
    ms.Position = 0; // important
    ContentType ct = new ContentType(MediaTypeNames.Image.Jpeg);
    Attachment attachment = new Attachment(ms, ct);
    // etc
    

    【讨论】:

      【解决方案2】:

      Official docs 给我的印象是Attachments.Add 应该只适用于文件路径,因此将MemoryStream 保存到临时文件并附加它可以解决问题。

      string tempFilePath = Path.GetTempPath() + "look_at_dis.jpg";
      FileStream fs = new FileStream(tempFilePath, FileMode.Create);
      
      ms.CopyTo(fs);
      fs.Close();
      
      mailIttem.Attachments.Add(tempFilePath, Outlook.OlAttachmentType.olByValue, 1, "look_at_dis.jpg");
      

      【讨论】:

        【解决方案3】:

        MailItem.Attachments.Add 只允许将字符串(文件的完全限定路径)或另一个 Outlook 项目(例如MailItem)作为参数传递。

        在扩展 MAPI 级别(仅限 C++ 或 Delphi),它只采用 IStream(您应该使用 IAttach::OpenPropertyPR_ATTACH_DATA_BIN 打开为 IStream)。如果使用Redemption(我是它的作者)是一个选项,它允许传递一个url、一个文件名、另一个Outlook项目、IStreamIStorage COM接口、另一个附件(Outlook.AttachmentRedemption.RDOAttachmentIAttach MAPI 接口)或数组(变量或字节)到RDOMail.Attachments.Add

        【讨论】:

        • 感谢您澄清这一点!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-03
        • 1970-01-01
        • 2011-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多