Sending emails from a Gmail account using Go can be done using Go's smtp package. Simply:
- Connect to
smtp.gmail.comon port 587, authenticating using your email and password - Optionally, use Go's
text/templatepackage to format theTo,From,Subject, andBodyfields of your email - Use
smtp'sSendMailmethod to actually send the email
An example usage follows. The SmtpTemplateData struct is used to hold the context for the templating mentioned in (2) above.
type SmtpTemplateData struct {
From string
To string
Subject string
Body string
}
var err error
var doc bytes.buffer
// Go template
const emailTemplate = `From: {{.From}}
To: {{.To}}
Subject: {{.Subject}}
{{.Body}}
Sincerely,
{{.From}}
`
// Authenticate with Gmail (analagous to logging in to your Gmail account in the browser)
auth := smtp.PlainAuth("", "gmailUsername", "gmailPassword", "smtp.gmail.com")
// Set the context for the email template.
context := &SmtpTemplateData{"Gmail Username <gmailUsername@gmail.com>",
"Recipient Person <recipient.person@gmail.com>",
"RethinkDB is so slick!",
"Hey Recipient, just wanted to drop you a line and let you know how I feel about ReQL..."}
// Create a new template for our SMTP message.
t := template.New("emailTemplate")
if t, err = t.Parse(emailTemplate); err != nil {
log.Print("error trying to parse mail template ", err)
}
// Apply the values we have initialized in our struct context to the template.
if err = t.Execute(&doc, context); err != nil {
log.Print("error trying to execute mail template ", err)
}
// Actually perform the step of sending the email - (3) above
err = smtp.SendMail("smtp.gmail.com:587",
auth,
"gmailUsername",
[]string{"recipient.person@gmail.com"},
doc.Bytes())
if err != nil {
log.Print("ERROR: attempting to send a mail ", err)
}