Merge branch 'refs/heads/feat-send-mail'

This commit is contained in:
junleea 2025-01-02 15:45:50 +08:00
commit 7607d29386
2 changed files with 78 additions and 0 deletions

View File

@ -31,6 +31,12 @@ type GetFileListReq struct {
Md5 string `json:"md5" form:"md5"`
}
type SendMailReq struct {
Title string `json:"title" form:"title"`
Content string `json:"content" form:"content"`
To string `json:"to" form:"to"`
}
func SetUpToolGroup(router *gin.Engine) {
toolGroup := router.Group("/tool")
toolGroup.POST("/set_redis", SetRedis)
@ -45,6 +51,8 @@ func SetUpToolGroup(router *gin.Engine) {
toolGroup.POST("/file_del", DelFile)
//服务器、设备状态接口
toolGroup.POST("/monitor", SetDeviceStatusV2)
//发送邮件
toolGroup.POST("/send_mail", SendMailTool)
}
func SetDeviceStatusV2(c *gin.Context) {
@ -353,3 +361,36 @@ func SendMail(title, content string) {
fmt.Println(err)
}
}
func SendMailTool(c *gin.Context) {
id, _ := c.Get("id")
id1 := int(id.(float64))
var req SendMailReq
if err := c.ShouldBind(&req); err == nil {
user := dao.FindUserByUserID(id1)
if user.ID == 0 {
c.JSON(http.StatusOK, gin.H{"error": "user not found", "code": proto.ParameterError, "message": "failed"})
return
}
//目标邮箱地址是否合法
if !service.CheckEmail(req.To) {
c.JSON(http.StatusOK, gin.H{"error": "email address is invalid", "code": proto.ParameterError, "message": "failed"})
return
}
if req.Title == "" || req.Content == "" {
c.JSON(http.StatusOK, gin.H{"error": "title or content is empty", "code": proto.ParameterError, "message": "failed"})
return
}
//发送邮件
if user.Role == "admin" {
go service.SendEmail(req.To, req.Title, req.Content)
c.JSON(http.StatusOK, gin.H{"code": proto.SuccessCode, "message": "success", "data": "mail will be sent"})
} else {
c.JSON(http.StatusOK, gin.H{"error": "no send mail permission", "code": proto.PermissionDenied, "message": "failed"})
}
} else {
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": proto.ParameterError, "message": "failed"})
}
}

View File

@ -1,6 +1,8 @@
package service
import (
"fmt"
"regexp"
"time"
"videoplayer/proto"
"videoplayer/worker"
@ -76,3 +78,38 @@ func GetAllRedis() (code int, msg string, data []worker.RedisInfo) {
}
return proto.SuccessCode, "success", data
}
func SendEmail(email, subject, body string) {
//捕获异常
defer func() {
if err := recover(); err != nil {
fmt.Errorf("tool send mail error: %s", err)
}
}()
// TODO
// 发送邮件
// 邮件内容
// 邮件标题
// 收件人
// 发送邮件
// 发送邮件通知
// 发送邮件通知
var em worker.MyEmail
em.SmtpPassword = "nihzazdkmucnbhid"
em.SmtpHost = "pop.qq.com:587"
em.SmtpUserName = "354425203@qq.com"
em.SmtpPort = 587
em.ImapPort = 993
err := em.Send(subject, body, []string{email})
if err != nil {
fmt.Println("send mail error:", err)
}
}
// 地址校验
func CheckEmail(email string) bool {
//正则表达式判断是否是邮箱
pattern := `^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(email)
}