C# 如何通过运行时电子邮件正文嵌入图像
我们正在尝试通过将图像放置在邮件正文中来发送电子邮件。但它未显示在收到的电子邮件中。这是我将图像附加到电子邮件正文的代码。请帮助我解决此问题C# 如何通过运行时电子邮件正文嵌入图像,c#,model-view-controller,C#,Model View Controller,我们正在尝试通过将图像放置在邮件正文中来发送电子邮件。但它未显示在收到的电子邮件中。这是我将图像附加到电子邮件正文的代码。请帮助我解决此问题 string Body = mainContent.ToString(); AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body.ToString(), null, "text/html"); HtmlDocum
string Body = mainContent.ToString();
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Body.ToString(), null, "text/html");
HtmlDocument document = new HtmlDocument();
document.LoadHtml(Body);
document.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);
string contentId = Guid.NewGuid().ToString();
LinkedResource inline = new LinkedResource(System.Web.Hosting.HostingEnvironment.MapPath("~"+currentSrcValue));
inline.ContentId = contentId;
inline.TransferEncoding = TransferEncoding.Base64;
x.SetAttributeValue("src", "cid:" + inline.ContentId);
htmlView.LinkedResources.Add(inline);
});
string result = document.DocumentNode.OuterHtml;
mail.IsBodyHtml = true;
htmlView = AlternateView.CreateAlternateViewFromString(result.ToString(), null, "text/html");
mail.AlternateViews.Add(htmlView);
构建电子邮件的另一个选项是使用RazorEngine(您必须在项目中安装它) 您可以有如下内容:
mail.Body = Razor.Parse(param1, param2);
其中,param1是cshtml的路径,param2表示模型
通过在模型属性中保留图像的路径,您甚至可以为每封电子邮件创建特定的图片
祝你今天愉快 有关在电子邮件中嵌入图像的简单方法,请参阅