在Google App Engine Go中,可以使用CSS创建电子邮件模板吗?

huangapple go评论102阅读模式
英文:

Is it possible to create email templates with CSS in Google App Engine Go?

问题

我正在创建一个使用GAE Golang应用程序,用于通知用户系统中正在发生的事情。由于我希望邮件看起来漂亮,所以我已经在使用HTMLBody。然而,随着我创建越来越复杂的邮件,我想开始使用类似html/template的东西来创建带有CSS等漂亮外观的邮件。然而,我不确定如何使用Template.Execute将其转换为可以发送的HTMLBody字符串。

我该如何使用类似html/template的东西来创建HTML邮件,并与appengine/mail一起使用?

英文:

I am creating a GAE Golang application that will be notifying users of what is happening in the system. Since I want the emails to look nice, I am already using HTMLBody. However, as I'm creating more and more complex emails, I would like to start using something like html/template to crease nice looking emails with CSS and so forth. However, I'm not sure how I can do Template.Execute to turn it into HTMLBody string that can be sent.

How can I use something like html/template to create HTML emails to use with appengine/mail ?

答案1

得分: 1

你可以将模板渲染到一个临时的字节缓冲区中,像这样:

var tmpl = template.Must(template.ParseFiles("templates/email.html"))

buff := new(bytes.Buffer)
if err = tmpl.Execute(buff, struct{ Name string }{"Juliet"}); err != nil {
    panic(err.Error())
}
msg := &mail.Message{
    Sender:   "romeo@montague.com",
    To:       []string{"Juliet <juliet@capulet.org>"},
    Subject:  "See you tonight",
    Body:     "...you put here the non-HTML part...",
    HTMLBody: buff.String(),
}
c := appengine.NewContext(r)
if err := mail.Send(c, msg); err != nil {
    c.Errorf("Alas, my user, the email failed to sendeth: %v", err)
}
英文:

You can render the template to a temporary byte buffer, like this:

var tmpl = template.Must(template.ParseFiles(&quot;templates/email.html&quot;))

buff := new(bytes.Buffer)
if err = tmpl.Execute(buff, struct{ Name string }{&quot;Juliet&quot;}); err != nil {
    panic(err.Error())
}
msg := &amp;mail.Message{
    Sender:   &quot;romeo@montague.com&quot;,
    To:       []string{&quot;Juliet &lt;juliet@capulet.org&gt;&quot;},
    Subject:  &quot;See you tonight&quot;,
    Body:     &quot;...you put here the non-HTML part...&quot;,
    HTMLBody: buff.String(),
}
c := appengine.NewContext(r)
if err := mail.Send(c, msg); err != nil {
    c.Errorf(&quot;Alas, my user, the email failed to sendeth: %v&quot;, err)
}

huangapple
  • 本文由 发表于 2014年6月7日 10:56:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/24093200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定