[英]Send Scheduled Email using email Templates in .NET MVC3 using C#
我正在使用.NET MVC3 Web應用程序,在此我的目標是發送計划使用的電子郵件,在該電子郵件中我將使用電子郵件模板。 我很困惑我應該遵循什么才能實現自己的目標。
我嘗試了MVC Mailer
。 但是它不適用於Scheduler。(Fluent Scheduler)我嘗試將RazorEngine
與Email模板一起使用,但是RazorEngine
地附加了HTML Email Templates
。
請幫忙...
使用RazorEngine
這樣的東西應該會非常簡單:
public bool SendEmailMessage(string template, object viewModel, string to, string @from, string subject, params string[] replyToAddresses)
{
var compiledTemplate = LoadTemplate(template, viewModel);
return SendEmail(from, to, subject, compiledTemplate, from, null, replyToAddresses);
}
public bool SendEmailMessageWithAttachments(string template, object viewModel, string to, string @from, string subject, List<Attachment> attachedFiles, params string[] replyToAddresses)
{
var compiledTemplate = LoadTemplate(template, viewModel);
return SendEmail(from, to, subject, compiledTemplate, from, attachedFiles, replyToAddresses);
}
public string LoadTemplate(string template, object viewModel)
{
var templateContent = AttemptLoadEmailTemplate(template);
var compiledTemplate = Razor.Parse(templateContent, viewModel);
return compiledTemplate;
}
private string AttemptLoadEmailTemplate(string name)
{
if (File.Exists(name))
{
var templateText = File.ReadAllText(name);
return templateText;
}
var templateName = string.Format("~/Data/EmailTemplates/{0}.html", name); //Just put your path to a scpecific template
var emailTemplate = HttpContext.Current.Server.MapPath(templateName);
if (File.Exists(emailTemplate))
{
var templateText = File.ReadAllText(emailTemplate);
return templateText;
}
return null;
}
private bool SendEmail(string from, string to, string subject, string body, string replyTo, List<Attachment> attachedFiles, params string[] replyToAddresses)
{
replyTo = replyTo ?? from;
attachedFiles = attachedFiles ?? new List<Attachment>();
var message = new MailMessage(from, to, subject, body);
message.ReplyToList.Add(replyTo);
foreach (var attachedFile in attachedFiles)
message.Attachments.Add(attachedFile);
try
{
smtpClient.SendAsync(email, null);
return true;
}
catch (Exception exption)
{
return false;
}
}
希望能幫助到你
編輯:
假設您有一個名為“ TestTemplate”的模板:
親愛的@ Model.Name
試想一下,如果這是一個普通的cshtml視圖,然后將模型屬性放置為:@ Model.SomeProperty
干杯。
在前一個模板位於我的輔助方法AttempLoadEmailTemplate中的路徑前綴中的情況下,您可以發送如下電子郵件:
var viewModel = new { Name = "Aks", SomeProperty = "Foo" };
mailService.SendEmailMessage("TestTemplate", viewModel, "aks@gmail.com", "daniel@gmail.com", "testing razor engine", null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.