what are the good good examples of methods to add multiple files from the database for an e-mail insInternet? I have got a technique that returns a Byte[] that contains the look column contents that i'm bringing in a loop to obtain each attachment, but I'm wondering if there is a "correct"/best-practice method of carrying this out, particularly with the potential of presenting memory leaks by utilizing MemoryStreams to retain the data? I am fine creating en e-mail object and affixing their email list of accessories into it, once I have got them and may do that fine having a single attachement however it appears to obtain a little more complex with multiple files. Thinking about I would not have believed this was a unusual requirement, there appears to become a dearth of articles/posts about this.

Thx - MH

Here's what direction to go. Let us suppose you have a range of accessories you have loaded out of your database:

IEnumerable<byte[]> attachments = ... fetch from your database

We're able to also securely think that together with individuals accessories you've loaded the filenames and most likely their corresponding MIME type (information that you simply surely should have endured together with individuals byte arrays representing your accessories). Which means you will most likely have fetched IEnumerable<SomeAttachmentType> but that is not important with regards to this publish.

Now you can send the mail:

using (var client = new SmtpClient("smtp.foo.com"))
using (var message = new MailMessage("from@foo.com", "to@bar.com"))
    message.Subject = "test subject";
    message.Body = "test body";
    message.IsBodyHtml = false;
    foreach (var attachment in attachments)
        var attachmentStream = new MemoryStream(attachment);
        // TODO: Choose a better name for your attachments and adapt the MIME type
        var messageAttachment = new Attachment(attachmentStream, Guid.NewGuid().ToString(), "application/octet-stream");

Here's the offer:

A [cde] (IDisposable) consists of multiple [cde] (IDisposable). Each attachment references a [cde] (IDisposable). The MailMessage is covered with a using MailMessage which guarantees that it is Dispose method is going to be known as which calls the Dispose approach to all accessories which call the Dispose approach to the memory streams.

Hi you could have buffered reads from the database, MemoryStream doesn't introduce any memory leak should you dispose it after usage. Example using SqlDataReader:


similar question regarding how to read bytes from database continues to be requested already numerous occasions, see here for instance: What is the most efficient way to read many bytes from SQL Server using SqlDataReader (C#)