Skip to content

Instantly share code, notes, and snippets.

@ivanmrchk
Created February 15, 2017 09:45
Show Gist options
  • Save ivanmrchk/e30eb45808536159bbec9aac20058b78 to your computer and use it in GitHub Desktop.
Save ivanmrchk/e30eb45808536159bbec9aac20058b78 to your computer and use it in GitHub Desktop.
Sending email template with golang using gomail v2 and attaching files.
package main
import (
"bytes"
"html/template"
"log"
gomail "gopkg.in/gomail.v2"
)
type info struct {
Name string
}
func (i info) sendMail() {
t := template.New("template.html")
var err error
t, err = t.ParseFiles("template.html")
if err != nil {
log.Println(err)
}
var tpl bytes.Buffer
if err := t.Execute(&tpl, i); err != nil {
log.Println(err)
}
result := tpl.String()
m := gomail.NewMessage()
m.SetHeader("From", "<SENDER>")
m.SetHeader("To", "<RECIPIENT>")
m.SetAddressHeader("Cc", "<RECIPIENT CC>", "<RECIPIENT CC NAME>")
m.SetHeader("Subject", "golang test")
m.SetBody("text/html", result)
m.Attach("template.html")// attach whatever you want
d := gomail.NewDialer("smtp.gmail.com", 587, "<EMAIL ADDRESS>", "<PASSWORD>")
// Send the email to Bob, Cora and Dan.
if err := d.DialAndSend(m); err != nil {
panic(err)
}
}
func main() {
d := info{"jack"}
d.sendMail()
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
</head>
<body>
<p>
<strong>Hello {{.Name}}</strong>
</p>
</body>
</html>
@mikesetiawira
Copy link

@ggalihpp
Copy link

How to do a looping inside the template?

@mastodilu
Copy link

you can't, but you can use a FuncMap with the template and build your loop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment