123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- package services
- import (
- "crypto/tls"
- "eta_gn/eta_api/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])
- 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
- }
|