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

后端 未结 5 1411
挽巷
挽巷 2020-12-15 01:32

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 b

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 02:10

    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();
    }
    

提交回复
热议问题