sendgrid api key 必须勾选 mail send 权限,否则发邮件返回 unauthorized 或 forbidden;需用 sendgrid-go sdk、验证发件人域名、设 html/文本内容、检查 err、配置 http 超时与连接池,并推荐使用动态模板 id 替代硬编码 html。

SendGrid API Key 权限配置必须选 Mail Send
直接用主账号 API Key 发邮件会失败,错误信息是 Unauthorized 或 Forbidden —— 这是因为 SendGrid 默认 API Key 权限为空。登录 SendGrid 控制台后,进 Settings → API Keys,创建新 Key 时务必勾选 Mail Send(其他权限如 Suppressions 或 Settings 不需要)。已存在的 Key 无法修改权限,只能删掉重建。
生成后把 Key 值存进环境变量,比如:SENDGRID_API_KEY=SG.xxx。Go 程序里用 os.Getenv("SENDGRID_API_KEY") 读取,别硬编码。
用 github.com/sendgrid/sendgrid-go 发送基础 HTML 邮件
官方 SDK 是最稳妥的选择,避免自己拼 JSON 或处理 HTTP 状态码。安装命令:go get github.com/sendgrid/sendgrid-go。
关键点:
-
sgclient := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY"))必须在初始化时传入有效 Key,否则后续调用全返回nil+ 错误 - 收件人地址必须用
sendgrid.NewEmail("Name", "to@example.com")包装,不能直接传字符串;发件人同理,且域名需通过 SendGrid 的Sender Authentication验证(否则会被拒) - HTML 内容设为
msg.SetHTMLContent("<h1>Hi</h1>"),纯文本用SetPlainTextContent;两者可共存,客户端自动择优渲染 - 调用
sgclient.Send(&msg)后一定要检查返回的err,常见失败原因包括:API Key 无效、发件人未验证、收件人格式错误(如含空格)、内容含敏感词触发风控
并发发信时要控制连接池和超时
默认 HTTP 客户端没有设置超时或复用限制,高并发下容易耗尽文件描述符或卡死。建议显式配置:
在 Go 中使用 google/wire 实现编译时依赖注入——wire.NewSet、wire.Build、wire.Bind(接口→实现)、wire.Struct、wire.Value、wire.Interface
client := &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 30 * time.Second,
},
}
sgclient := sendgrid.NewSendClientWithClient(os.Getenv("SENDGRID_API_KEY"), client)
不这么做,可能遇到 net/http: request canceled (Client.Timeout exceeded while awaiting headers) 或 too many open files。
模板 ID 替代硬编码 HTML,但注意参数键名必须匹配
用模板发信更安全可控,避免每次构造 HTML。先在 SendGrid 后台创建模板,拿到模板 ID(形如 d-xxxxxxxxxxxx4xxxxxxxa5xxxxxxxb),然后在 Go 中这样用:
msg.SetTemplateID("d-xxxxxxxxxxxx4xxxxxxxa5xxxxxxxb")
再通过 msg.AddDynamicTemplateData("name", "Alice") 注入变量。注意两点:
- 模板里变量写法必须是
{{.name}}(Go text/template 语法),不是{{name}}或${name} - 如果模板用了嵌套结构(如
{{.user.email}}),就要用msg.AddDynamicTemplateData("user", map[string]string{"email": "a@b.c"}),不能拆成两层调用
模板调试困难,出错时 SendGrid 不返回具体渲染失败原因,只能靠日志打点 + 小范围测试验证结构是否匹配。
golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!










