go发送邮件

go发送邮件


🚀 Go 发送邮箱验证码 (基于 gomail)

安装依赖

1
go get gopkg.in/gomail.v2

后端代码 (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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main

import (
"encoding/json"
"log"
"math/rand"
"net/http"
"time"

"gopkg.in/gomail.v2"
)

// 邮件配置
const (
smtpHost = "smtp.example.com" // SMTP 服务器地址,例如 smtp.qq.com / smtp.163.com / smtp.gmail.com
smtpPort = 587 // SMTP 端口,QQ/163 推荐 465 或 587
email = "your@email.com" // 发件人邮箱
password = "yourpassword" // 授权码(不是登录密码)
)

// 内存保存验证码,简单实现 (生产建议用 Redis/数据库)
var codeStore = make(map[string]string)

// 生成随机验证码
func generateCode(length int) string {
rand.Seed(time.Now().UnixNano())
digits := "0123456789"
code := ""
for i := 0; i < length; i++ {
code += string(digits[rand.Intn(len(digits))])
}
return code
}

// 发送验证码邮件
func sendEmail(to string, code string) error {
m := gomail.NewMessage()
m.SetHeader("From", email)
m.SetHeader("To", to)
m.SetHeader("Subject", "您的验证码")
m.SetBody("text/html", "<h2>验证码</h2><p>您的验证码是:<b>"+code+"</b></p><p>有效期 5 分钟。</p>")

d := gomail.NewDialer(smtpHost, smtpPort, email, password)
return d.DialAndSend(m)
}

// 请求验证码接口
func sendCodeHandler(w http.ResponseWriter, r *http.Request) {
type req struct {
Email string `json:"email"`
}
var in req
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Email == "" {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}

code := generateCode(6)
codeStore[in.Email] = code

if err := sendEmail(in.Email, code); err != nil {
http.Error(w, "send mail failed: "+err.Error(), http.StatusInternalServerError)
return
}

resp := map[string]string{"msg": "验证码已发送"}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}

// 验证验证码接口
func verifyCodeHandler(w http.ResponseWriter, r *http.Request) {
type req struct {
Email string `json:"email"`
Code string `json:"code"`
}
var in req
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}

ok := codeStore[in.Email] == in.Code
resp := map[string]bool{"ok": ok}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}

func main() {
http.HandleFunc("/send-code", sendCodeHandler)
http.HandleFunc("/verify-code", verifyCodeHandler)
http.Handle("/", http.FileServer(http.Dir("."))) // 提供 index.html

log.Println("Server running at http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}

前端页面 (index.html)

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>邮箱验证码 Demo</title>
</head>
<body>
<h3>邮箱验证码 Demo</h3>

<div>
<input type="email" id="email" placeholder="输入邮箱地址" />
<button onclick="sendCode()">发送验证码</button>
</div>

<div>
<input type="text" id="code" placeholder="输入收到的验证码" />
<button onclick="verify()">验证</button>
</div>

<p id="result"></p>

<script>
async function sendCode() {
let email = document.getElementById("email").value;
let res = await fetch("/send-code", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({email})
});
let data = await res.json();
document.getElementById("result").innerText = data.msg || "已发送";
}

async function verify() {
let email = document.getElementById("email").value;
let code = document.getElementById("code").value;
let res = await fetch("/verify-code", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({email, code})
});
let data = await res.json();
document.getElementById("result").innerText = data.ok ? "✅ 验证成功" : "❌ 验证失败";
}
</script>
</body>
</html>

🔹 使用流程

  1. 在邮箱服务商(QQ 邮箱、163、Gmail 等)开启 SMTP 并获取授权码。

  2. 修改 smtpHost、smtpPort、email、password 配置。

  3. 启动服务:

    1
    go run main.go
  4. 打开浏览器访问 http://localhost:8080/

  5. 输入邮箱 → 点击 “发送验证码” → 去邮箱查收 → 输入验证码 → 点击 “验证”。


