Daily Archives: February 22, 2011
Email with attachment from byte array
Posted by robbsadler
How to Send Email with Attachment using ASP.NET 2.0 and C#
This article tells how to send an email with an attachment. I made a few modifications to make it work because I had to attach a byte array that came from a database. So this is how you do that:
void SendEmail()
{
List<String> recipientList = GetEmailAddressList();
SmtpClient client = new SmtpClient(GetSMTPServer(), GetSMTPPort());
MailAddress from = new MailAddress(ConfigurationManager.AppSettings["EmailContacts.From"]);
if (recipientList.Count == 0)
{
AddError("no email addresses found.");
return;
}
MailMessage message = new MailMessage();
message.From = from;
foreach (string to in recipientList)
{
message.To.Add(to);
}
//create the message
message.Body = "A new file is attached for your review.";
message.BodyEncoding = Encoding.UTF8;
// Get pdf binary data and save the data to a memory stream
System.IO.MemoryStream ms = new System.IO.MemoryStream(GetPdf());
// Create the attachment from a stream. Be sure to name the data with a file and
// media type that is respective of the data
message.Attachments.Add(new Attachment(ms, "myFile.pdf", "application/pdf"));
message.Subject = "New File for Review";
//send it
client.Send(message);
}

