Eitan K
Eitan K

Reputation: 837

How to send email from template using RazorEngine

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);

Upvotes: 5

Views: 4975

Answers (2)

Ehsan Mirsaeedi
Ehsan Mirsaeedi

Reputation: 7592

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.

Upvotes: 3

user1023602
user1023602

Reputation:

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();
   }
}

Upvotes: 4

Related Questions