golang,go,博客,开源,编程
我今天要介绍的gmail库是一个简单易用的 Golang 邮件发送库
支持 SMTP 发送、附件、HTML 邮件、TLS 加密等功能。适用于发送通知、验证码、报告等邮件。
go get gopkg.in/gomail.v2
package main
import (
"gopkg.in/gomail.v2"
)
func main() {
m := gomail.NewMessage()
m.SetHeader("From", "your-email@example.com") // 发件人
m.SetHeader("To", "recipient@example.com") // 收件人
m.SetHeader("Subject", "Hello from Go") // 主题
m.SetBody("text/plain", "This is a test email!") // 邮件正文(纯文本)
d := gomail.NewDialer("smtp.example.com", 587, "your-email@example.com", "your-password")
// 发送邮件
if err := d.DialAndSend(m); err != nil {
panic(err)
}
}
⚠ 注意: SMTP 服务器、端口、账号和密码需要替换成实际值。
m.SetBody("text/html", "<h1>Hello!</h1><p>This is an <b>HTML</b> email.</p>")
m.SetHeader("Cc", "cc@example.com") // 抄送
m.SetHeader("Bcc", "bcc@example.com") // 密送
m.Attach("path/to/file.pdf") // 添加附件
m.SetHeader("To", "user1@example.com", "user2@example.com")
d := gomail.NewDialer("smtp.example.com", 465, "your-email@example.com", "your-password")
d.SSL = true
注意: 有些 SMTP 服务器使用 587 端口时不需要
SSL = true
,但 465 端口通常需要。
在实际应用中,邮件内容通常不是静态的,而是动态生成的,比如通知邮件、验证码邮件等。Go 提供了 text/template
(纯文本邮件)和 html/template
(HTML 邮件)来生成动态内容。
text/template
发送纯文本邮件package main
import (
"bytes"
"fmt"
"gopkg.in/gomail.v2"
"text/template"
)
const textTemplate = `Hello {{.Name}},
Thank you for signing up! Your verification code is: {{.Code}}
Best regards,
Your Company`
func main() {
// 定义模板数据
data := struct {
Name string
Code string
}{
Name: "Alice",
Code: "123456",
}
// 解析模板
tmpl, err := template.New("email").Parse(textTemplate)
if err != nil {
panic(err)
}
// 渲染模板
var body bytes.Buffer
if err := tmpl.Execute(&body, data); err != nil {
panic(err)
}
// 发送邮件
sendEmail("alice@example.com", "Verification Code", body.String())
}
// 发送邮件的函数
func sendEmail(to, subject, body string) {
m := gomail.NewMessage()
m.SetHeader("From", "your-email@example.com")
m.SetHeader("To", to)
m.SetHeader("Subject", subject)
m.SetBody("text/plain", body)
d := gomail.NewDialer("smtp.example.com", 587, "your-email@example.com", "your-password")
if err := d.DialAndSend(m); err != nil {
fmt.Println("Error sending email:", err)
} else {
fmt.Println("Email sent successfully!")
}
}
📌 说明:
textTemplate
,用 {{.Name}}
和 {{.Code}}
作为动态变量。template.New().Parse()
解析模板,然后 tmpl.Execute()
渲染内容。sendEmail()
负责发送邮件,模板内容作为 text/plain
发送。html/template
发送 HTML 邮件package main
import (
"bytes"
"fmt"
"gopkg.in/gomail.v2"
"html/template"
)
const htmlTemplate = `
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Hello {{.Name}},</h1>
<p>Thank you for signing up! Your verification code is: <strong>{{.Code}}</strong></p>
<p>Click <a href="https://example.com/verify?code={{.Code}}">here</a> to verify your account.</p>
</body>
</html>`
func main() {
// 定义模板数据
data := struct {
Name string
Code string
}{
Name: "Alice",
Code: "123456",
}
// 解析模板
tmpl, err := template.New("email").Parse(htmlTemplate)
if err != nil {
panic(err)
}
// 渲染模板
var body bytes.Buffer
if err := tmpl.Execute(&body, data); err != nil {
panic(err)
}
// 发送邮件
sendEmail("alice@example.com", "Welcome to Our Service", body.String())
}
// 发送邮件的函数
func sendEmail(to, subject, body string) {
m := gomail.NewMessage()
m.SetHeader("From", "your-email@example.com")
m.SetHeader("To", to)
m.SetHeader("Subject", subject)
m.SetBody("text/html", body) // 发送 HTML 邮件
d := gomail.NewDialer("smtp.example.com", 587, "your-email@example.com", "your-password")
if err := d.DialAndSend(m); err != nil {
fmt.Println("Error sending email:", err)
} else {
fmt.Println("Email sent successfully!")
}
}
📌 说明:
html/template
渲染 HTML 内容,支持 <h1>
、<p>
、<a>
等标签。SetBody("text/html", body)
发送 HTML 格式的邮件。func sendEmailWithAttachment(to, subject, body, attachmentPath string) {
m := gomail.NewMessage()
m.SetHeader("From", "your-email@example.com")
m.SetHeader("To", to)
m.SetHeader("Subject", subject)
m.SetBody("text/html", body)
// 添加附件
m.Attach(attachmentPath)
d := gomail.NewDialer("smtp.example.com", 587, "your-email@example.com", "your-password")
if err := d.DialAndSend(m); err != nil {
fmt.Println("Error sending email:", err)
} else {
fmt.Println("Email sent successfully with attachment!")
}
}
// 调用
sendEmailWithAttachment("alice@example.com", "Report", "<p>Here is your report.</p>", "report.pdf")
📌 说明:
m.Attach("file.pdf")
添加附件。d := gomail.NewDialer("smtp.gmail.com", 587, "your-email@gmail.com", "your-app-password")
⚠ 重要提示: Gmail 不支持直接使用密码登录 SMTP,需要 开启应用专用密码。
d := gomail.NewDialer("smtp.office365.com", 587, "your-email@outlook.com", "your-password")
d := gomail.NewDialer("smtp.qq.com", 587, "your-email@qq.com", "your-smtp-auth-code")
⚠ 重要提示: QQ 邮箱需要在 邮箱设置 中开启 SMTP 服务 并获取授权码。
可以使用 DialAndSend
直接发送,但如果要更细粒度控制,可以使用 Dial
和 Send
:
s, err := d.Dial()
if err != nil {
panic(err)
}
if err := s.Send(m); err != nil {
panic(err)
}
好处: 当发送多封邮件时,可以先
Dial()
,然后多次Send()
,减少 SMTP 连接开销。