Question

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!

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top