【发布时间】:2026-01-10 10:20:04
【问题描述】:
如何在 c# 中动态分配带有内容 id 的 src How to embed multiple images in email body using .NET 但没有得到好主意。 当我提交时,我将能够获取 html 源以及如何动态分配 cid
> >
> > <html>><body><img src="~/Upload/1.jpg"><br><img src="~/Upload/1.jpg" /><br><img
> src="~/Upload/3.jpg"/><br><br>
> > thanks!!!</body></html>
需要转换
我想发送包含多张图片的电子邮件
<html>><body><img src=cid:c1 /><br><img src=cid:c2 /><br><img
src=cid:c3/><br><br>
thanks!!!</body></html>
然后
if (htmlString == null) return null;
var doc = new HtmlDocument();
doc.LoadHtml(htmlString);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//img");
if (nodes == null) return null;
foreach (HtmlNode node in nodes)
{
if (node.Attributes.Contains("src"))
{
string data = node.Attributes["src"].Value;
string base64Data = Regex.Match(data, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
if (base64Data != "")
{
string cid = Guid.NewGuid().ToString();
byte[] binData = Convert.FromBase64String(base64Data);
var stream = new MemoryStream(binData);
string contenttype = "image/" +
Regex.Match(data, @"data:image/(?<type>.+?);(?<data>.+)").Groups["type"]
.Value;
var inline = new Attachment(stream, new ContentType(contenttype));
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = cid;
inline.ContentType.MediaType = contenttype;
mailMessage.Attachments.Add(inline);
node.Attributes["src"].Value = "cid:" + cid;
}
}
动态分配和添加链接资源和替代视图的任何好主意, 给定的代码适用于静态情况
string path = System.Web.HttpContext.Current.Server.MapPath("~/images/Logo.jpg"); // my logo is placed in images folder
//var path=""
var logo = new LinkedResource(path);
logo.ContentId = "companylogo";
logo.ContentType = new ContentType("image/jpeg");
//now do the HTML formatting
AlternateView av1 = AlternateView.CreateAlternateViewFromString(
"<html><body><img src=cid:companylogo/>" +
"<br></body></html>" + strMailContent,
null, MediaTypeNames.Text.Html);
//now add the AlternateView
av1.LinkedResources.Add(logo);
//now append it to the body of the mail
msg.AlternateViews.Add(av1);
【问题讨论】:
-
请提及你的想法@john
标签: c# email razor model-view-controller