Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Send e-mail from ASP.NET MVC Razor View
public class EmailController : Controller
// GET: Default
public ActionResult Index()
return RedirectToAction(nameof(SendEmail), new
To = "Jon Davis <>",
From ="Phil Whiffenfarts <>",
public ActionResult SendEmail(string to, string from, string subject, string view, object model = null)
ViewBag.To = to;
ViewBag.From = from;
ViewBag.Subject = subject;
var body = RenderViewToString(ControllerContext, view, model);
var message = new MailMessage(from, to, subject, body)
IsBodyHtml = true
var smtpClient = new SmtpClient("");
return Content(body, "text/html");
// source: "Listing 1" at
static string RenderViewToString(ControllerContext context, string viewPath,
object model = null, bool partial = false)
// first find the ViewEngine for this view
var viewEngineResult = partial
? ViewEngines.Engines.FindPartialView(context, viewPath)
: ViewEngines.Engines.FindView(context, viewPath, null);
if (viewEngineResult == null) throw new FileNotFoundException("View cannot be found.");
// get the view and attach the model to view data
var view = viewEngineResult.View;
context.Controller.ViewData.Model = model;
using (var sw = new StringWriter())
var ctx = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, sw);
view.Render(ctx, sw);
return sw.ToString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment