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 = "asdf@asdf.is";
MailMessage mail = new MailMessage();
mail.To.Add(new MailAddress(sendEmailTo));
mail.From = new MailAddress("asdf@asdf.is");
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);
}