28

My console app needs to send HTML emails. I'd like to write the emails in HTML format in a Razor view and have the engine generate the email body content.

This means no controllers or requests. How could I go about this?

Jess
  • 23,901
  • 21
  • 124
  • 145
Roman
  • 10,309
  • 17
  • 66
  • 101
  • 1
    I wonder what would be the answer to this question after 6 years? Now, I have a requirement to parse the HTML template and replace the values using @Model. – Coder Absolute Oct 25 '18 at 12:18

2 Answers2

28

There is an open source project which allows to use Razor as a general templating engine: it's called RazorEngine (the code in on GitHub)

A sample for the project's page:

string template = "Hello @Model.Name! Welcome to Razor!";
string result = Razor.Parse(template, new { Name = "World" });
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • Yes I've seen it but I like the idea of having views in separate files. – Roman Feb 24 '12 at 05:55
  • 4
    You can put your templates in separate files, just load the template from the file and pass it to the engine. – nemesv Feb 24 '12 at 05:57
  • I've downloaded it and messed around before, looks promising. – The Muffin Man Feb 24 '12 at 08:52
  • 1
    I used this but not a huge fan, although I'm not aware of a better alternative. My biggest issue is that I can't get it to support strongly typed models. – Zaid Masud Mar 22 '12 at 16:47
  • 2
    I'm using it and it's quite good. But it has following drawbacks: 1- no strongly type model. 2- you cannot use html helper. So, no partial view then :S!3- if you use version 3.0 it supports layout and section but it is super slow and will kill your machine!! – Azadeh Khojandi Aug 23 '12 at 06:44
  • Just a quick note that it does support strongly typed models. I think it has improved a lot since 2012. – Brian MacKay Dec 26 '16 at 18:02
6

I have a demo project on GitHub that demonstrates how to use Razor views to render content outside of the context of a running ASP.Net application. It provides full support for layouts, _ViewStart files, partials, HtmlHelper, Urlhelper etc.

Note that it uses the RazorGenerator Visual Studio tool to precompile Razor templates.

See my introductory blog post for further background.

Dan Malcolm
  • 4,382
  • 2
  • 33
  • 27