From caa37b087c8c338a47105463d97394d14bdd522c Mon Sep 17 00:00:00 2001 From: Ulric Qin Date: Tue, 1 Mar 2022 13:44:46 +0800 Subject: [PATCH] use batch send mail --- etc/server.conf | 1 + src/server/config/config.go | 1 + src/server/engine/engine.go | 3 +++ src/server/engine/notify.go | 2 +- src/server/sender/email.go | 26 ++++++++++++++++++++++++++ 5 files changed, 32 insertions(+), 1 deletion(-) diff --git a/etc/server.conf b/etc/server.conf index 12daddd5..6273611b 100644 --- a/etc/server.conf +++ b/etc/server.conf @@ -61,6 +61,7 @@ User = "username" Pass = "password" From = "username@163.com" InsecureSkipVerify = true +Batch = 5 [Alerting] TemplatesDir = "./etc/template" diff --git a/src/server/config/config.go b/src/server/config/config.go index 4ba151fe..7f10242f 100644 --- a/src/server/config/config.go +++ b/src/server/config/config.go @@ -131,6 +131,7 @@ type SMTPConfig struct { Pass string From string InsecureSkipVerify bool + Batch int } type Alerting struct { diff --git a/src/server/engine/engine.go b/src/server/engine/engine.go index d55cf703..c2524c54 100644 --- a/src/server/engine/engine.go +++ b/src/server/engine/engine.go @@ -5,6 +5,7 @@ import ( "time" "github.com/didi/nightingale/v5/src/server/config" + "github.com/didi/nightingale/v5/src/server/sender" promstat "github.com/didi/nightingale/v5/src/server/stat" ) @@ -22,6 +23,8 @@ func Start(ctx context.Context) error { go reportQueueSize() + go sender.StartEmailSender() + return nil } diff --git a/src/server/engine/notify.go b/src/server/engine/notify.go index de0e6a49..2153c84a 100644 --- a/src/server/engine/notify.go +++ b/src/server/engine/notify.go @@ -175,7 +175,7 @@ func handleNotice(notice Notice, bs []byte) { content = "mailbody.tpl not found" } - sender.SendEmail(subject, content, StringSetKeys(emailset)) + sender.WriteEmail(subject, content, StringSetKeys(emailset)) case "dingtalk": if len(dingtalkset) == 0 { continue diff --git a/src/server/sender/email.go b/src/server/sender/email.go index 8dc75b65..5b479565 100644 --- a/src/server/sender/email.go +++ b/src/server/sender/email.go @@ -67,19 +67,45 @@ func StartEmailSender() { var s gomail.SendCloser var open bool + var size int for { select { case m, ok := <-mailch: if !ok { return } + if !open { s = dialSmtp(d) open = true } + if err := gomail.Send(s, m); err != nil { logger.Errorf("email_sender: failed to send: %s", err) + + // close and retry + if err := s.Close(); err != nil { + logger.Warningf("email_sender: failed to close smtp connection: %s", err) + } + + s = dialSmtp(d) + open = true + + if err := gomail.Send(s, m); err != nil { + logger.Errorf("email_sender: failed to retry send: %s", err) + } } + + size++ + + if size >= conf.Batch { + if err := s.Close(); err != nil { + logger.Warningf("email_sender: failed to close smtp connection: %s", err) + } + open = false + size = 0 + } + // Close the connection to the SMTP server if no email was sent in // the last 30 seconds. case <-time.After(30 * time.Second):