Skip to content

Instantly share code, notes, and snippets.

@sithuwin93
Forked from ivanmrchk/main.go
Created September 9, 2021 03:36
Show Gist options
  • Save sithuwin93/703e24f70d006b60504f4d54883253cd to your computer and use it in GitHub Desktop.
Save sithuwin93/703e24f70d006b60504f4d54883253cd 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment