func_email.go 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package config
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/xinliangnote/go-gin-api/configs"
  6. "github.com/xinliangnote/go-gin-api/internal/code"
  7. "github.com/xinliangnote/go-gin-api/internal/pkg/core"
  8. "github.com/xinliangnote/go-gin-api/pkg/env"
  9. "github.com/xinliangnote/go-gin-api/pkg/mail"
  10. "github.com/spf13/cast"
  11. "github.com/spf13/viper"
  12. )
  13. type emailRequest struct {
  14. Host string `form:"host"` // 邮箱服务器
  15. Port string `form:"port"` // 端口
  16. User string `form:"user"` // 发件人邮箱
  17. Pass string `form:"pass"` // 发件人密码
  18. To string `form:"to"` // 收件人邮箱地址,多个用,分割
  19. }
  20. type emailResponse struct {
  21. Email string `json:"email"` // 邮箱地址
  22. }
  23. // Email 修改邮件配置
  24. // @Summary 修改邮件配置
  25. // @Description 修改邮件配置
  26. // @Tags API.config
  27. // @Accept application/x-www-form-urlencoded
  28. // @Produce json
  29. // @Param host formData string true "邮箱服务器"
  30. // @Param port formData string true "端口"
  31. // @Param user formData string true "发件人邮箱"
  32. // @Param pass formData string true "发件人密码"
  33. // @Param to formData string true "收件人邮箱地址,多个用,分割"
  34. // @Success 200 {object} emailResponse
  35. // @Failure 400 {object} code.Failure
  36. // @Router /api/config/email [patch]
  37. // @Security LoginToken
  38. func (h *handler) Email() core.HandlerFunc {
  39. return func(c core.Context) {
  40. req := new(emailRequest)
  41. res := new(emailResponse)
  42. if err := c.ShouldBindForm(req); err != nil {
  43. c.AbortWithError(core.Error(
  44. http.StatusBadRequest,
  45. code.ParamBindError,
  46. code.Text(code.ParamBindError)).WithError(err),
  47. )
  48. return
  49. }
  50. options := &mail.Options{
  51. MailHost: req.Host,
  52. MailPort: cast.ToInt(req.Port),
  53. MailUser: req.User,
  54. MailPass: req.Pass,
  55. MailTo: req.To,
  56. Subject: fmt.Sprintf("%s[%s] 邮箱告警人调整通知。", configs.ProjectName, env.Active().Value()),
  57. Body: fmt.Sprintf("%s[%s] 已添加您为系统告警通知人。", configs.ProjectName, env.Active().Value()),
  58. }
  59. if err := mail.Send(options); err != nil {
  60. c.AbortWithError(core.Error(
  61. http.StatusBadRequest,
  62. code.SendEmailError,
  63. code.Text(code.SendEmailError)+err.Error()).WithError(err),
  64. )
  65. return
  66. }
  67. viper.Set("mail.host", req.Host)
  68. viper.Set("mail.port", cast.ToInt(req.Port))
  69. viper.Set("mail.user", req.User)
  70. viper.Set("mail.pass", req.Pass)
  71. viper.Set("mail.to", req.To)
  72. err := viper.WriteConfig()
  73. if err != nil {
  74. c.AbortWithError(core.Error(
  75. http.StatusBadRequest,
  76. code.WriteConfigError,
  77. code.Text(code.WriteConfigError)).WithError(err),
  78. )
  79. return
  80. }
  81. res.Email = req.To
  82. c.Payload(res)
  83. }
  84. }