golang,go,博客,开源,编程

golang每日一库之gomail.v2

Updated on with 0 views and 0 comments

我今天要介绍的gmail库是一个简单易用的 Golang 邮件发送库

支持 SMTP 发送、附件、HTML 邮件、TLS 加密等功能。适用于发送通知、验证码、报告等邮件。


安装

go get gopkg.in/gomail.v2

基本用法

1. 发送简单邮件

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 服务器、端口、账号和密码需要替换成实际值。


进阶用法

2. 发送 HTML 格式邮件

m.SetBody("text/html", "<h1>Hello!</h1><p>This is an <b>HTML</b> email.</p>")

3. 添加抄送(CC)和密送(BCC)

m.SetHeader("Cc", "cc@example.com")    // 抄送
m.SetHeader("Bcc", "bcc@example.com")  // 密送

4. 添加附件

m.Attach("path/to/file.pdf")  // 添加附件

5. 发送邮件到多个收件人

m.SetHeader("To", "user1@example.com", "user2@example.com")

6. 发送邮件时使用 TLS

d := gomail.NewDialer("smtp.example.com", 465, "your-email@example.com", "your-password")
d.SSL = true

注意: 有些 SMTP 服务器使用 587 端口时不需要 SSL = true,但 465 端口通常需要。


7.结合text/template使用

在实际应用中,邮件内容通常不是静态的,而是动态生成的,比如通知邮件、验证码邮件等。Go 提供了 text/template(纯文本邮件)和 html/template(HTML 邮件)来生成动态内容。


示例 1:使用 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 发送。

示例 2:使用 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> 等标签。
  • 生成的 HTML 邮件比纯文本邮件更美观,并支持超链接。
  • SetBody("text/html", body) 发送 HTML 格式的邮件。

示例 3:发送带附件的 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") 添加附件。
  • 适用于发送报表、日志、文件等邮件。

SMTP 配置示例

Gmail

d := gomail.NewDialer("smtp.gmail.com", 587, "your-email@gmail.com", "your-app-password")

⚠ 重要提示: Gmail 不支持直接使用密码登录 SMTP,需要 开启应用专用密码

Outlook / Hotmail

d := gomail.NewDialer("smtp.office365.com", 587, "your-email@outlook.com", "your-password")

QQ 邮箱

d := gomail.NewDialer("smtp.qq.com", 587, "your-email@qq.com", "your-smtp-auth-code")

⚠ 重要提示: QQ 邮箱需要在 邮箱设置 中开启 SMTP 服务 并获取授权码。


错误处理

可以使用 DialAndSend 直接发送,但如果要更细粒度控制,可以使用 DialSend

s, err := d.Dial()
if err != nil {
    panic(err)
}

if err := s.Send(m); err != nil {
    panic(err)
}

好处: 当发送多封邮件时,可以先 Dial(),然后多次 Send(),减少 SMTP 连接开销。


应用场景

  • 用户注册/密码重置邮件
  • 通知/提醒
  • 系统日志/错误报告
  • 批量邮件发送(群发)


标题:golang每日一库之gomail.v2
作者:mooncakeee
地址:http://blog.dd95828.com/articles/2025/03/22/1742613127801.html
联系:scotttu@163.com