嵌入式图像显示为已损坏

时间:2017-09-04 05:56:11

标签: c# .net email

我有一个脚本循环遍历所有img标签的HTML表格(使用HtmlAgilityPack)。它转换任何具有Base64格式值的src属性,并将它们作为链接资源添加到MailMessage对象(包含在电子邮件中)。

以下是我的测试代码:

$scope.facebookLogout=function(){
// here destroy the session, which has been recently created at the time of login
}

当在客户端收到电子邮件时,HTML呈现,但嵌入的图像显示为损坏的图像。 Base64图像没有损坏或格式错误,因为我已经通过将Base64保存到本地文件进行了测试,该文件完全打开。

我正在测试的电子邮件客户端将显示嵌入的图像。这已启用。

我还测试了加载本地文件,将其转换为Base64图像并使用类似的脚本发送到下面。这非常有效。

1 个答案:

答案 0 :(得分:0)

我发现其他任何人都在努力解决这个问题。创建备用视图的顺序是关键,因为我在使用新的CID更新主体之前创建了AlternativeView。这是我现在有效的更新源:

mailMessage.Body = GetFormattedEntries(279);
var picList = new List<LinkedResource>();


HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
htmlDocument.LoadHtml(mailMessage.Body);
var images = htmlDocument.DocumentNode.Descendants("img").ToList();

foreach (var image in images)
{

    var src = image.Attributes["src"].Value;
    var regex = new Regex(@"data:(?<mime>[\w/\-\.]+);(?<encoding>\w+),(?<data>.*)", RegexOptions.Compiled);
    var match = regex.Match(src);
    var mime = match.Groups["mime"].Value;
    var encoding = match.Groups["encoding"].Value;
    var data = match.Groups["data"].Value;

    byte[] bytes = Convert.FromBase64String(data);
    System.IO.MemoryStream embeddedMs = new System.IO.MemoryStream(bytes, 0, bytes.Length);
    LinkedResource pic1 = new LinkedResource(embeddedMs, new System.Net.Mime.ContentType(mime));
    pic1.TransferEncoding = TransferEncoding.Base64;
    pic1.ContentId = Guid.NewGuid().ToString();
    picList.Add(pic1);
    var newNode = image.CloneNode(true);
    newNode.Attributes.Remove(newNode.Attributes["class"]);
    newNode.Attributes["src"].Value = string.Format("cid:{0}", pic1.ContentId);
    image.ParentNode.ReplaceChild(newNode, image);
}


mailMessage.IsBodyHtml = true;
mailMessage.Body = htmlDocument.DocumentNode.OuterHtml;

AlternateView avHtml = AlternateView.CreateAlternateViewFromString(mailMessage.Body, null, MediaTypeNames.Text.Html);

foreach (var pic in picList)
    avHtml.LinkedResources.Add(pic);


mailMessage.AlternateViews.Add(avHtml);

mailMessage.SendMail();