email.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package services
  2. import (
  3. "crypto/tls"
  4. "eta/eta_mobile/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. // 邮箱配置
  28. confMap, e := models.GetBusinessConf()
  29. if e != nil {
  30. err = fmt.Errorf("GetBusinessConf err: %s", e.Error())
  31. return
  32. }
  33. checkArr := []string{
  34. models.BusinessConfEmailServerHost, models.BusinessConfEmailServerPort,
  35. models.BusinessConfEmailSender, models.BusinessConfEmailSenderUserName,
  36. models.BusinessConfEmailSenderPassword,
  37. }
  38. for _, v := range checkArr {
  39. if confMap[v] == "" {
  40. err = fmt.Errorf("%s配置有误", v)
  41. return
  42. }
  43. }
  44. port, _ := strconv.Atoi(confMap[models.BusinessConfEmailServerPort])
  45. if port <= 0 {
  46. port = 587 // 默认587端口
  47. }
  48. m := gomail.NewMessage()
  49. m.SetHeader("From", confMap[models.BusinessConfEmailSender])
  50. m.SetHeader("To", req.ToUser...)
  51. m.SetHeader("Subject", req.Title)
  52. m.SetBody("text/html", req.Content)
  53. d := gomail.NewDialer(confMap[models.BusinessConfEmailServerHost], port, confMap[models.BusinessConfEmailSenderUserName], confMap[models.BusinessConfEmailSenderPassword])
  54. // 解决x509报错的问题。证书不通过。跳过证书验证
  55. config := &tls.Config{ServerName: confMap[models.BusinessConfEmailServerHost], InsecureSkipVerify: true}
  56. d.TLSConfig = config
  57. if e = d.DialAndSend(m); e != nil {
  58. err = fmt.Errorf("邮件发送失败, Err: %s", e.Error())
  59. return
  60. }
  61. success = true
  62. return
  63. }