email.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package services
  2. import (
  3. "crypto/tls"
  4. "eta_gn/eta_api/models"
  5. "fmt"
  6. "gopkg.in/gomail.v2"
  7. "strconv"
  8. )
  9. type SendEmailReq struct {
  10. Title string `description:"标题"`
  11. Content string `description:"内容"`
  12. ToUser []string `description:"收信人邮箱"`
  13. }
  14. func SendEmail(req SendEmailReq) (success bool, err error) {
  15. if req.Title == "" {
  16. err = fmt.Errorf("邮件主题不可为空")
  17. return
  18. }
  19. if req.Content == "" {
  20. err = fmt.Errorf("邮件内容不可为空")
  21. return
  22. }
  23. if len(req.ToUser) <= 0 {
  24. err = fmt.Errorf("收信人不可为空")
  25. return
  26. }
  27. confMap, e := models.GetBusinessConf()
  28. if e != nil {
  29. err = fmt.Errorf("GetBusinessConf err: %s", e.Error())
  30. return
  31. }
  32. checkArr := []string{
  33. models.BusinessConfEmailServerHost, models.BusinessConfEmailServerPort,
  34. models.BusinessConfEmailSender, models.BusinessConfEmailSenderUserName,
  35. models.BusinessConfEmailSenderPassword,
  36. }
  37. for _, v := range checkArr {
  38. if confMap[v] == "" {
  39. err = fmt.Errorf("%s配置有误", v)
  40. return
  41. }
  42. }
  43. port, _ := strconv.Atoi(confMap[models.BusinessConfEmailServerPort])
  44. if port <= 0 {
  45. port = 587 // 默认587端口
  46. }
  47. m := gomail.NewMessage()
  48. m.SetHeader("From", confMap[models.BusinessConfEmailSender])
  49. m.SetHeader("To", req.ToUser...)
  50. m.SetHeader("Subject", req.Title)
  51. m.SetBody("text/html", req.Content)
  52. d := gomail.NewDialer(confMap[models.BusinessConfEmailServerHost], port, confMap[models.BusinessConfEmailSenderUserName], confMap[models.BusinessConfEmailSenderPassword])
  53. config := &tls.Config{ServerName: confMap[models.BusinessConfEmailServerHost], InsecureSkipVerify: true}
  54. d.TLSConfig = config
  55. if e = d.DialAndSend(m); e != nil {
  56. err = fmt.Errorf("邮件发送失败, Err: %s", e.Error())
  57. return
  58. }
  59. success = true
  60. return
  61. }