dourui9570 2018-05-04 08:46
浏览 133
已采纳

HTML解析模板以发送电子邮件时未解析

I am working on a SAAS based project for which I need to send emails to different clients on different events.

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.

following is the custom function that I have made to parse these tokens into email body.

    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
}

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.

Can anybody tell me what should I do to parse html in ParseTemplate function?

  • 写回答

2条回答 默认 最新

  • dsaff82024 2018-05-04 15:32
    关注

    You just need to define type EmailTemplate struct as

    type EmailTemplate struct{
        BookingDetails template.HTML
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 计算二重积分∫∫e^(x+y)dxdy,其中0≤x≤1,0≤y≤1,试分别用复合辛普森公式(取n=4)以及高斯求积公式(取n=4)计算积分 给出matlab程序
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的