使用AspNet Razor发送从模板构建的电子邮件

时间:2015-07-24 18:40:34

标签: asp.net asp.net-mvc razor asp.net-core-mvc

我正在尝试创建一个编译Razor视图的方法(我正在使用Asp Net 5)并将其转换为我可以作为电子邮件正文发送的字符串。到目前为止我所拥有的是:

             MailMessage mailmessage  = new MailMessage("email@test.com",email);

        var parser = new RazorParser(new CSharpCodeParser(),
            new HtmlMarkupParser(),
            null);
        var result = parser.Parse(new StringReader("<p>Hello world. The time is @DateTime.UtcNow</p>"));

        mailmessage.Body = ""; // What to put here?

        mailmessage.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient("smtp.test.com");
        smtp.Port = 587;
        smtp.Credentials = // Removed
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        return smtp.SendMailAsync(mailmessage);

我无法弄清楚我需要做些什么来将ParserResult转换为可用于电子邮件正文的东西,我一直在挖掘AspNet源代码但是没有运气,有谁知道怎么做?

1 个答案:

答案 0 :(得分:0)

使用此方法从当前控制器获取视图的内容为字符串:

private string getViewContents(string viewName, object model)
{
  var writer = new StringWriter();

  ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
  var data = new ViewDataDictionary();
  data.Model = model;

  var viewContext = new ViewContext(ControllerContext, viewResult.View, data, new TempDataDictionary(), writer);
  viewResult.View.Render(viewContext, writer);

  return writer.GetStringBuilder().ToString();
}