Sending emails with embedded images in .NET


Hi all.

Today I had to find a way to send emails with embedded images in it, for branding purposes. At first glance, it might seem an easy task to accomplish but it took me some time to actually realize how I could pull this through.

To be able to embed images, the body of your email has to be HTML, so we start off by creating a standard HTML email message, with all the proper fields (To, From, Subject, Body, etc.) with data, like this:


var message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress("no-reply@pmhsilva.com");
message.To.Add(new MailAddress("reader@pmhsilva.com"));
message.Subject = "Sending emails with embedded images in ASP.NET MVC 4";
message.Body = "<!DOCTYPE HTML><html><head><title>Sample email with embedded image</title></head><body><img src='cid:logoPic' alt='logo'><p>Dear Reader,</p><p>This is an email with an embedded image!</p><p>Cheers,<br/>
Pedro</p></body></html>"

After this, we will use the AlternateView Class to change the format of the HTML message.


var av = AlternateView.CreateAlternateViewFromString(body, null, "text/html");

This will enable us view the email body in a different format, including embedding images, like this:


var ct = new ContentType(MediaTypeNames.Image.Jpeg);
var imageLocation = HttpContext.Server.MapPath("../img/pmhsilvaLogo.jpg");
var logoPic = new LinkedResource(imageLocation, ct) { ContentId = "logoPic" };
av.LinkedResources.Add(logoPic);

First, we define the MIME content type of the image we’re adding, and for this we use the ContentType class. Then we create a new linked resource, from the image file we want to embed in the email. Note that it has to be a physical path, the LinkedResource constructor won’t accept a URI. Note that the LinkedResource constructor initializes the ContentID property to enable us to determine what placeholder we will replace with the linked resource. This, in practice, will replace the string “logoPic” in the body’s HTML string with the embedded image CID. Finally, we add the linked resource to the Alternate View object to embed the image.

Next step, add the alternate view to the email message object and fire the message away!


message.AlternateViews.Add(av);
var client = new SmtpClient
{
Port = 21, //YourMailServerPort
Host = "YourMailServerHostName",
EnableSsl = false
};
client.Send(message);

And there you go. Simple solution for something that looked complicated at start. I hope this could be of assistance to other people.

Cheers.
Pedro

Leave a comment

Your email address will not be published. Required fields are marked *