0

I'm using MailKit to send emails in a C# ASP.NET MVC Framework 4.8 app. HTML emails to desktop Outlook show inline images fine. However, when sent to Gmail web, the inline images are attached to the message and show the alt text instead. Here's simplified code:

var builder = new BodyBuilder ();
var pathImage = Path.Combine (Misc.GetPathOfExecutingAssembly (), "Image.png");
var image = builder.LinkedResources.Add (pathLogoFile);

image.ContentId = MimeUtils.GenerateMessageId ();

builder.HtmlBody = string.Format (@"<p>Hey!</p><img src=""cid:{0}"">", image.ContentId);

message.Body = builder.ToMessageBody ();

From what people are saying (such as here), it requires an AlternativeView, which becomes MultipartAlternative in MailKit (sample here). But then how do you do the LinkedResources, which is only supported on the BodyBuilder object?

Thanks.

Alex
  • 34,699
  • 13
  • 75
  • 158

1 Answers1

1

Here's the working solution with comments; hope this helps the next person.

// Using HtmlAgilityPack
var doc = new HtmlDocument();
doc.LoadHtml(Body);  // Load your html text here

// Loop over the img tags in html doc
foreach (var node in doc.DocumentNode.SelectNodes("//img"))
{
    // File path to the image. We get the src attribute off the current node for the file name.
    var file = Path.Combine(ImagesRootPath, node.GetAttributeValue("src", ""));
    if (!File.Exists(file))
    {
        continue;
    }

    // Set content type to the current image's extension, such as "png" or "jpg"
    var contentType = new ContentType("image", Path.GetExtension(file));
    var contentId = MimeKit.Utils.MimeUtils.GenerateMessageId();
    var image = (MimePart) bodyBuilder.LinkedResources.Add(file, contentType);
    image.ContentTransferEncoding = ContentEncoding.Base64;
    image.ContentId = contentId;

    // Set the current image's src attriubte to "cid:<content-id>"
    node.SetAttributeValue("src", $"cid:" + contentId);
}

bodyBuilder.HtmlBody = doc.DocumentNode.OuterHtml;

From a combo of two posts:

Alex
  • 34,699
  • 13
  • 75
  • 158