我想使用Razor视图引擎生成电子邮件。
根据我的阅读,我可以使用这些操作系统项目从我的网站上执行此操作:
但是,所有这些都使用用户提交表单并从控制器发送电子邮件的示例。创建电子邮件时,似乎需要ControllerContext。我希望定期在我的“服务”层中进行生成,所以我怀疑我是否可以访问ControllerContext。
这可行吗?
答案 0 :(得分:8)
检查this。我正在使用模板作为这样的嵌入式资源(但可以修改为在任何地方定位模板):
public static class MailSender
{
static MailSender()
{
CompilerServiceFactory = new DefaultCompilerServiceFactory();
TemplateService = new TemplateService(CompilerServiceFactory.CreateCompilerService(), typeof(MailTemplate<>));
}
private static ICompilerServiceFactory CompilerServiceFactory { get; set; }
private static TemplateService TemplateService { get; set; }
private static ITemplate<T> GetTemplate<T>(T model)
{
string path = typeof(T).FullName;
var assembly = Assembly.GetExecutingAssembly();
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path))
{
if (stream == null)
throw new FileNotFoundException("Mail template not found");
using (var reader = new StreamReader(stream))
{
string source = reader.ReadToEnd();
return TemplateService.GetTemplate<T>(source, model);
}
}
}
public static void Send<T>(string to, T model)
{
Send(new string[] { to }, new string[] { }, new string[] { }, model);
}
public static void Send<T>(string to, string cc, string bcc, T model)
{
Send(new string[] { to }, new string[] { cc }, new string[] { bcc }, model);
}
public static void Send<T>(string[] to, string[] cc, string[] bcc, T model)
{
var template = (MailTemplate<T>)GetTemplate<T>(model);
template.Execute();
Trace.WriteLine(string.Format("To: {0} Subject: {1}{3}Body: {2}", string.Join(",", to), template.Subject, template.Result, Environment.NewLine), "Mail");
#if !LOCAL
using (var message = new MailMessage())
using (var client = new SmtpClient())
{
if (!string.IsNullOrWhiteSpace(template.From))
message.From = new MailAddress(template.From);
message.To.Add(string.Join(",", to));
if (cc != null && cc.Length > 0)
message.CC.Add(string.Join(",", cc));
if (bcc != null && bcc.Length > 0)
message.Bcc.Add(string.Join(",", bcc));
message.Subject = template.Subject;
message.Body = template.Result;
message.IsBodyHtml = true;
client.Send(message);
}
#endif
}
}
public abstract class MailTemplate<TModel> : TemplateBase<TModel>
{
public string From { get; set; }
public string Subject { get; set; }
}
模型:
public class Contact
{
public string Name { get; set; }
public string Email { get; set; }
public string Text { get; set; }
}
模板:
@inherits Feedback.Lib.Mail.MailTemplate<Feedback.Lib.Mail.Templates.Contact>
@{
From = string.Format("{0} <{1}>", Model.Name, Model.Email);
Subject = "Contact request - " + From;
}
@Model.Text
我为每个模板都有自己的模型,因此很容易通过类名找到它们。我也无法进行智能感知工作。
答案 1 :(得分:0)
所以我在asp.net外面使用razor是在codeplex上找到的剃刀引擎: RazorEngine