I am trying to send HTML emails using Golang, but instead of using the native Golang html/template package I am trying to do it with Pongo2.
In this question: Is it possible to create email templates with CSS in Google App Engine Go?
The user is providing this example, which is using the html/template
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: "[email protected]",
To: []string{"Juliet <[email protected]>"},
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)
What I am trying to do
var tmpl = pongo2.Must(pongo2.FromFile("template.html"))
buff := new(bytes.Buffer)
tmpl.Execute(buff, pongo2.Context{"data": "best-data"}, w)
The problem here is that pongo2.Execute() only allows to enter the context data and not the buff.
My end goal is to be able to write my templates using Pongo2, and I can render the HTML in a way where I can also use it for sending my emails.
My question is what I am doing it wrong? It's possible what I am trying to achieve? If I can find a way to render that HTML into a buff, I can use it later as part buff.String()
, which will allow me to enter it in HTML body.
Use ExecuteWriterUnbuffered
instead of Execute
:
tmpl.ExecuteWriterUnbuffered(pongo2.Context{"data": "best-data"}, &buff)
Not sure what w
is doing in your example. If it's another Writer
that you'd like to write too, you can use an io.MultiWriter.
// writes to w2 will go to both buff and w
w2 := io.MultiWriter(&buff, w)