I'd like to make use of the Model Binding / Rendering capabilities of a Razor View to generate the HTML Body Content for an email I'm sending from my ASP.NET MVC Application.
Is there a way to render a view to a string instead of returning it as the ActionResult of a GET request?
To illustrate I'm looking for something that will do the following...
public ActionResult SendEmail(int id)
{
EmailDetailsViewModel emailDetails = EmailDetailsViewModel().CreateEmailDetails(id);
// THIS IS WHERE I NEED HELP...
// I want to pass my ViewModel (emailDetails) to my View (EmailBodyRazorView) but instead of Rending that to the Response stream I want to capture the output and pass it to an email client.
string htmlEmailBody = View("EmailBodyRazorView", emailDetails).ToString();
// Once I have the htmlEmail body I'm good to go. I've got a utilityt that will send the email for me.
MyEmailUtility.SmtpSendEmail("stevejobs@apple.com", "Email Subject", htmlEmailBody);
// Redirect another Action that will return a page to the user confirming the email was sent.
return RedirectToAction("ConfirmationEmailWasSent");
}
There is also Essential Mail: Razor package from NuGet. It is build over RazorEngine and provides simple interface for email rendering.
Email message template looks something like
The project is hosted on GitHub: https://github.com/smolyakoff/essential-templating/wiki/Email-Template-with-Razor
You may checkout Postal for using views for sending emails.
Based on Ryan's answer, I did an extension method:
To call from inside a controller action (example usage):
Another one would be ActionMailer.Net: https://bitbucket.org/swaj/actionmailer.net/wiki/Home
From the website: An MVC 3-based port of the Rails ActionMailer library to ASP.NET MVC. The goal is to make it easy and relatively painless to send email from your application.
NuGet:
Install-Package ActionMailer
Try MvcMailer: http://www.codeproject.com/KB/aspnet/MvcMailerNuGet.aspx
If you just need to render the view into a string try something like this:
You'll need to pass in the name of the view and the ViewData and ControllerContext from your controller action.