Skip to content

Instantly share code, notes, and snippets.

@stimpy77
Created December 1, 2015 05:44
Show Gist options
  • Save stimpy77/a49bad26b9fca299332a to your computer and use it in GitHub Desktop.
Save stimpy77/a49bad26b9fca299332a to your computer and use it in GitHub Desktop.
Send e-mail from ASP.NET MVC Razor View
public class EmailController : Controller
{
// GET: Default
[Route("")]
public ActionResult Index()
{
return RedirectToAction(nameof(SendEmail), new
{
To = "Jon Davis <jon@jondavis.net>",
From ="Phil Whiffenfarts <philwhiffenfarts@gmail.com>",
Subject="Yo",
View="OMG"
});
}
[Route("Send")]
[ValidateInput(false)]
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("smtp.west.cox.net");
smtpClient.Send(message);
return Content(body, "text/html");
}
// source: "Listing 1" at http://www.codemag.com/article/1312081
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