将附件的base64图像添加到MailMessage并读入html正文

将附件的base64图像添加到MailMessage并读入html正文

将body的HTML转换为AlternateView的方法完成

bodyHtml 示例:

例子


<img src=\ "data:image/jpeg;base64,---base64string---">


例子


<img src=\ "data:image/png;base64,---base64string---">


某物

使用此方法,您可以在许多 ESP(gmail、outlook 等)中可视化多个图像。

私有静态 AlternateView ContentToAlternateView(字符串内容)
{
变量 imgCount = 0;
列表resourceCollection = 新列表();
foreach (匹配 m in Regex.Matches(content, " <img(? .?)>"))
{
imgCount++;
var imgContent = m.Groups["value"].Value;
字符串类型 = Regex.Match(imgContent, "😦? .
?);base64,").Groups["type"].Value;
string base64 = Regex.Match(imgContent, "base64,(? .*?)"").Groups["base64"].Value;
if (String.IsNullOrEmpty(type) || String.IsNullOrEmpty(base64))
{
//正常匹配时忽略替换标签
继续;
}
var 替换 = " src="cid:" + imgCount + """;
内容 = 内容。替换(imgContent,替换);
var tempResource = new LinkedResource(Base64ToImageStream(base64), new ContentType(type))
{
ContentId = imgCount.ToString()
};
resourceCollection.Add(tempResource);
} AlternateView alternateView = AlternateView.CreateAlternateViewFromString(content, null, MediaTypeNames.Text.Html);
foreach(resourceCollection 中的变量项)
{
alterView.LinkedResources.Add(item);
} 返回备用视图;
}

[

将附件的base64图像添加到MailMessage并读入html正文

将 body HTML 转换为 AlternateView 的完整方法 bodyHtml 示例:示例示例 使用此方法,许多 ESP(gmail、outlook 等)...

编程.c-function.com

](http://programming.c-function.com/c3-1/1001031979.html)

将 Base64 转换为流:

公共静态流 Base64ToImageStream(string base64String)
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
返回毫秒;
}

配置您的电子邮件:

MailMessage 邮件 = 新的 MailMessage();
mail.IsBodyHtml = true;
AlternateView alterView = ContentToAlternateView(bodyHtml);
mail.AlternateViews.Add(alterView);
//更多设置
//...
//////////////
SmtpClient smtp = new SmtpClient(Host, Port) { EnableSsl = false };
smtp.发送(邮件);

在电子邮件消息中嵌入图像:(与将文件附加到非消息中相同)

如果您使用 system.net.mail 命名空间来发送电子邮件,则无需将图像转换为 base64。

var mail = new MailMessage();
var imageToInline = new LinkedResource("你的图片完整路径", MediaTypeNames.Image.Jpeg);
imageToInline.ContentId = "我的图片";
alterView.LinkedResources.Add(imageToInline);
mail.AlternateViews.Add(body);

[

将附件的base64图像添加到MailMessage并读入html正文

将 body HTML 转换为 AlternateView 的完整方法 bodyHtml 示例:示例示例 使用此方法,许多 ESP(gmail、outlook 等)...

编程.c-function.com

](http://programming.c-function.com/c3-1/1001031979.html)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明

本文链接:https://www.qanswer.top/38744/07202310

posted @ 2022-09-23 10:08  哈哈哈来了啊啊啊  阅读(228)  评论(0)    收藏  举报