1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package services
- import (
- "crypto/tls"
- "eta/eta_mobile/models"
- "fmt"
- "gopkg.in/gomail.v2"
- "strconv"
- )
- type SendEmailReq struct {
- Title string `description:"标题"`
- Content string `description:"内容"`
- ToUser []string `description:"收信人邮箱"`
- }
- func SendEmail(req SendEmailReq) (success bool, err error) {
- if req.Title == "" {
- err = fmt.Errorf("邮件主题不可为空")
- return
- }
- if req.Content == "" {
- err = fmt.Errorf("邮件内容不可为空")
- return
- }
- if len(req.ToUser) <= 0 {
- err = fmt.Errorf("收信人不可为空")
- return
- }
- // 邮箱配置
- confMap, e := models.GetBusinessConf()
- if e != nil {
- err = fmt.Errorf("GetBusinessConf err: %s", e.Error())
- return
- }
- checkArr := []string{
- models.BusinessConfEmailServerHost, models.BusinessConfEmailServerPort,
- models.BusinessConfEmailSender, models.BusinessConfEmailSenderUserName,
- models.BusinessConfEmailSenderPassword,
- }
- for _, v := range checkArr {
- if confMap[v] == "" {
- err = fmt.Errorf("%s配置有误", v)
- return
- }
- }
- port, _ := strconv.Atoi(confMap[models.BusinessConfEmailServerPort])
- if port <= 0 {
- port = 587 // 默认587端口
- }
- m := gomail.NewMessage()
- m.SetHeader("From", confMap[models.BusinessConfEmailSender])
- m.SetHeader("To", req.ToUser...)
- m.SetHeader("Subject", req.Title)
- m.SetBody("text/html", req.Content)
- d := gomail.NewDialer(confMap[models.BusinessConfEmailServerHost], port, confMap[models.BusinessConfEmailSenderUserName], confMap[models.BusinessConfEmailSenderPassword])
- // 解决x509报错的问题。证书不通过。跳过证书验证
- config := &tls.Config{ServerName: confMap[models.BusinessConfEmailServerHost], InsecureSkipVerify: true}
- d.TLSConfig = config
- if e = d.DialAndSend(m); e != nil {
- err = fmt.Errorf("邮件发送失败, Err: %s", e.Error())
- return
- }
- success = true
- return
- }
|