开发者

Howto convert a byte array to mail attachment

I have byte array which is essentially an encoded .docx retrieved from the DB. I try to convert this byte[] to it's original file and make it as an attachment to a mail without having to store it first as file on disk. What's the best way to go about this?

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;
}


There is an overload of the constructor of Attachment that takes a stream. You can pass in the file directly by constructing a MemoryStream using the byte[]:

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

The second argument is the name of the file, from which the mime-type will be inferred. Remember to call Dispose() on the MemoryStream once you have finished with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