ASP.Net邮件模板编辑与发送邮件的完美实现

首先明确要求:

1、数据库里存储的是带有标签的,例如:(之所以存储带标签的,是因为可以直接copy出来用html打开进行查看)在这里插入图片描述
2、邮件模板页面编辑展示:(页面富文本编辑器编辑的格式)
在这里插入图片描述

3、发送邮件接收效果展示:
在这里插入图片描述

---------------------------------实现过程------------------------

Controller:(在controller中调用这个方法,该方法可写在controller最下面)

        [HttpGet]
        [UserAuthorizeAttribute]
        public ActionResult Edit(int? id)
        {
            //根据id获取对象obj
            return View(obj);//直接返回该对象
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [UserAuthorizeAttribute]
        public ActionResult Edit(EditEmailTemplate e_EamilTemplate, int? id)
        {
            try
            {
                //根据id获取编辑对象 sysEmail 
                sysEmail.Subject = e_EamilTemplate.Subject;
                sysEmail.Body = StringToLabel(e_EamilTemplate.Body);//这里的方法在controller的最下面有定义
                db.SaveChanges();
                return RedirectToAction("Edit", "EmailTemplates", new { id = id });
            }
            catch (Exception ex)
            {
                return View(e_EamilTemplate);
            }
        }
        [HttpPost]
        [UserAuthorizeAttribute]
        public ActionResult SendTestEmail(string subJect, string body, string sendToEmailAddress)
        {
            try
            {
                body = "<html><head></head><body>" + StringToLabel(body) + "</body></html>";//这里必须这么做,否则邮件接收格式有问题;
                //下面是发送邮件过程,参考SPSmtpClient类发送邮件;
                return Json(1, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(2, JsonRequestBehavior.AllowGet);
            }
        }


private string StringToLabel(string body)
        {
            body = body.Replace("&amp;lt;", "<").Replace("&amp;gt;", ">");//这一行可以省去
            body = body.Replace("&amp;", "&").Replace("&quot;", "\"");
            body = body.Replace("&lt;", "<").Replace("&gt;", ">");
            body = body.Replace("&#39;", "'").Replace("&nbsp;", " ");
            return body;
        }

cshtml:

<div class="form-group row">
                    @Html.LabelFor(model => model.Body, htmlAttributes: new { @class = "col-form-label col-md-2 label_required" })
                    <div class="col-md-9 demo-section editor">
                        @Html.TextAreaFor(model => model.Body, "kendoEditor")<!--这里使用的是kendoEditor富文本编辑器,js中已引用-->
                    </div>
                </div>

js:

$("#sendTestEmail").click(function () {
        var backUrl = window.location.href;
        var EmailAddress = document.getElementById("testEmailAddress").value;
        var Subject = document.getElementById("Subject").value;
        var Body = document.getElementById("Body").value;
        backUrl = backUrl.replace("Edit/" + id, "Index");//这里的id请更具自己的方式获取到,我这里的id代表的是数据库中的key,

        $.ajax({
            type: "POST",
            url: "../SendTestEmail",
            data: {
                "sendToEmailAddress": EmailAddress,
                "subJect": Subject,
                "body": Body
            },
            success: function (data) {
                if (data == 0) {
                    alert("Email Address error");
                }
                else if (data == 1) {
                    alert("Send test email Successd!");
                    window.location.href = backUrl;
                }
                else {
                    alert("Send test email Falid!");
                }
            }
        })
    })

 $(function () {
        function escapeHTML(html) {
            return html.replace(/&lt;/g, "<").replace(/&gt;/g, ">")
        }
        var editor = $("#Body").kendoEditor().data("kendoEditor");//Body指的是标签的id,kendoEditor()指的是富文本编辑器
        var editorVal = $("#Body").val();
        editor.value(escapeHTML(editorVal));
    })

总结:

1、页面使用富文本编辑器编辑的格式在传到controller中被自动转义了两次;比如<p>标签变成了&lt;p&gt;,因此在post–>edit中调用了StringToLabel(string body)方法,然后存储带标签的到数据库中(如最上方的图一)
2、数据库中保存的是带标签的内容:<p><strong>Dear</strong>{%FirstName%} {%LastName%}:</p><p style="text-align:center;">Please use the bel</p>(上方图二),在发送邮件前,则必须使用拼接方式拼接成"<html><head></head><body>" + StringToLabel(body) + "</body></html>"形式,然后传给发送邮件方法的Body,因为这样才是一个完成的HTML;(你也可以在入库的时候,就保存拼接后的格式

说明:
1、由于项目原因,不能直接放上所有代码;(后面有时间会整理放到GitHub上,供大家使用,如果还没有放链接,那就说明我还没整理,嘻嘻嘻
2、是个人原创,欢迎留言讨论;转载请注明

<div class="post-text" itemprop="text"> <p>I am working on a SAAS based project for which I need to send emails to different clients on different events.</p> <p>I am using email templates which use tokens (in format {{.TOKENNAME}}) that are made dynamic while sending emails. Now these token are parsed by using "html/template" package.</p> <p>following is the custom function that I have made to parse these tokens into email body.</p> <pre><code> type EmailTemplate struct{ BookingDetails string } type EmailRequest struct{ EmailTo string EmailBody string } // get saved html with tokens from database notificationTemplate, errVal := merchantDb.GetNotificationTemplate() request := EmailRequest{ "test@example.com", notificationTemplate.Content, } templateData.BookingDetails += "<p><span>Industry</span><span>"+industry.IndustryName+"</span></p>" request.EmailSend(templateData) func (request *EmailRequest) EmailSend(notificationTemplateData interface{}) (bool, error) { body, errParse := ParseTemplate(request.EmailBody, notificationTemplateData) //email sending code here } func ParseTemplate(templateHtml string, data interface{}) (string, error) { var body string t, err := template.New("my_template").Parse(templateHtml) if err != nil { return body, err } buf := new(bytes.Buffer) if err = t.Execute(buf, data); err != nil { return body, err } body = buf.String() return body, nil } </code></pre> <p>Where templateHtml is the email body with tokens and data is the interface holding dynamic values for these tokens. When I use ParseTemplate function to parse tokens as string values then it works fine. But if I have to parse html in one of my tokens then it parses html as string and in email displays html as string.</p> <p>Can anybody tell me what should I do to parse html in ParseTemplate function?</p> </div>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页