【问题标题】:How to send email from template using RazorEngine如何使用 RazorEngine 从模板发送电子邮件
【发布时间】:2016-10-08 23:46:13
【问题描述】:

我正在尝试使用 .cshtml 模板通过 RazorEngine 发送电子邮件。 their site 上的文档显示了如何将它与包含剃刀语法的字符串一起使用。我将如何通过加载 .cshtml 文件来使用它?

这就是我所拥有的

    string templatePath = "~/Templates/InitialApplicationBody.cshtml";
    var result = Engine.Razor.RunCompile(templatePath, "templateKey", null, viewModel);

【问题讨论】:

    标签: asp.net-mvc razor html-email razorengine


    【解决方案1】:

    从 MVC 控制器,很容易从 Razor 视图(CSHTML 文件)生成 HTML。

    我已成功使用Render a view as a string 接受答案中的代码,将其放入基本控制器中。

    // Renders a Razor view, returning the HTML as a string
    protected string RenderRazorViewToString<T>(string viewName, T model) where T : class
    {
        ViewData.Model = model;
    
        using (var sw = new StringWriter())
        {
          var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                               viewName);
    
          var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                            ViewData, TempData, sw);
    
          viewResult.View.Render(viewContext, sw);
          viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    
          return sw.GetStringBuilder().ToString();
       }
    }
    

    【讨论】:

      【解决方案2】:

      Mailzory 项目是发送带有 Razor 模板的电子邮件的便捷选择。 Mailzory 在后台使用 RazorEngine。

      // template path
      var viewPath = Path.Combine("Views/Emails", "hello.cshtml");
      // read the content of template and pass it to the Email constructor
      var template = File.ReadAllText(viewPath);
      
      var email = new Email(template);
      
      // set ViewBag properties
      email.ViewBag.Name = "Johnny";
      email.ViewBag.Content = "Mailzory Is Funny";
      
      // send email
      var task = email.SendAsync("mailzory@outlook.com", "subject");
      task.Wait()
      

      这个项目托管在 Github。 Mailzory 还有一个nuget package

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-17
        • 2015-05-30
        • 1970-01-01
        • 2018-07-11
        • 2020-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多