Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor views as email templates

I am creating an email engine in mvc3 and I am trying to use razor views as email templates. I heard this is possible but I have not yet found any information about it.

like image 833
sTodorov Avatar asked Dec 06 '10 16:12

sTodorov


People also ask

What is Razor template?

Razor is a templating engine that was introduced with ASP.NET MVC, originally to run on the server and generate HTML to be served to web browsers. The Razor templating engine extends standard HTML syntax with C# so that you can express the layout and incorporate CSS stylesheets and JavaScript easily.


2 Answers

You can use http://razorengine.codeplex.com/ to achieve this. It allows you to use razor outside of mvc.

string Email = "Hello @Model.Name! Welcome to Razor!"; string EmailBody = Razor.Parse(Email, new { Name = "World" }); 

It's simple to implement and it's available on http://nuget.codeplex.com/ for easy integration into your projects.

like image 198
Buildstarted Avatar answered Oct 21 '22 16:10

Buildstarted


You CAN use a template file to serve as a razor email body template. You can use whichever extension you choose because you can load a file as text in .Net. Let's use the following example for the template:

Hello @Model.Name,  Welcome to @Model.SiteName!  Regards, Site Admins 

Save that file as something like "WelcomeMessage.cshtml", "WelcomeMessage.template", etc. Select the file in Solution Explorer and in the Properties window, select "Copy to Output Directory" and choose "Copy Always". The only down point is that this template has to accompany the application and doesn't compile as a class.

Now we want to parse it as a string to assign to a mail message body. Razor will take the template and a model class, parse them, and then return a string with the necessary values. In your application you will need to add the RazorEngine package which can be found with NuGet. Here's a short code example to illustrate the usage:

using System.IO; using RazorEngine;  // ... MyModel model = new MyModel { Name = "User", SiteName = "Example.com" }; string template = File.OpenText("WelcomeMessage.template").ReadToEnd(); string message = Razor.Parse(template, model); 

It's similar to the other answers but shows a quick way to load the template from a text file.

like image 34
Jeff LaFay Avatar answered Oct 21 '22 14:10

Jeff LaFay