如何将字节数组转换为邮件附件

时间:2010-07-07 21:35:50

标签: c# email

我有字节数组,它本质上是从数据库中检索的编码.docx。我尝试将此byte []转换为它的原始文件,并将其作为邮件的附件,而不必先将其作为文件存储在磁盘上。 什么是最好的方法呢?

public MailMessage ComposeMail(string mailFrom, string mailTo, string copyTo, byte[] docFile)
{
    var mail = new MailMessage();

    mail.From = new MailAddress(mailFrom);

    mail.To.Add(new MailAddress(mailTo));
    mail.Body = "mail with attachment";

    System.Net.Mail.Attachment attachment;

    //Attach the byte array as .docx file without having to store it first as a file on disk?
    attachment = new System.Net.Mail.Attachment("docFile");
    mail.Attachments.Add(attachment);

    return mail;
}

1 个答案:

答案 0 :(得分:17)

Attachment byte[]有一个流。您可以使用MemoryStream stream = new MemoryStream(docFile); Attachment attachment = new Attachment(stream, "document.docx");

构建overload of the constructor来直接传递文件
MemoryStream

第二个参数是文件的名称,将从中推断出mime类型。完成后,请务必在{{1}}上致电MemoryStream