mail.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package user
  2. import (
  3. "errors"
  4. "github.com/astaxie/beego/logs"
  5. "nginx-ui/server/base"
  6. "nginx-ui/server/models"
  7. "nginx-ui/server/modules/mail"
  8. "nginx-ui/server/modules/settings"
  9. "strings"
  10. )
  11. var ConfigUserResetPass = "USER_EMAIL_RESET_PASS"
  12. // SendUserResetPassEmail 忘记密码邮件,to: 邮件地址, link: 密码或者链接
  13. func SendUserResetPassEmail(user *models.User, link string) error {
  14. list := settings.GetSettings(ConfigUserResetPass)
  15. if len(list) == 0 {
  16. logs.Warn("not config add user email!")
  17. return errors.New("系统未配置邮件信息")
  18. }
  19. if user.Email == "" {
  20. logs.Warn("user's mail is empty")
  21. return errors.New("账号未绑定邮箱地址!")
  22. }
  23. content := ""
  24. subject := ""
  25. for _, c := range list {
  26. if strings.HasSuffix(c.ConfigKey, "@Content") {
  27. content = c.ConfigValue
  28. } else if strings.HasSuffix(c.ConfigKey, "@Subject") {
  29. subject = c.ConfigValue
  30. }
  31. }
  32. if subject == "" || content == "" {
  33. logs.Warn("subject or content is empty")
  34. return errors.New("系统未正确配置邮件信息!")
  35. }
  36. replaces := []*base.Replace{
  37. base.CreateReplace("{{username}}", user.Nickname),
  38. base.CreateReplace("{{account}}", user.Account),
  39. base.CreateReplace("{{link}}", link),
  40. base.CreateReplace("{{password}}", link),
  41. }
  42. for _, replace := range replaces {
  43. content = strings.ReplaceAll(content, replace.Old, replace.New)
  44. }
  45. err := mail.SendEmail(user.Email, subject, content, nil)
  46. if err != nil {
  47. return errors.New("邮件发送失败,请稍后重试!")
  48. }
  49. return nil
  50. }