Click here to Skip to main content
15,878,430 members
Articles / Web Development / HTML

ASP.NET MVC WebAPI Email Templating and Localization

Rate me:
Please Sign up or sign in to vote.
4.80/5 (5 votes)
9 Apr 2015CPOL3 min read 35.6K   924   8   5
How to use Razor Views as Email Templates and Localize them using sample WebAPI


In most of the applications, we need to send emails to users. Instead of directly sending emails from various applications, we can write a webapi to do the same so that we can call this Email web API for sending emails from any of the applications.

It does two things in the current example.

  1. Uses the Razor Views as templates to format the email body
  2. Localizes the email based on User Preference

In the below example, I tried to use multiple templates to send list of errors to users in multiple languages. I have used VS2013 to develop this, the source files are attached to the article.

Using the Code

Step 1

Create a new MVC Web API application and in the Controller, add an API SendMail. The method actually takes JSON string as input and sends the email accordingly. The Json string contains a list of To,CC,BCC addresses, information to be sent in email body, subject. Along with these, it contains the Locale in which Email should be sent to user and the template name to be used for formatting the email.

       public void SendMail(JToken Payload) {
           try {
               var emailList = Payload.SelectToken("email").ToObject<List<EmailModel>>();

               foreach (var data in emailList) {

                   //Set Culture
                   Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(
                   Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

                   //Localize the body
                   var model = JsonConvert.DeserializeObject<Errors>(data.EmailBody);
                   string template = File.ReadAllText(
                   data.EmailBody = Razor.Parse<Errors>(template, model);
                   data.EmailSubject = Razor.Parse("@MyWebAPI.Resources.Language.ErrorEmailTitle");

                   //Send Mail
                   var smtpClient = new SmtpClient("", 587) {
                       Credentials = new NetworkCredential("", "password"),
                       EnableSsl = true
                   MailMessage mail = new MailMessage();
                   mail.From = new MailAddress(data.FromAddress);
                   mail.Subject = data.EmailSubject;
                   mail.Body = data.EmailBody;
                   mail.IsBodyHtml = true;
                   if (!string.IsNullOrEmpty(data.EmailIds))
                   if (!string.IsNullOrEmpty(data.EmailIdsCC))
                   if (!string.IsNullOrEmpty(data.EmailIdsBCC))
           } catch (Exception e) {
               //Log Errors

In the above method, Razor.Parse plays a vital role. It takes full Razer View path and model object and returns the new HTML formatted string. RazorView(.cshtml) file acts as an Email Template to format the body.

Step 2

In order to localize the email template, i.e., RazorView we need resource files. So add as many resource files as number of languages required. Here, I have added two resource files (English,French) with all the required phrases.

Image 1

Now add one more resource file (.resx) without any Locale extension, i.e., Language.resx. Now in Language.Designer.cs, add methods to return phrases depending on locale set.

public static string High
           return ResourceManager.GetString("High", resourceCulture);

   public static string at {
       get {
           return ResourceManager.GetString("at", resourceCulture);

   public static string With {
       get {
           return ResourceManager.GetString("With", resourceCulture);

So each word that is required in template should have a method/property here. So by calling this in Razor View, we will display the data.

Step 3

Now design the razor view templates for email body. Depending upon user preference, we will pick the appropriate template. In the below code, we can observe that we are using properties/methods in Language class in order to get the localized phrase.

@using MyWebAPI.Resources;
@using System.Web.WebPages.Razor;

<!DOCTYPE html>
        <h3>@Model.DisplayCount @Language.New.ToLower() @Language.Errors</h3>
    <div class="pmargin">


        @foreach (var error in @Model.ErrorList) {
                <td>@error.LastUpdate </td>
    <br />

Step 4

Finally, define a model to deserialize user input. Here, I have used JSON as payload to the WebApi and designed the model accordingly.

public class EmailModel {
       public string FromAddress { get; set; }

       public string EmailIds { get; set; }

       public string EmailSubject { get; set; }

       public string EmailBody { get; set; }

       public string EmailIdsCC { get; set; }

       public string EmailIdsBCC { get; set; }

       public string EmailTemplate { get; set; }

       public string Locale { get; set; }

Email Model is to deserialize the user input. And in that input, Email body again contains JSON string for list of errors. Hence, multiple models are required.

public class Errors {
      public List<Error> ErrorList { get; set; }

      public int DisplayCount { get; set; }

  public class Error {
      public string Description { get; set; }

      public string Severity { get; set; }

      public DateTime LastUpdate { get; set; }

How to Test this WebAPI?

  1. Create a Website in IIS
  2. In the SendMail API, I have used Gmail SMTP, so please use your gmail credentials in that method.
  3. In fiddler, select POST, Request URL: http://localhost:98/api/Email (use the port number which you have given in IIS) and use the below json as payload (replace the invalid emailids with some valid emailids to test it)
    "email": [
            "fromAddress": "",
            "toAddress": "",
            "subject": "My First WebAPI",
            "body": "{\"errors\":[{\"description\":\"Disconnected\",
            "toAddressCC": "",
            "toAddressBCC": "",
            "emailTemplate": "ErrorsTable",
            "locale": "fr-CA"
            "fromAddress": "",
            "toAddress": "",
            "subject": "My First WebAPI",
            "body": "{\"errors\":[{\"description\":\"Disconnected\",
            "toAddressCC": "",
            "toAddressBCC": "",
            "emailTemplate": "ErrorsList",
            "locale": "en-US"

Points of Interest

Till now, I have learnt so many things by going through the CodeProject articles. This the first time I am trying to write something. So have a glance and revert to me for any questions/comments.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Web Developer
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

QuestionNothing Pin
Member 119595694-Sep-15 2:55
Member 119595694-Sep-15 2:55 
QuestionNuget package RazorEngine for Razor.Parse Pin
ffernandez231-Jun-15 2:57
ffernandez231-Jun-15 2:57 
GeneralMy vote of 5 Pin
Vaso Elias13-Apr-15 0:51
Vaso Elias13-Apr-15 0:51 
GeneralRe: My vote of 5 Pin
Parvathaneni Mamatha13-Apr-15 19:20
professionalParvathaneni Mamatha13-Apr-15 19:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.