将正文 HTML 转换为 AlternateView 的完整方法
bodyHtml 示例(您可以将其传递到下面的 MailMessage 代码块中)
<p>example</p>
<p><img src=\ "data:image/jpeg;base64,---base64string---"></p>
<p>example</p>
<p><img src=\ "data:image/png;base64,---base64string---"></p>
<p>something</p>
使用此方法,您可以通过许多 ESP(gmail、outlook 等)可视化多个图像
private static AlternateView ContentToAlternateView(string content)
{
var imgCount = 0;
List<LinkedResource> resourceCollection = new List<LinkedResource>();
foreach (Match m in Regex.Matches(content, "<img(?<value>.*?)>"))
{
imgCount++;
var imgContent = m.Groups["value"].Value;
string type = Regex.Match(imgContent, ":(?<type>.*?);base64,").Groups["type"].Value;
string base64 = Regex.Match(imgContent, "base64,(?<base64>.*?)\"").Groups["base64"].Value;
if (String.IsNullOrEmpty(type) || String.IsNullOrEmpty(base64))
{
//ignore replacement when match normal <img> tag
continue;
}
var replacement = " src=\"cid:" + imgCount + "\"";
content = content.Replace(imgContent, replacement);
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 (var item in resourceCollection)
{
alternateView.LinkedResources.Add(item);
}
return alternateView;
}
将 Base64 转换为流:
public static Stream Base64ToImageStream(string base64String)
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
return ms;
}
设置 MailMessage :
MailMessage mail = new MailMessage();
mail.IsBodyHtml = true;
AlternateView alterView = ContentToAlternateView(bodyHtml);
mail.AlternateViews.Add(alterView);
//more settings
//...
//////////////
SmtpClient smtp = new SmtpClient(Host, Port) { EnableSsl = false };
smtp.Send(mail);