我想使用Razor視圖引擎生成電子郵件。在Web項目之外使用Razor
從我讀過,我可以使用這些操作系統做的項目,從我的網站:
然而,所有這些使用用戶提交表單並從控制器發送電子郵件的示例。在創建電子郵件時,ControllerContext似乎是必需的。我希望定期在我的「服務」層中進行生成,所以我懷疑我有權訪問ControllerContext。
這是可行的嗎?
我想使用Razor視圖引擎生成電子郵件。在Web項目之外使用Razor
從我讀過,我可以使用這些操作系統做的項目,從我的網站:
然而,所有這些使用用戶提交表單並從控制器發送電子郵件的示例。在創建電子郵件時,ControllerContext似乎是必需的。我希望定期在我的「服務」層中進行生成,所以我懷疑我有權訪問ControllerContext。
這是可行的嗎?
檢查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
我有對於每個模板都是自己的模型,所以很容易通過類名來定位它們。此外,我無法進行智能感知工作。
,所以我用它來獲得外界的asp.net剃鬚刀什麼是CodePlex上找到的剃刀引擎: RazorEngine
嘿!我不能在這裏拉我自己的項目?! :) – Buildstarted 2011-03-30 15:36:56