MailKit电子邮件未在Gmail上显示嵌入式图像

问题描述

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

reduce

根据人们所说的内容(例如here),它需要一个const arr = [ { "persentage": "30","value": "123" },{ "persentage": "27","value": "345" },{ "persentage": "2","value": "232" },"value": "343" },{ "persentage": "9","value": "4334" },{ "persentage": "6","value": "43343" },{ "persentage": "4","value": "95" } ]; const filtered = arr.reduce((acc,item,i) => { acc.percentage += Number(item.persentage); if (acc.percentage <= 90 && i < 6) { acc.items.push(item); } return acc; },{percentage: 0,items: []}).items; console.log(filtered);,它在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 (); (示例here)。但是,如何处理AlternativeView对象仅支持MultipartAlternative

谢谢。

解决方法

这是带有注释的有效解决方案;希望这对下一个人有帮助。

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

来自两个帖子的组合: