简介
根据产品需求,需要实现监控告警功能,在告警产生和恢复时向相关人员发送邮件,初步方案是使用QQ邮箱SMTP服务来实现,先实现功能后续再进行优化。
如何开启QQ邮箱SMTP服务,请百度搜索“QQ邮箱SMTP服务”参考相关文档,可参考如何开启QQ邮箱的SMTP服务和设置授权码。
示例代码
注意:代码仅作参考,请自行替换代码中发送邮箱地址、授权码、目的邮箱地址列表、邮件标题、邮件内容
package main
import (
"crypto/tls"
"fmt"
"gopkg.in/gomail.v2"
)
func main() {
// TODO: 替换发送邮箱地址、授权码、目的邮箱地址列表、邮件标题、邮件内容
sendEmailAddr := "xxx@qq.com"
password := "xxx"
tos := []string{"xxx@qq.com"}
subject := "测试邮件发送"
content := `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试邮件</title>
</head>
<body>
<div>
Just for testing.
</div>
</body>
</html>
`
conf := SMTPConfig{
Host: "smtp.qq.com",
Port: 465,
User: sendEmailAddr,
Password: password,
From: sendEmailAddr,
InsecureSkipVerify: true,
}
d := gomail.NewDialer(conf.Host, conf.Port, conf.User, conf.Password)
if conf.InsecureSkipVerify {
d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
}
m := gomail.NewMessage()
m.SetHeader("From", conf.From)
m.SetHeader("To", tos...)
m.SetHeader("Subject", subject)
m.SetBody("text/html", content)
err := d.DialAndSend(m)
if err != nil {
fmt.Printf("Send email failed: %v.", err)
return
}
fmt.Printf("Send email succeed.")
}
type SMTPConfig struct {
Host string
Port int
User string
Password string
From string
InsecureSkipVerify bool
}