我正在构建一种方法,该方法将发送带有某些图像的电子邮件。我的模板是基于其视图模型集合的局部视图。图像是我在img标签的src中放入的base64字符串(内联图像),当完全构建部分视图时,我使用RazorEngine将视图解析为字符串,因为我使用该函数发送电子邮件(带有NotificationHubClient)将html字符串作为SendGrid模板的参数发送。
但是,当我收到电子邮件时,图像未显示在任何客户端中,我想电子邮件客户端会阻止嵌入式图像。因此,我认为使用CID来吸引图像。我之前使用过该方法,但是要使CID正常工作,我必须生成一个AlternateView,但是AlternateView仅适用于MailMessage(System.Net.Mail)。
我发现了这个线程:How to convert EmailMessage alternate views into SendGrid Html and Text 我试图建立类似的东西:
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();
}
}
我将返回的字符串作为参数传递给Send函数,但是当我收到邮件时,再次没有显示图像,甚至我的css也消失了。
您知道一种将MailMessage及其AlternateView转换为带有附带图像的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;
}
谢谢。