sender.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package mail
  2. import (
  3. "crypto/tls"
  4. "github.com/astaxie/beego/logs"
  5. "gopkg.in/gomail.v2"
  6. settings2 "nginx-ui/server/modules/settings"
  7. "strconv"
  8. "strings"
  9. )
  10. type Sender struct {
  11. Server string
  12. Port int
  13. Username string
  14. Password string
  15. Nickname string
  16. Ssl bool
  17. }
  18. func GetDefaultSender() *Sender {
  19. settings := settings2.GetSettings("email")
  20. sender := &Sender{}
  21. for _, v := range settings {
  22. k := v.ConfigKey
  23. if strings.HasSuffix(k, "@server") {
  24. sender.Server = v.ConfigValue
  25. }
  26. if strings.HasSuffix(k, "@port") {
  27. port, err := strconv.Atoi(v.ConfigValue)
  28. if err != nil {
  29. logs.Error("email port is invalid : %s, use 25 replace", v.ConfigValue)
  30. sender.Port = 25
  31. } else {
  32. sender.Port = port
  33. }
  34. }
  35. if strings.HasSuffix(k, "@username") {
  36. sender.Username = v.ConfigValue
  37. }
  38. if strings.HasSuffix(k, "@password") {
  39. sender.Password = v.ConfigValue
  40. }
  41. if strings.HasSuffix(k, "@nickname") {
  42. sender.Nickname = v.ConfigValue
  43. }
  44. if strings.HasSuffix(k, "@ssl") {
  45. sender.Ssl = v.ConfigValue == "Y"
  46. }
  47. }
  48. return sender
  49. }
  50. func SendEmail(to string, subject string, body string, sender *Sender) error {
  51. if sender == nil {
  52. sender = GetDefaultSender()
  53. }
  54. d := gomail.NewDialer(sender.Server, sender.Port, sender.Username, sender.Password)
  55. d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
  56. closer, err := d.Dial()
  57. if err != nil {
  58. logs.Error("dial error: %v", err)
  59. return err
  60. }
  61. defer closer.Close()
  62. m := gomail.NewMessage()
  63. from := m.FormatAddress(sender.Username, sender.Nickname)
  64. m.SetHeader("From", from)
  65. m.SetHeader("To", to)
  66. m.SetHeader("Subject", subject)
  67. m.SetBody("text/html", body)
  68. if err := d.DialAndSend(m); err != nil {
  69. logs.Error("send email error: %v", err)
  70. return err
  71. }
  72. return nil
  73. }