How to send email from template using RazorEngine
Asked Answered
E

2

5

I am trying to use a .cshtml template to send an email with RazorEngine. The documentation on their site shows how to use it with a string containing the razor syntax. How would I go about using it by loading a .cshtml file instead?

This is what I have

    string templatePath = "~/Templates/InitialApplicationBody.cshtml";
    var result = Engine.Razor.RunCompile(templatePath, "templateKey", null, viewModel);
Erickericka answered 8/6, 2016 at 15:38 Comment(0)
H
4

From a MVC Controller, it's easy to generate HTML from a Razor view (CSHTML file).

I have successfully used code from the accepted answer to Render a view as a string, putting it in a base controller.

// 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();
   }
}
Hexad answered 8/6, 2016 at 16:7 Comment(0)
J
3

The Mailzory project is a convenient choice for sending emails which have Razor templates. Mailzory uses RazorEngine behind the scene.

// 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("[email protected]", "subject");
task.Wait()

this project is hosted at Github. Also there is a nuget package available for Mailzory.

Janise answered 15/9, 2017 at 3:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.