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

11

我有一个字节数组,基本上是从数据库中检索到的编码为.docx的文件。我尝试将这个字节数组转换回它的原始文件,并将其作为附件添加到邮件中,而不必先将其存储为磁盘文件。

最好的方法是什么?

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个回答

20

有一个构造函数的过载,它接受一个流作为参数。你可以通过使用byte[]构造一个MemoryStream来直接传递文件:

MemoryStream stream = new MemoryStream(docFile);
Attachment attachment = new Attachment(stream, "document.docx");

第二个参数是文件名,从中可以推断出mime类型。记得在使用完MemoryStream后调用Dispose()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接