🚀 Go 发送邮箱验证码 (基于 jordan-wright/email)


1️⃣ 安装依赖

1
go get github.com/jordan-wright/email

2️⃣ 后端代码 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main

import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"net/smtp"
"time"

"github.com/jordan-wright/email"
)

// 邮件服务器配置
const (
smtpHost = "smtp.example.com" // SMTP 服务器地址(如 smtp.qq.com / smtp.163.com)
smtpPort = "587" // SMTP 端口(25 / 465 / 587)
username = "your@email.com" // 发件人邮箱
password = "yourpassword" // 邮箱授权码(不是登录密码)
)

// 内存存储验证码,实际项目建议用 Redis
var codeStore = make(map[string]string)

// 生成随机验证码
func generateCode(length int) string {
rand.Seed(time.Now().UnixNano())
digits := "0123456789"
code := ""
for i := 0; i < length; i++ {
code += string(digits[rand.Intn(len(digits))])
}
return code
}

// 发送邮件
func sendEmail(to string, code string) error {
e := email.NewEmail()
e.From = username
e.To = []string{to}
e.Subject = "您的验证码"
e.HTML = []byte(fmt.Sprintf("<h2>验证码</h2><p>您的验证码是:<b>%s</b></p><p>有效期 5 分钟。</p>", code))

// 使用 net/smtp 发送
return e.Send(smtpHost+":"+smtpPort,
smtp.PlainAuth("", username, password, smtpHost))
}

// 发送验证码接口
func sendCodeHandler(w http.ResponseWriter, r *http.Request) {
type req struct {
Email string `json:"email"`
}
var in req
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Email == "" {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}

code := generateCode(6)
codeStore[in.Email] = code

if err := sendEmail(in.Email, code); err != nil {
http.Error(w, "send mail failed: "+err.Error(), http.StatusInternalServerError)
return
}

resp := map[string]string{"msg": "验证码已发送"}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}

// 验证验证码接口
func verifyCodeHandler(w http.ResponseWriter, r *http.Request) {
type req struct {
Email string `json:"email"`
Code string `json:"code"`
}
var in req
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}

ok := codeStore[in.Email] == in.Code
resp := map[string]bool{"ok": ok}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}

func main() {
http.HandleFunc("/send-code", sendCodeHandler)
http.HandleFunc("/verify-code", verifyCodeHandler)
http.Handle("/", http.FileServer(http.Dir("."))) // 提供 index.html

log.Println("Server running at http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}

3️⃣ 前端页面 index.html

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>邮箱验证码 Demo</title>
</head>
<body>
<h3>邮箱验证码 Demo (jordan-wright/email)</h3>

<div>
<input type="email" id="email" placeholder="输入邮箱地址" />
<button onclick="sendCode()">发送验证码</button>
</div>

<div>
<input type="text" id="code" placeholder="输入收到的验证码" />
<button onclick="verify()">验证</button>
</div>

<p id="result"></p>

<script>
async function sendCode() {
let email = document.getElementById("email").value;
let res = await fetch("/send-code", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({email})
});
let data = await res.json();
document.getElementById("result").innerText = data.msg || "已发送";
}

async function verify() {
let email = document.getElementById("email").value;
let code = document.getElementById("code").value;
let res = await fetch("/verify-code", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({email, code})
});
let data = await res.json();
document.getElementById("result").innerText = data.ok ? "✅ 验证成功" : "❌ 验证失败";
}
</script>
</body>
</html>

4️⃣ 使用步骤

  1. 在邮箱(QQ/163/Gmail 等)开启 SMTP 服务,获取授权码。

  2. 修改 smtpHostsmtpPortusernamepassword

  3. 启动后端:

    1
    go run main.go
  4. 打开浏览器访问 http://localhost:8080/,输入邮箱地址 → 发送验证码 → 验证。


[up主专用,视频内嵌代码贴在这]