Created
February 15, 2017 09:45
-
-
Save ivanmrchk/e30eb45808536159bbec9aac20058b78 to your computer and use it in GitHub Desktop.
Sending email template with golang using gomail v2 and attaching files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
How to do a looping inside the template?
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
hi there, thanks for sharing this... i was wondering can i do tag with the html? as far as i concern it didn't redirect to the intended link.... many thanks :)