我有一个字节数组,它本质上是一个从数据库中检索到的编码 .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;
}
最佳答案
有一个overload of the constructor获取流的 Attachment
。可以通过构造一个MemoryStream直接传入文件使用 byte[]
:
MemoryStream stream = new MemoryStream(docFile);
Attachment attachment = new Attachment(stream, "document.docx");
第二个参数是文件的名称,将从中推断 mime 类型。记得调用Dispose()
完成后在 MemoryStream
上。
关于c# - 如何将字节数组转换为邮件附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3199033/