Zayko in the Net

Personal blog of Vitaly Zayko


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

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";


       // Create SmtpClient as reqular:
        SmtpClient smtp = new SmtpClient("");

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

       // ...and here we go:

Add comment