我能够将jpg图片正确转换为base64String。但是我在使用转换后的图像字符串和LinkedResource将其嵌入电子邮件正文时遇到了麻烦。该图像作为电子邮件正文中的“未找到图像”图标出现。 任何帮助将不胜感激。
我在以下链接上关注了该示例:Iterate through an html string to find all img tags and replace the src attribute values
我正在使用HtmlAgilityPack(nuget包)通过以下代码定位img元素。
private string embedImageInMail(string html)
{
HtmlAgilityPack.HtmlDocument doc = new
HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
doc.DocumentNode.Descendants("img").Where(e =>
{
string src = e.GetAttributeValue("src", null) ?? "";
return !string.IsNullOrEmpty(src) && src.StartsWith("data:image");
})
.ToList()
.ForEach(x =>
{
string currentSrcValue = x.GetAttributeValue("src", null);
currentSrcValue = currentSrcValue.Split(',')[1]; //Base64 part of string
byte[] imageData = Convert.FromBase64String(currentSrcValue);
string contentId = Guid.NewGuid().ToString();
using (MemoryStream ms = new MemoryStream(imageData))
{
LinkedResource inline = new LinkedResource(ms, "image/jpeg");
inline.ContentId = contentId;
inline.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
x.SetAttributeValue("src", "cid:" + inline.ContentId);
}
});
return doc.DocumentNode.OuterHtml;
}
传递给函数的html参数包含img标记,其src等于图像的base64编码。 从此函数返回的内容将分配给电子邮件的message.body。
答案 0 :(得分:0)
通过遵循其他帖子中的解决方案来解决。如果外面有人试图做同样的事情并且遇到像我一样的麻烦,我将在下面发布代码。
基本上,我必须将html中的LinkedResource(图像)保存到一个列表,然后遍历该列表,并将所有图像添加到foreach循环之外的AlternateView中。
// Embeds image to properly show in Email. Image element to show in html will not work in Email body.
// https://stackoverflow.com/questions/39785600/iterate-through-an-html-string-to-find-all-img-tags-and-replace-the-src-attribut
// XmlAgilityPack gets used here to parse html string.
List<LinkedResource> linkedResources = new List<LinkedResource>();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
int increment = 0;
doc.LoadHtml(tempMsg);
doc.DocumentNode.Descendants("img").Where(z =>
{
string src = z.GetAttributeValue("src", null) ?? "";
return !string.IsNullOrEmpty(src) && src.StartsWith("data:image");
})
.ToList()
.ForEach(x =>
{
string currentSrcValue = x.GetAttributeValue("src", null);
currentSrcValue = currentSrcValue.Split(',')[1]; //Base64 part of string
byte[] imageData = Convert.FromBase64String(currentSrcValue);
string id = Guid.NewGuid().ToString();
increment++;
LinkedResource inlineImage = new LinkedResource(new MemoryStream(imageData), System.Net.Mime.MediaTypeNames.Image.Jpeg);
inlineImage.ContentType.Name = "img " + increment;
inlineImage.ContentId = id;
inlineImage.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
x.SetAttributeValue("src", "cid:" + inlineImage.ContentId);
linkedResources.Add(inlineImage);
});
// Append multiple images from template to email message.
// https://stackoverflow.com/questions/7048758/how-to-embed-multiple-images-in-email-body-using-net
// Write html to message.body
AlternateView altView = AlternateView.CreateAlternateViewFromString(doc.DocumentNode.OuterHtml, null, "text/html");
linkedResources.ForEach(x=>altView.LinkedResources.Add(x));
message.AlternateViews.Add(altView);
String[] attachments = txtAttachFiles.Text.Split(';');
foreach (String filename in attachments)
{
if (File.Exists(filename))
{
Attachment attachment = new Attachment(filename);
message.Attachments.Add(attachment);
}
}
// loop is set to 1 in the app.config file so technically this for loop is not needed, but will keep this loop just in case.
for (int loop = 0; loop < Convert.ToInt32(ConfigurationManager.AppSettings["loop"]); loop++)
{
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["mailHost"];
smtp.Port = Int32.Parse(ConfigurationManager.AppSettings["mailPort"]);
smtp.UseDefaultCredentials = Convert.ToBoolean(ConfigurationManager.AppSettings["mailDefaultCredentials"]);
smtp.Send(message);
}
}