How to send HTML e-mail with an image embedded in its body? (C#)

by Vitaly Zayko 20. February 2009 13:56

I’m trying to cover two common questions in one post:

  1. How to send an HTML message by SMTP?
  2. How to embed a picture into its body?

Follow the C# code below.

// Use AlternateView to create HTML body ("cid:image" - here we place the image):
using(AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
   "This is an <b>Html</b> e-mail message with <i>embedded image</i> below\r\n<img src='cid:image'>",
   null, "text/html"))
{
   // Create LinkedResource to specify an embedded image:
    using (LinkedResource image = new LinkedResource("c:\\IMAGE.jpg"))
   {
       // ContentId should be equals to the CID that we specified above
        image.ContentId = "image";
       htmlView.LinkedResources.Add(image);

       mail.AlternateViews.Add(htmlView);

       // Create SmtpClient as reqular:
        SmtpClient smtp = new SmtpClient("mail.zayko.net");

       // Set Credential if needed:
        smtp.Credentials = new System.Net.NetworkCredential("mailusername", "mailpassword");

       // ...and here we go:
        smtp.Send(mail);
   }
}

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

Comments are closed

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

About the author

Vitaly Zayko

Senior Software Developer / Team Lead / Product Manager

Moscow, Russia