19 Comments
  •   Posted in: 
  • C#
I've seen a couple posts on this before but they all seem to miss out a critical piece of code that without, causes the images to be embedded but they do not display correctly in some e-mail clients (such as Outlook 2003/2007). The following code will make it work across a number of clients I've tested it with and I've also thrown in a basic way to have a plain text e-mail attached as well in case the client does not support HTML.

Disclaimer: I've chosen to use the media type of JPEG, it's not ideal but it's something I threw together to get the main point across. You should really get the file extension and use a switch statement for the different media types.
public static void SendMessageWithEmbeddedImages()
{
  string htmlMessage = @"<html>
                         <body>
                         <img src='cid:EmbeddedContent_1' />
                         </body>
                         </html>";
  SmtpClient client = new SmtpClient("mail.server.com");
  MailMessage msg = new MailMessage("[email protected]",
                                    "[email protected]");
  // Create the HTML view
  AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
                                               htmlMessage,
                                               Encoding.UTF8,
                                               MediaTypeNames.Text.Html);
  // Create a plain text message for client that don't support HTML
  AlternateView plainView = AlternateView.CreateAlternateViewFromString(
                                              Regex.Replace(htmlMessage,
                                                            "<[^>]+?>",
                                                            string.Empty),
                                              Encoding.UTF8,
                                              MediaTypeNames.Text.Plain);
  string mediaType = MediaTypeNames.Image.Jpeg;
  LinkedResource img = new LinkedResource(@"C:\Images\MyImage.jpg", mediaType);
  // Make sure you set all these values!!!
  img.ContentId = "EmbeddedContent_1";
  img.ContentType.MediaType = mediaType;
  img.TransferEncoding = TransferEncoding.Base64;
  img.ContentType.Name = img.ContentId;
  img.ContentLink = new Uri("cid:" + img.ContentId);
  htmlView.LinkedResources.Add(img);
  //////////////////////////////////////////////////////////////
  msg.AlternateViews.Add(plainView);
  msg.AlternateViews.Add(htmlView);
  msg.IsBodyHtml = true;
  msg.Subject = "Some subject";
  client.Send(msg);
}
I couldn't find this information anywhere but I tried setting a whole bunch of things until the images displayed correctly, hope this helps someone with the same issues.

Expect to see this feature in my Command Line E-mailer application so that sending HTML e-mails appear the way you designed them locally when they arrive at the recipient.