Skip to content

Instantly share code, notes, and snippets.

@nathanleclaire
Last active February 24, 2016 19:21
Show Gist options
  • Save nathanleclaire/8662755 to your computer and use it in GitHub Desktop.
Save nathanleclaire/8662755 to your computer and use it in GitHub Desktop.
More terse, technical definition of how to send emails using Golang.

Sending emails from Gmail Using Golang

Sending emails from a Gmail account using Go can be done using Go's smtp package. Simply:

  1. Connect to smtp.gmail.com on port 587, authenticating using your email and password
  2. Optionally, use Go's text/template package to format the To, From, Subject, and Body fields of your email
  3. Use smtp's SendMail method 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)
}
@AHaymond
Copy link

import (
  "bytes"
  "net/smtp"
  "text/template"
)

type SmtpTemplateData struct {
    From    string
    To      string
    Subject string
    Body    string
}

var doc bytes.Buffer

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