开启SMTP服务:
QQ邮箱参考下面连接:
QQ邮箱如何开通SMTP服务
https://jingyan.baidu.com/article/00a07f389eea7dc3d128dc36.html
发邮件测试
package test
import (
"core/define"
"crypto/tls"
"net/smtp"
"testing"
"github.com/jordan-wright/email"
)
func TestSendMail(t *testing.T) {
e := email.NewEmail()
mailUserName := "whm2416@163.com" //邮箱账号
mailPassword := define.MailPassword //邮箱授权码
code := "12345678" //发送的验证码
Subject := "验证码发送测试" //发送的主题
e.From = "Get <whm2416@163.com>"
e.To = []string{"228654416@qq.com"}
e.Subject = Subject
e.HTML = []byte("你的验证码为:<h1>" + code + "</h1>")
err := e.SendWithTLS("smtp.163.com:465", smtp.PlainAuth("", mailUserName, mailPassword, "smtp.163.com"),
&tls.Config{InsecureSkipVerify: true, ServerName: "smtp.163.com"})
if err != nil {
t.Fatal(err)
}
}
func TestSendMailQQ(t *testing.T) {
mailUserName := "whm2416@qq.com" //邮箱账号
mailPassword := define.MailPassword //邮箱授权码
addr := "smtp.qq.com:465" //TLS地址
host := "smtp.qq.com" //邮件服务器地址
code := "12345678" //发送的验证码
Subject := "验证码发送测试" //发送的主题
e := email.NewEmail()
e.From = "Get <whm2416@qq.com>"
e.To = []string{"228654416@qq.com"}
e.Subject = Subject
e.HTML = []byte("你的验证码为:<h1>" + code + "</h1>")
err := e.SendWithTLS(addr, smtp.PlainAuth("", mailUserName, mailPassword, host),
&tls.Config{InsecureSkipVerify: true, ServerName: "smtp.qq.com"})
if err != nil {
t.Fatal(err)
}
}
效果:
业务实现
逻辑层:
func (l *MailCodeSendRegisterLogic) MailCodeSendRegister(req *types.MailCodeSendRequest) (resp *types.MailCodeSendReply, err error) {
// 该邮箱未被注册
cnt, err := models.Engine.Where("email = ?", req.Email).Count(new(models.UserBasic))
if err != nil {
return
}
if cnt > 0 {
err = errors.New("该邮箱已被注册")
return
}
// 获取验证码
code := helper.RandCode()
// 存储验证码
models.RDB.Set(l.ctx, req.Email, code, time.Second*time.Duration(define.CodeExpire))
// 发送验证码
err = helper.MailSendCode(req.Email, code)
return
}
封装包:
// MailSendCode
// 邮箱验证码发送
func MailSendCode(mail, code string) error {
e := email.NewEmail()
e.From = "Get <getcharzhaopan@163.com>"
e.To = []string{"getcharzp@qq.com"}
e.Subject = "验证码发送测试"
e.HTML = []byte("你的验证码为:<h1>" + code + "</h1>")
err := e.SendWithTLS("smtp.163.com:465", smtp.PlainAuth("", "getcharzhaopan@163.com", define.MailPassword, "smtp.163.com"),
&tls.Config{InsecureSkipVerify: true, ServerName: "smtp.163.com"})
if err != nil {
return err
}
return nil
}
func RandCode() string {
s := "1234567890"
code := ""
rand.Seed(time.Now().UnixNano())
for i := 0; i < define.CodeLength; i++ {
code += string(s[rand.Intn(len(s))])
}
return code
}