Created
December 19, 2016 02:42
-
-
Save austindoeswork/9ee5c36c2579a140e43f2657c65d2c39 to your computer and use it in GitHub Desktop.
This file contains 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" | |
"log" | |
"net/smtp" | |
"text/template" | |
) | |
func main() { | |
sendGmail("sender@domain.com", "<passwd>", "recipient@domain.com", | |
"This is an example subject", | |
"This is an example body", | |
) | |
} | |
func sendGmail(user, pass, recipient, subject, body string) { | |
data := &SmtpTemplateData{ | |
user, | |
recipient, | |
subject, | |
body, | |
} | |
var doc bytes.Buffer | |
t, err := template.New("_").Parse(emailTemplate) | |
if err != nil { | |
log.Print("error trying to parse mail template") | |
} | |
err = t.Execute(&doc, data) | |
if err != nil { | |
log.Print("error trying to execute mail template") | |
} | |
err = smtp.SendMail("smtp.gmail.com:587", | |
smtp.PlainAuth("", user, pass, "smtp.gmail.com"), | |
user, | |
[]string{recipient}, | |
doc.Bytes(), | |
) | |
if err != nil { | |
log.Printf("smtp error: %s", err) | |
return | |
} | |
} | |
type SmtpTemplateData struct { | |
From string | |
To string | |
Subject string | |
Body string | |
} | |
const emailTemplate = `From: {{ .From }}; | |
To: {{ .To }}; | |
Subject: {{ .Subject }} | |
{{ .Body }} | |
Sincerely, | |
{{ .From }} | |
` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment