利用Razor產生信件樣版

利用Razor產生信件樣版

網路上其實已經有很多善心人士寫好的外掛函式,其實寫法很簡單,所以後來就自己寫了一個,要調整跟自訂也比較方便。說白了就是利用Razor產生內容字串,不管是要拿來寄信或是要做其它功能都很好用。

{

    [NonAction]
    protected void SendEmail(User user, EmailTemplete templete)
    {
        var email = new EMailContent();
        email.System = Session["SystemTitle"] as string;
        email.Name = user.UserName;

        var content = RenderViewToString("~/Views/Email/Active.cshtml", email);
        SiteUtility.SendEmail(user.Email, email.System + "帳號啟用通知", content);
    }

    [NonAction]
    protected string RenderViewToString(string viewName, object model)
    {
        this.ViewData.Model = model;
        try
        {
            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }
}
Dotblogs 的標籤: ,