Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

How to embed an image in email body

5.00/5 (15 votes)
3 Dec 2013CPOL 161.6K  
How to embed an image in email body

Usually when we are sending images in an email, we place the...

HTML
<img src="" alt="" />

...tag in the HTML email body and the 'src' of the image tag points to the HTTP URL of the image. To get this HTTP URL, the image has to be hosted somewhere, either on your own website or somewhere on the internet.

But in many scenarios, you don't have the HTTP URL to the image and you want to send the image in an email.

This kind of scenario occurs while sending images that are saved in the database or when sending the emails from a Windows application.

In these scenarios, you need to use the LinkedResource object to directly 'embed' the image in an HTML email and then send the email using our standard .NET 'MailMessage' class.

Here is the complete code to it - tested and working:

C#
MailMessage Mail = new MailMessage();        

Mail.From = new MailAddress("myemail@bogusdomain.com");
Mail.To.Add("hisemail@bogusdomain.com");
Mail.Subject = "This is Image Test.";
Mail.Body = "This is the body of the email";
LinkedResource LinkedImage = new LinkedResource(@"J:\My Documents\Advika1.jpg");
LinkedImage.ContentId = "MyPic";
//Added the patch for Thunderbird as suggested by Jorge
LinkedImage.ContentType = new ContentType(MediaTypeNames.Image.Jpeg);

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
  "You should see image next to this line. <img src=cid:MyPic>", 
  null, "text/html");

htmlView.LinkedResources.Add(LinkedImage);
Mail.AlternateViews.Add(htmlView);
SmtpClient smtp = new SmtpClient("111.111.111.111", 25); 
try
{
    smtp.Send(Mail);
}
catch (SmtpException ex)
{
    Logger.LogException(ex);
}

Let me know if this post helps you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)