refactor: re-implement logic of notify

This commit is contained in:
Fu Diwei
2024-11-10 18:03:20 +08:00
parent 150b666d4b
commit 5d93334426
10 changed files with 166 additions and 269 deletions

View File

@@ -2,10 +2,10 @@
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/smtp"
"os"
"github.com/domodwyer/mailyak/v3"
@@ -44,15 +44,25 @@ func (n *EmailNotifier) Notify(ctx context.Context, subject string, message stri
smtpAuth = smtp.PlainAuth("", n.config.Username, n.config.Password, n.config.SmtpHost)
}
var smtpAddr string
if n.config.SmtpPort == 0 {
if n.config.SmtpTLS {
smtpAddr = fmt.Sprintf("%s:465", n.config.SmtpHost)
} else {
smtpAddr = fmt.Sprintf("%s:25", n.config.SmtpHost)
}
} else {
smtpAddr = fmt.Sprintf("%s:%d", n.config.SmtpHost, n.config.SmtpPort)
}
var yak *mailyak.MailYak
if n.config.SmtpTLS {
os.Setenv("GODEBUG", "tlsrsakex=1") // Fix for TLS handshake error
yak, err = mailyak.NewWithTLS(fmt.Sprintf("%s:%d", n.config.SmtpHost, n.config.SmtpPort), smtpAuth, nil)
yak, err = mailyak.NewWithTLS(smtpAddr, smtpAuth, newTlsConfig())
if err != nil {
return nil, err
}
} else {
yak = mailyak.New(fmt.Sprintf("%s:%d", n.config.SmtpHost, n.config.SmtpPort), smtpAuth)
yak = mailyak.New(smtpAddr, smtpAuth)
}
yak.From(n.config.SenderAddress)
@@ -67,3 +77,19 @@ func (n *EmailNotifier) Notify(ctx context.Context, subject string, message stri
return &notifier.NotifyResult{}, nil
}
func newTlsConfig() *tls.Config {
var suiteIds []uint16
for _, suite := range tls.CipherSuites() {
suiteIds = append(suiteIds, suite.ID)
}
for _, suite := range tls.InsecureCipherSuites() {
suiteIds = append(suiteIds, suite.ID)
}
// 为兼容国内部分低版本 TLS 的 SMTP 服务商
return &tls.Config{
MinVersion: tls.VersionTLS10,
CipherSuites: suiteIds,
}
}