我正在构建一种方法,该方法将发送带有一些图像的电子邮件。我的模板是基于其视图模型集合的局部视图。图像是我放入 img 标签的 src 中的 base64 字符串(内联图像),当部分视图完全构建时,我使用 RazorEngine 将视图解析为字符串,因为我使用该函数发送电子邮件(使用NotificationHubClient) 将 html 字符串作为 SendGrid 模板的参数发送。
但是,当我收到电子邮件时,图像未显示在任何客户端中,我猜电子邮件客户端会阻止内联图像。所以我想使用 CID 来附加图像。我以前曾使用过该方法,但要使 CID 正常工作,我必须生成一个 AlternateView,但 AlternateView 仅适用于 MailMessage (System.Net.Mail)。
我找到了这个线程:如何将 EmailMessage 备用视图转换为 SendGrid Html 和文本 我尝试构建类似的东西:
public static string GenerateHTML(AlternateView alternateView, string template)
{
MailMessage messageTemp = new MailMessage{ Body = template, IsBodyHtml = true };
messageTemp.AlternateViews.Add(alternateView);
var stream = messageTemp.AlternateViews[0].ContentStream;
using(var rd = new StreamReader(stream))
{
return rd.ReadToEnd();
}
}
我将返回的字符串作为参数传递给发送函数,但是当我收到邮件时,图像再次没有显示,甚至我的 css 也不见了。
您知道将带有 AlternateView 的 MailMessage 转换为带有附加图像的 html 字符串的方法吗?
如果您需要它们,这些是发送电子邮件和生成 AlternateView 的功能。
public static void SendNotification(List<string> recipients, Dictionary<string, string> customParams, string template)
{
string hubURL = ConfigurationManager.AppSettings["NotificationHubUrl"];
string apiKey = ConfigurationManager.AppSettings["NotificationHubApiKey"];
NotificationHubClient.NotificationHubClient client = new NotificationHubClient.NotificationHubClient(hubURL, apiKey);
Dictionary<string, string> authParams = new Dictionary<string, string>();
authParams["username"] = ConfigurationManager.AppSettings["SendGridUser"];
authParams["password"] = ConfigurationManager.AppSettings["SendGridPassword"];
NotificationHubModels.NotificationResponse response = client.SendNotification(new NotificationHubModels.NotificationMessage()
{
Type = "EMAIL",
Provider = "SENDGRID",
Template = template,
CustomParams = customParams,
Recipients = recipients,
ProviderAuthParams = authParams,
});
}
public static AlternateView InsertImages(AlternateView alternateView, IList<Tuple<MemoryStream, string>> images)
{
foreach(var item in images)
{
LinkedResource linkedResource = new LinkedResource(item.Item1, "image/jpg");
linkedResource.ContentId = item.Item2;
linkedResource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
alternateView.LinkedResources.Add(linkedResource);
}
return alternateView;
}
提前致谢。