I was recently writing a webapplication for one of our clients. The application is a training management tool and thus involves sending loads of e-mail. This way people get reminded that they’ll be following a training in the next days or asked to write a review about their training. To make the mail look great, we wanted it to be in HTML and contain the company logo.

A first attempt was made by just writing the html for the mail and use an ordinary image-tag with a reference to the client’s intranet (like this: <img src=”http://intranet.client.com/logo.gif”/>). However, the kick-ass intranet-security of our client wouldn’t allow this and each time the mail was opened, the user was prompted for his credentials. Very annoying! So we had to include the image in the mail as an attachment. You see it every day, but apparently the code to do this in c# isn’t that widely spread. So here’s my function to accomplish it:

/// <summary>
/// Embeds the company logo into the given mail message
/// </summary>
/// <param name="message">Message in which the logo should be embedded</param>
private static void EmbedCompanyLogo(MailMessage message)
{
   AlternateView av1 = AlternateView.CreateAlternateViewFromString(message.Body, null, System.Net.Mime.MediaTypeNames.Text.Html);
   string strImageUrl = System.Web.HttpContext.Current.Server.MapPath("~/images/logo_print.gif");
   LinkedResource logo = new LinkedResource(strImageUrl, System.Net.Mime.MediaTypeNames.Image.Jpeg);
   logo.ContentId = "companylogo";
   //To refer to this image in the html body, use <img src="cid: companylogo"/>
   av1.LinkedResources.Add(logo);
   message.AlternateViews.Add(av1);
}

As mentioned in the code comment, in your mail message you can refer to the image with a source equal to “cid:companylogo”.

If you have any thoughts, remarks or questions, the comments are open…