forked from ouqiang/gocron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail.go
84 lines (75 loc) · 2.3 KB
/
mail.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
package notify
import (
"github.com/ouqiang/gocron/models"
"github.com/ouqiang/gocron/modules/logger"
"strconv"
"strings"
"github.com/ouqiang/gocron/modules/utils"
"time"
"github.com/go-gomail/gomail"
)
// @author qiang.ou<qingqianludao@gmail.com>
// @date 2017/5/1-00:19
type Mail struct {
}
func (mail *Mail) Send(msg Message) {
model := new(models.Setting)
mailSetting, err := model.Mail()
logger.Debugf("%+v", mailSetting)
if err != nil {
logger.Error("#mail#从数据库获取mail配置失败", err)
return
}
if mailSetting.Host == "" {
logger.Error("#mail#Host为空")
return
}
if mailSetting.Port == 0 {
logger.Error("#mail#Port为空")
return
}
if mailSetting.User == "" {
logger.Error("#mail#User为空")
return
}
if mailSetting.Password == "" {
logger.Error("#mail#Password为空")
return
}
toUsers := mail.getActiveMailUsers(mailSetting, msg)
mail.send(mailSetting, toUsers, msg)
}
func (mail *Mail) send(mailSetting models.Mail, toUsers []string, msg Message) {
body := msg["content"].(string)
body = strings.Replace(body, "\n", "<br>", -1)
gomailMessage := gomail.NewMessage()
gomailMessage.SetHeader("From", mailSetting.User)
gomailMessage.SetHeader("To", toUsers...)
gomailMessage.SetHeader("Subject", "gocron-定时任务监控通知")
gomailMessage.SetBody("text/html", body)
mailer := gomail.NewPlainDialer(mailSetting.Host, mailSetting.Port,
mailSetting.User, mailSetting.Password)
maxTimes := 3
i := 0
for i < maxTimes {
err := mailer.DialAndSend(gomailMessage)
if err == nil {
break;
}
i += 1
time.Sleep(2 * time.Second)
if i < maxTimes {
logger.Errorf("mail#发送消息失败#%s#消息内容-%s", err.Error(), msg["content"])
}
}
}
func (mail *Mail) getActiveMailUsers(mailSetting models.Mail, msg Message) []string {
taskReceiverIds := strings.Split(msg["task_receiver_id"].(string), ",")
users := []string{}
for _, v := range(mailSetting.MailUsers) {
if utils.InStringSlice(taskReceiverIds, strconv.Itoa(v.Id)) {
users = append(users, v.Email)
}
}
return users
}