pkg/mail 提供基于 SMTP 的邮件发送能力,支持模板、附件、批量发送与连接池。
Engine、顶层辅助函数集成。type MailConfig
Host / Port / Username / PasswordFrom / FromNameTLStype Mailer
NewMailer(cfg)SendMail:纯文本邮件SendMailHTML:HTML 邮件SendTemplate:渲染模板后发送 HTML 邮件SendBatch:批量发送纯文本邮件ConfigurePool:启用 SMTP 连接池type SMTPPool
NewSMTPPoolGet / Put / Closetype BatchResult
Total / Succeeded / Failed / ErrorsInitDefaultMailer(cfg):初始化全局默认发送器DefaultMailer():获取全局发送器RenderTemplate(templateName, data):渲染 mail/templates 下模板WithMailCCWithMailBCCWithMailReplyToWithMailAttachmentWithMailAttachmentDataWithContinueOnErrorWithMaxConcurrentWithPoolSizeWithPoolMaxIdleWithPoolTimeoutHost:SMTP 主机,必填Port:SMTP 端口,必填Username / Password:认证凭证From:发件人邮箱,必填FromName:发件人显示名称TLS:是否启用 TLS,启用后最小版本为 TLS 1.2WithPoolSize(n):池大小,默认 5WithPoolMaxIdle(d):空闲连接最大存活时间,默认 5mWithPoolTimeout(d):取连接超时,默认 10sWithMaxConcurrent(n):并发 worker 数,默认 1WithContinueOnError(bool):单个失败后是否继续,默认 truemail/templatesRenderTemplate 会校验模板名与路径,避免非法路径访问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
_ = err
gin.WithMail(cfg):初始化 Engine 时注入邮件配置,并自动调用 mail.InitDefaultMailer。gin.SendMailgin.SendMailHTMLgin.SendTemplategin.SendBatche := gin.New(
gin.WithMail(mail.MailConfig{
Host: "smtp.example.com",
Port: 587,
From: "noreply@example.com",
}),
)
_ = gin.SendMail("user@example.com", "标题", "内容")