Question

My application is split into three tiers:

  1. View (MVC)
  2. Business logic (Services)
  3. Data (LINQ / SQL)

Throughout my Services layer, I have calls to an EmailSender service that currently sends plaintext emails via SmtpClient and MailMessage. Pretty standard stuff as far as I know.

I'm now trying to format the body of these emails by using a Razor template that accepts a MailMessage as a model, and generates some HTML that I can stick into the body of the message.

Right now this is what I have:

public void SendAsyncEmail(MailMessage message)
        {
            message.IsBodyHtml = true;

            message.body = {generate html string from body here using razor?}

            // Async code here
        }

Say I define a razor view like this:

@model System.Net.Mail.MailMessage

<div>
    <h1>@Model.Subject</h1>
    <p>@Model.Body</p>
</div>

How can I pass the MailMessage into this view from my service method and generate a string from it for the body of the email?

Was it helpful?

Solution

To render a view you'll need to use a view engine and a view context. The view engine is responsible for finding and rendering a view. The view context contains information about the view and its state.

public ActionResult Index()
{
    StringWriter sw = new StringWriter();
    ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, "Index", "_Layout");
    ViewContext context = new ViewContext(ControllerContext, result.View, ViewData, TempData, sw);
    result.View.Render(context, sw);
    result.ViewEngine.ReleaseView(ControllerContext, result.View);

    string viewString = sw.ToString();

    return Content(viewString);
}

To pass a model use ViewData (i.e. property available from the controller).

ViewData.Model = new MailMessage();

I'd also like to highly recommend Postal and MvcMailer as alternatives to your current approach. Both of them work on the same principle of using views (such as razor) to generate emails. The setup is pretty simple and the rewards are worth it.

If your application uses a lot of emails then I'd suggest you try them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top