使用 Go 透過 SMTP 服務寄送電子郵件

前言

本文使用 Gmail 提供的 SMTP server 做為範例。

前置作業

首先,到 Google 帳戶的「安全性」頁面,設定以下:

  • 啟用兩步驟驗證(2-Step Verification)
  • 新增應用程式密碼(App passwords)

實作

新增 main.go 檔:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
"log"
"net/smtp"
)

func main() {
addr := "smtp.gmail.com:587"
host := "smtp.gmail.com"
identity := ""
from := "" // 寄件者
password := "" // 應用程式密碼
to := "" // 收件者
subject := "This is an example email"
body := "Hello"
msg := "From:" + from + "\r\n" + "To:" + to + "\r\n" + "Subject:" + subject + "\r\n" + body

err := smtp.SendMail(
addr,
smtp.PlainAuth(identity, from, password, host),
from,
[]string{to},
[]byte(msg),
)

if err != nil {
log.Println(err)
}
}

寄送郵件。

1
go run main.go

程式碼