我搜索了好几次并找到了解决方案,但都只支持一张图像。最后我使用了这段代码。
但问题是,如果 html 包含多个图像,则正文中仅显示一张图像,其他图像将作为附件显示。
string inputHtmlContent = htmlbody;
string outputHtmlContent = string.Empty;
var myResources = new List<LinkedResource>();
if ((!string.IsNullOrEmpty(inputHtmlContent)))
{
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(inputHtmlContent);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//img");
if (nodes !=null)
{
foreach (HtmlNode node in nodes)
{
if (node.Attributes.Contains("src"))
{
string data = node.Attributes["src"].Value;
string imgPath = Application.StartupPath+"\\"+data;
var imgLogo = new LinkedResource(imgPath);
imgLogo.ContentId = Guid.NewGuid().ToString();
imgLogo.ContentType = new ContentType("image/jpeg");
myResources.Add(imgLogo);
node.Attributes["src"].Value = string.Format("cid:{0}", imgLogo.ContentId);
outputHtmlContent = doc.DocumentNode.OuterHtml;
}
}
}
else
{
outputHtmlContent = inputHtmlContent;
}
AlternateView av2 = AlternateView.CreateAlternateViewFromString(outputHtmlContent,
null, MediaTypeNames.Text.Html);
foreach (LinkedResource linkedResource in myResources)
{
av2.LinkedResources.Add(linkedResource);
}
msg.AlternateViews.Add(av2);
请帮我解决这个问题,如何显示电子邮件正文中的所有图像?...
您可以将图像附加到邮件中,然后放入img
标记和使用ContentId https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.attachment.contentid(v=exchg.80).aspx附件为src
这边走:
private void denMailButton_Click(object sender, EventArgs e)
{
string subject = "Subject";
string body = @"Image 1: <img src=""$CONTENTID1$""/> <br/> Image 2: <img src=""$CONTENTID2$""/> <br/> Some Other Content";
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected] /cdn-cgi/l/email-protection");
mail.To.Add(new MailAddress("[email protected] /cdn-cgi/l/email-protection"));
mail.Subject = subject;
mail.Body = body;
mail.Priority = MailPriority.Normal;
string contentID1 = Guid.NewGuid().ToString().Replace("-", "");
string contentID2 = Guid.NewGuid().ToString().Replace("-", "");
body = body.Replace("$CONTENTID1$", "cid:" + contentID1);
body = body.Replace("$CONTENTID2$", "cid:" + contentID2);
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
//path of image or stream
LinkedResource imagelink1 = new LinkedResource(@"D:\1.png", "image/png");
imagelink1.ContentId = contentID1;
imagelink1.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(imagelink1);
LinkedResource imagelink2 = new LinkedResource(@"D:\2.png", "image/png");
imagelink2.ContentId = contentID2;
imagelink2.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(imagelink2);
mail.AlternateViews.Add(htmlView);
SmtpClient client = new SmtpClient();
client.Host = "mail.example.com";
client.Credentials = new NetworkCredential("[email protected] /cdn-cgi/l/email-protection", "password");
client.Send(mail);
}
这是屏幕截图:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)