Wednesday, February 29, 2012

In-Line Image attachment in the Email using C# Memory stream

Bitmap thumbnail = new Bitmap(200,200);

MemoryStream _stream = new MemoryStream();

thumbnail.Save(_stream, System.Drawing.Imaging.ImageFormat.Bmp);

MailMessage m = new MailMessage();


m.To.Add("ramkrivas@gmail.com");

m.From = new System.Net.Mail.MailAddress("Anyone-from@gmail.com);

m.Subject = "In Line attachement";

// Define the plain text alternate view and add to message
string plainTextBody =
"You must use an email client that supports HTML messages";

AlternateView plainTextView =
AlternateView.CreateAlternateViewFromString(
plainTextBody, null, MediaTypeNames.Text.Plain);

m.AlternateViews.Add(plainTextView);


// Define the html alternate view with embedded image and
// add to message. To reference images attached as linked
// resources from your HTML message body, use "cid:contentID"
// in the tag...
string sEmailBody = string.Empty;
sEmailBody + "" + "";
AlternateView htmlView =
AlternateView.CreateAlternateViewFromString(
sEmailBody, null, System.Net.Mime.MediaTypeNames.Text.Html);

// ...and then define the actual LinkedResource matching the
// ContentID property as found in the image tag.
// LinkedResource.ContentId is set to "SampleImage"
_stream.Position = 0;

LinkedResource sampleImage =
new LinkedResource(_stream, "image/bmp");
sampleImage.ContentId = "sampleImage";

htmlView.LinkedResources.Add(sampleImage);

m.AlternateViews.Add(htmlView);

//send the message
SmtpClient smtp = new SmtpClient(strDomainAddress); //specify the mail server address
smtp.Send(m);