Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: How to send an html email using a controller?

What would be the simplest way to send a customised html email using asp.net?

I suppose ideally I would like to send html via email rather than returning it to the browser via a ActionResult, as I normally would. This way I could build the email as a view, supply it with data via a model and then fire it using standard .NET email stuff.

It this feasible / the way to do it?

Thanks,

like image 509
Sergio Avatar asked Oct 28 '09 15:10

Sergio


3 Answers

This blog post has a good solution for rendering a View to a string so you can send it in email.

/// Static Method to render string - put somewhere of your choosing
public static string RenderPartialToString(string controlName, object viewData)
{
     ViewDataDictionary vd = new ViewDataDictionary(viewData);
     ViewPage vp = new ViewPage { ViewData = vd };
     Control control = vp.LoadControl(controlName);

     vp.Controls.Add(control);

     StringBuilder sb = new StringBuilder();
     using (StringWriter sw = new StringWriter(sb))
     {
         using (HtmlTextWriter tw = new HtmlTextWriter(sw))
         {
             vp.RenderControl(tw);
         }
     }

     return sb.ToString();
}
like image 103
Ian Mercer Avatar answered Sep 28 '22 03:09

Ian Mercer


I think sending email in mvc is just the same as in web form, you just need to set the atribute of the mail message to html enabled then it is food to go. Like this code

MailMessage mm = new MailMessage(emmailFrom,emailTo);
mm.Subject = "Your Subject";
mm.IsBodyHtml = true;
mm.Body = body.ToString();

SmtpClient smtp = new SmtpClient();
smtp.Send(mm);
like image 33
tuanvt Avatar answered Sep 28 '22 03:09

tuanvt


I use MVC Mailer for all my Email Needs

see the project link below for more information

https://github.com/smsohan/MvcMailer

like image 32
Seth IK Avatar answered Sep 28 '22 05:09

Seth IK