Serving medium size and large enterprises nationwide by building and customizing resources planning, consulting, customer management solutions. Research, design, development and support of bussiness information systems.

Sending Email Messages with Embedded Images

December 19, 2013 12:32 pm

Sending Email Messages with Embedded Images

Usually, when we implement email notification from various applications we send emails containing HTML body. And when there should be an image within the email body we put the image on a web server and use a reference to that image in the HTML code. Following as an example of this:

Hello world

 <img alt="sample image" src="http://webserveraddress/Images/sample_image.png" />

The drawback with this scenario is the need for connection to the web server when reading the email. This is causing issues, for example, when the server is part of an intranet network that is not always accessible by the clients.

To avoid this issue we found a way to embed the images into the email message itself. This could be done by using the MIME standard for putting multiple content parts into a single email message. When using multiple MIME parts the message looks like this:

Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable

      Hello world

Content-Type: image/png
Content-Transfer-Encoding: base64


In that way the email could contain multiple images embedded as different MIME parts. The binary image is usually encoded as Base64 string. In that case the “Content-ID” element specifies the content ID of the particular image. Next, the “src” attribute of the <img /> tag should point to that ID and the embedded image could be used into the HTML code. Following is an example:

   <img alt="sample image" src="cid:IMAGE_ID_HERE" />

Fortunately, the .NET Framework supports a mechanism for adding multiple resources (parts) to the email message. Following is a sample code in C# that is adding an embedded image to an email message:

string body = "<p>Hello world! <img alt='Hello' src='cid:HELLO_IMG' /></p>";
MailMessage mail = new MailMessage();

AlternateView altView = AlternateView.CreateAlternateViewFromString(body, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html);

LinkedResource imageResource = new LinkedResource(@"D:\Images\Hello.png", "image/png");
imageResource.ContentId = "HELLO_IMG";

This sample code shows just how to add the embedded image by using the AlternateView and LinkedResource classes. I will leave it to you to implement the rest part of the work for sending the email by configuring and working with the SmtpClient and MailMessage classes.

It is important to notice that you should use the same content ID in both the HTML code and the resource construction:

<img alt="Hello" src="cid:<b>HELLO_IMG</b>" />

imageResource.ContentId = "<b>HELLO_IMG</b>";

I hope that information was helpful and you enjoyed reading it!