[Golang] Send Email Using Gmail


Sometimes we may want to send mails when some events occurs. This post shows you how to send mails programatically using Gmail.

We use package github.com/jordan-wright/email [2] to send mails, and to read your username and password from console input, we use the SO answer [4]. The following is complete source code:

Required packages:

$ go get -u github.com/jordan-wright/email
$ go get -u golang.org/x/crypto/ssh
$ go get -u golang.org/x/sys/unix

Code:

package main

import (
      "bufio"
      "fmt"
      "net/smtp"
      "net/textproto"
      "os"
      "strings"
      "syscall"

      "github.com/jordan-wright/email"
      "golang.org/x/crypto/ssh/terminal"
)

func credentials() (string, string, error) {
      reader := bufio.NewReader(os.Stdin)

      fmt.Print("Enter Username: ")
      username, _ := reader.ReadString('\n')

      fmt.Print("Enter Password: ")
      bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
      if err != nil {
              return "", "", err
      }
      password := string(bytePassword)

      return strings.TrimSpace(username), strings.TrimSpace(password), nil
}

func main() {
      e := &email.Email{
              To:      []string{"someone@example.com"},
              From:    "someone <someone@example.com>",
              Subject: "Test",
              Text:    []byte("Hello World"),
              Headers: textproto.MIMEHeader{},
      }

      username, password, err := credentials()
      if err != nil {
              panic(err)
      }

      fmt.Println("\nsending mail ...")
      if !strings.HasSuffix(username, "@gmail.com") {
              username += "@gmail.com"
      }
      err = e.Send("smtp.gmail.com:587", smtp.PlainAuth("", username, password, "smtp.gmail.com"))
      if err != nil {
              panic(err)
      }
}

You can even send attachments, see github.com/jordan-wright/email for more options.


Tested on: Ubuntu Linux 17.10, Go 1.10.1

References

[1]
[2]How to send an email with attachments in Go - Stack Overflow
[3]
[4]passwords - getpasswd functionality in Go? - Stack Overflow
[5]What's the recommended encryption library for Go? : golang
[6]sha512 in Go : golang