user1526912
user1526912

Reputation: 17280

C# How to populate email body as string from Razor view that includes CSS

In my C# Web MVC app I would like to use the html template found at the link below to send emails:

https://github.com/leemunroe/html-email-template/blob/master/email.html

I found numerous example of how to use Razor views as email templates:

Razor views as email templates http://razorengine.codeplex.com/

However the examples I found are simplified. The challenge I am facing is including CSS double quotes special characters... in the template:

Can anyone steer me in the right direction to populate the body of my email with a razor cshtml file including CSS

Upvotes: 1

Views: 4487

Answers (1)

Add Razor template "Emailtemplate.cshtml" to the Views folder:

@model Person

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Email Template</title>
        <style>
            /* Styles */
        </style>
    </head>
    <body>
        <h2>Razor email template</h2>
        <p>@Model.Name</p>
        <p>@Model.Age</p>
    </body>
</html>

Add the following function to your controller:

private string ConvertViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (StringWriter writer = new StringWriter())
  {
    ViewEngineResult vResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
    ViewContext vContext = new ViewContext(this.ControllerContext, vResult.View, ViewData, new TempDataDictionary(), writer);
    vResult.View.Render(vContext, writer);
    return writer.ToString();
  }
}

with the following using statements:

using System.IO;
using System.Web.Mvc;
using System.Net.Mail;

Now call the function in your controller and send your email:

Person model = new Person();
model.Name = "John";
model.Age = 22;
string HtmlString = ConvertViewToString("~/Views/Emailtemplate.cshtml", model);
sendEmail(HtmlString);

where

private void SendEmail(string emailHmtl)
{
    string sendEmailTo = "[email protected]";
    MailMessage mail = new MailMessage();
    mail.To.Add(new MailAddress(sendEmailTo));
    mail.From = new MailAddress("[email protected]");
    string Subject = "Custom Razor Email template";
    mail.Subject = Subject;
    mail.IsBodyHtml = true;
    string SmtpHost = "your.smtphost";
    mail.Body = emailHmtl;
    SmtpClient smtpClient = new SmtpClient(SmtpHost);
    smtpClient.Port = 25;
    smtpClient.Host = SmtpHost;
    smtpClient.Send(mail);
}

Upvotes: 4

Related Questions