pkg/mail 提供基于 SMTP 的邮件发送能力,支持模板、附件、批量发送与连接池。
- 封装 SMTP 邮件发送流程。
- 提供全局默认发送器,便于与
Engine、顶层辅助函数集成。 - 支持 HTML 模板邮件、附件、批量并发发送、SMTP 连接池复用。
type MailConfigHost/Port/Username/PasswordFrom/FromNameTLS
type MailerNewMailer(cfg)SendMail:纯文本邮件SendMailHTML:HTML 邮件SendTemplate:渲染模板后发送 HTML 邮件SendBatch:批量发送纯文本邮件ConfigurePool:启用 SMTP 连接池
type SMTPPoolNewSMTPPoolGet/Put/Close
type BatchResultTotal/Succeeded/Failed/Errors
InitDefaultMailer(cfg):初始化全局默认发送器DefaultMailer():获取全局发送器RenderTemplate(templateName, data):渲染mail/templates下模板
WithMailCCWithMailBCCWithMailReplyToWithMailAttachmentWithMailAttachmentDataWithContinueOnErrorWithMaxConcurrentWithPoolSizeWithPoolMaxIdleWithPoolTimeout
Host:SMTP 主机,必填Port:SMTP 端口,必填Username/Password:认证凭证From:发件人邮箱,必填FromName:发件人显示名称TLS:是否启用 TLS,启用后最小版本为 TLS 1.2
WithPoolSize(n):池大小,默认5WithPoolMaxIdle(d):空闲连接最大存活时间,默认5mWithPoolTimeout(d):取连接超时,默认10s
WithMaxConcurrent(n):并发 worker 数,默认1WithContinueOnError(bool):单个失败后是否继续,默认true
- 模板目录固定为
mail/templates RenderTemplate会校验模板名与路径,避免非法路径访问
cfg := mail.MailConfig{
Host: "smtp.example.com",
Port: 587,
Username: "noreply@example.com",
Password: "secret",
From: "noreply@example.com",
FromName: "Demo App",
TLS: true,
}
mailer, err := mail.NewMailer(cfg)
if err != nil {
panic(err)
}
err = mailer.SendMail(
"user@example.com",
"欢迎注册",
"欢迎使用 Demo App",
mail.WithMailCC("audit@example.com"),
)err := mailer.SendTemplate(
"user@example.com",
"重置密码",
"reset_password.html",
map[string]any{"Name": "Alice", "Code": "123456"},
)mailer.ConfigurePool(
mail.WithPoolSize(10),
mail.WithPoolMaxIdle(10*time.Minute),
)
result, err := mailer.SendBatch(
[]string{"a@example.com", "b@example.com"},
"系统通知",
"今晚维护",
mail.WithMaxConcurrent(3),
mail.WithContinueOnError(true),
)
_ = result
_ = errgin.WithMail(cfg):初始化Engine时注入邮件配置,并自动调用mail.InitDefaultMailer。- 顶层辅助函数会直接复用默认发送器:
gin.SendMailgin.SendMailHTMLgin.SendTemplategin.SendBatch
e := gin.New(
gin.WithMail(mail.MailConfig{
Host: "smtp.example.com",
Port: 587,
From: "noreply@example.com",
}),
)
_ = gin.SendMail("user@example.com", "标题", "内容")