我使用MVCMailer和asp.net MVC 3。 这是一个很棒的图书馆,但我有一个问题。
我看到可以将图像嵌入电子邮件中,如下所示:
var resources = new Dictionary<string, string>();
resources["image"] = imagePath;
PopulateBody(mailMessage, "WelcomeMessage", resources);
因此看起来“资源”期望从文件系统到图像的路径,但是,我的图像在内存流中。
是否可以直接将图像作为base64嵌入,而无需在磁盘上实际写入文件然后传递路径?
感谢您的帮助!
答案 0 :(得分:1)
Baucause MVCMailer基于System.Net.Mail,很容易将LinkedResource添加为流。
以下是修复:
在ILinkedResourceProvider.cs中添加:
List<LinkedResource> GetAll(Dictionary<string, MemoryStream> resources);
LinkedResource Get(string contentId, MemoryStream stream);
LinkedResourceProvider中的添加:
public virtual List<LinkedResource> GetAll(Dictionary<string, MemoryStream> resources)
{
var linkedResources = new List<LinkedResource>();
foreach (var resource in resources)
{
linkedResources.Add(Get(resource.Key, resource.Value));
}
return linkedResources;
}
public virtual LinkedResource Get(string contentId, MemoryStream stream)
{
LinkedResource resource = new LinkedResource(stream);
resource.ContentId = contentId;
return resource;
}
在MailerBase.cs中添加:
public virtual void PopulateBody(MailMessage mailMessage, string viewName, Dictionary<string, MemoryStream> linkedResources)
{
PopulateBody(mailMessage, viewName, null, linkedResources);
}
public virtual void PopulateBody(MailMessage mailMessage, string viewName, string masterName = null, Dictionary<string, MemoryStream> linkedResources = null)
{
if (mailMessage == null)
{
throw new ArgumentNullException("mailMessage", "mailMessage cannot be null");
}
masterName = masterName ?? MasterName;
var linkedResourcesPresent = linkedResources != null && linkedResources.Count > 0;
var textExists = TextViewExists(viewName, masterName);
//if Text exists, it always goes to the body
if (textExists)
{
PopulateTextBody(mailMessage, viewName, masterName);
}
// if html exists
if (HtmlViewExists(viewName, masterName))
{
if (textExists || linkedResourcesPresent)
{
PopulateHtmlPart(mailMessage, viewName, masterName, linkedResources);
}
else
{
PopulateHtmlBody(mailMessage, viewName, masterName);
}
}
}
public virtual AlternateView PopulateHtmlPart(MailMessage mailMessage, string viewName, string masterName, Dictionary<string, MemoryStream> linkedResources)
{
var htmlPart = PopulatePart(mailMessage, viewName, "text/html", masterName);
if (htmlPart != null)
{
PopulateLinkedResources(htmlPart, linkedResources);
}
return htmlPart;
}
public virtual List<LinkedResource> PopulateLinkedResources(AlternateView mailPart, Dictionary<string, MemoryStream> resources)
{
if (resources == null || resources.Count == 0)
return new List<LinkedResource>();
var linkedResources = LinkedResourceProvider.GetAll(resources);
linkedResources.ForEach(resource => mailPart.LinkedResources.Add(resource));
return linkedResources;
}
希望它将成为下一个MVCMailer发布的一部分。