views:

68

answers:

1

I'd like to attach a PDF file stored as binary object in SQL Server to an email but without creating a (temporary) file on disk.

I already have the first step to pull out the PDF file from the binary field in SQL Server as a byte[] array.

Also I have the step to setup the MailMessage:

MailMessage aMailMessage = new MailMessage();
// set address, subject, body
aMailMessage.Attachments.Add(attachment);

Where I am stuck is the attachment object:

Attachment attachment = new Attachment(... what goes here? ...);

The constructor of Attachment accepts mainly either a string fileName (which I don't have and want) or a System.IO.Stream contentStream.

So my question is: With a given byte[] array is it possible to create the proper Attachment object without an intermediary file on disk and what steps do I have to do?

Thank you in advance!

+1  A: 

You can convert byte[] to MemoryStream and create Attachment instance from it. Here is an example:

ContentType ct = new ContentType(MediaTypeNames.Application.Pdf);
MemoryStream pdf = new MemoryStream(pdfContent);
Attachment data = new Attachment(pdf, ct);
Giorgi
Great, thank you! Just one question: I have just used the constructor with the `name` (of the attached file), not with the `ContentType`, since I have a pure text mail. Is it correct that I only need to specify the `ContentType` if I have a HTML mail?
Slauma