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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With