如何从内存中制作Outlook邮件附件?

时间:2019-02-14 16:34:24

标签: c# .net outlook-addin

通过System.Net.Mail.AttachmentOutlook.MailItem.Attachments添加新的Attachments.Add()会产生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.',这什么也没告诉我:-/

3 个答案:

答案 0 :(得分:1)

MailItem.Attachments.Add仅允许传递字符串(文件的标准路径)或另一个Outlook项目(例如MailItem)作为参数。

在扩展MAPI级别(仅C ++或Delphi)上,仅使用IStream(您应该使用PR_ATTACH_DATA_BINIStream的形式打开IAttach::OpenProperty。如果可以选择使用Redemption(我是作者),则允许传递url,文件名,另一个Outlook项目,IStreamIStorage COM界面,另一个附件({ {1}}或Outlook.AttachmentRedemption.RDOAttachment MAPI接口)或RDOMailAttachmentsIAttach

答案 1 :(得分:0)

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

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 :(得分:0)

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");