Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto convert a byte array to mail attachment

Tags:

c#

email

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;
}
like image 323
Oysio Avatar asked Jul 07 '10 21:07

Oysio


1 Answers

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.

like image 97
adrianbanks Avatar answered Sep 20 '22 06:09

adrianbanks