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