一,安装第三方库:
$ go get -u github.com/jordan-wright/email
go: downloading github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible
go: added github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible
二,代码:
1,发送邮件函数
package serviceimport ("crypto/tls""fmt""github.com/jordan-wright/email""net/smtp"
)//发送邮件,to:收件人,
//subject:标题
//content:邮件内容
func SendOneEmail(to,subject,content string) error {//定义发件邮箱密码等 信息frombox:="chinal@163.com" //发件邮箱fromUser:="管理员 <chinal@163.com>" //显示的用户名smtpNoPort:="smtp.163.com" //hostsmtpPort:= "smtp.163.com:465" //host带portsmtpAuthPass :="Bxxxxxxxxxx4" //auth pass//执行邮件发送e := email.NewEmail()e.From = fromUser //要显示用户名e.To = []string{to} //收件人// 主要就是在这里添加了抄送人cc以及秘密抄送人bcc//e.Cc = []string{"1315381111@qq.com"}//e.Bcc = []string{"1315381111@qq.com"}e.Subject = subject//text是文本型内容,HTML是网页型内容//e.Text = []byte("测试抄送和密码抄送邮件,收到可以忽略")e.HTML = []byte(content)//登录验证auth:=smtp.PlainAuth("", frombox, smtpAuthPass, smtpNoPort)//send方法表示不使用tls,SendWithTLS则使用tls//err := e.Send(smtpPort, auth)err := e.SendWithTLS(smtpPort, auth, &tls.Config{ServerName: smtpNoPort})if err != nil {fmt.Println(err)return err}return nil
}
2,调用:
//准备需要的数据email:="laoliu@niubi.com" //收件人subject:="重置密码信息" //标题//内容html:="密码重置<br>您好"+username+"!<br/>你已经请求了重置密码,可以点击下面的链接来重置密码。<br><br><br>"//发送邮件err2:=service.SendOneEmail(email,subject,html)