5

[Golang] Send Email Using Gmail

 2 years ago
source link: https://siongui.github.io/2018/04/19/go-send-email-using-gmail/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
[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{"[email protected]"},
              From:    "someone <[email protected]>",
              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)
      }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK