MailKit 电子邮件不会在 Gmail 上显示内联图像

MailKit email doesn't show inline images on Gmail

我正在使用 MailKit 在 C# ASP.NET MVC Framework 4.8 应用程序中发送电子邮件。 HTML 发送到桌面 Outlook 的电子邮件可以正常显示内联图像。但是,当发送到 Gmail 网络时,内联图像会附加到邮件中并显示 alt 文本。这是简化的代码:

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 ();

根据人们的说法(例如 ), it requires an AlternativeView, which becomes MultipartAlternative in MailKit (sample here)。但是只有 BodyBuilder 对象才支持的 LinkedResources 怎么办?

谢谢。

这是带评论的工作解决方案;希望这对下一个人有帮助。

// 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;

来自两个帖子的组合: