将FileAttachment附加到message.C#EWS中的附件

时间:2018-12-04 10:59:34

标签: c# email exchangewebservices attachment

我正在尝试在邮件中添加FileAttachment。不幸的是message.Attachments.AddFileAttachment()要求提供一条我没有的路径。我有另一封邮件中的FileAttachment

我在这里得到附件:

EmailMessage oldEmailMessage = EmailMessage.Bind(service, olderSoxMail.Id);
// load attachments
FileAttachment fileAttachment = newEmailMessage.Attachments[0] as FileAttachment;
fileAttachment.Load();

在这里,我尝试将附件附加到邮件上

public static void ComposeEmail(string recipient, string subject, string body, FileAttachment[] attachment = null)
{
    var map = new Dictionary<char, string>() {
        { 'ä', "ae" },
        { 'ö', "oe" },
        { 'ü', "ue" },
        { 'Ä', "Ae" },
        { 'Ö', "Oe" },
        { 'Ü', "Ue" },
        { 'ß', "ss" }
    };
    recipient = recipient.Aggregate(
      new StringBuilder(),
      (sb, c) =>
      {
          string r;
          if (map.TryGetValue(c, out r))
              return sb.Append(r);
          else
              return sb.Append(c);
      }).ToString();

    EmailMessage message = new EmailMessage(service);
    message.Subject = subject;
    message.Body = body;
    message.ToRecipients.Add(recipient);

    foreach (FileAttachment attach in attachment)
    {
        // COMPILER ERROR HERE: Cannot Convert from FileAttachment to Path (string)
        message.Attachments.AddFileAttachment(attach);
        // END ERROR
    }

    message.SendAndSaveCopy();
}

您知道如何添加FileAttachment吗?

1 个答案:

答案 0 :(得分:1)

现在,Exchange服务器上已存在要接收的文件附件。您可以下载这些附件并存储路径,并将这些路径附加到新电子邮件中。

更好的解决方案是将附件作为流读取,并将其直接附加到邮件中,而无需先将其保存到磁盘上。

foreach (var fileAttachment in fileAttachments)
{
    var stream = new System.IO.MemoryStream(fileAttachment.Content);
    message.Attachments.AddFileAttachment(fileAttachment.Name, stream);
}