下面以网易126邮箱为例,若使用其他邮箱,只需把SendEmail方法中的host改成响应邮箱的smtp服务器地址,user填写对应的邮箱地址,pass只需填写你的邮箱密码,并在邮箱设置里面获取授权码。
package main
import (
"gopkg.in/gomail.v2"
"strconv"
)
func SendEmail(mailTo []string, subject string, body string) error {
mailConn := map[string]string{
"user": "xxxxx@126.com",
"pass": "password",
"host": "smtp.126.com",
"port": "465",
}
port, _ := strconv.Atoi(mailConn["port"]) //转换端口类型为int
m := gomail.NewMessage()
m.SetHeader("From", "This is demo "+"<"+mailConn["user"]+">") //这种方式可以添加别名,即“XD Game”, 也可以直接用<code>m.SetHeader("From",mailConn["user"])</code> 读者可以自行实验下效果
m.SetHeader("To", mailTo...) //发送给多个用户
m.SetHeader("Subject", subject) //设置邮件主题
m.SetBody("text/html", body) //设置邮件正文
d := gomail.NewDialer(mailConn["host"], port, mailConn["user"], mailConn["pass"])
err := d.DialAndSend(m)
return err
}
func main() {
mailTo := []string{
"xxxx1@qq.com",
"xxx2@126.com",
}
subject := "Hello"
body := "Good"
_ = SendEmail(mailTo, subject, body)
}