feat: add mail push

新增电子邮箱推送
This commit is contained in:
Leo Chen
2024-10-27 20:21:34 +08:00
parent ffacfe0f42
commit 0396d8222e
10 changed files with 423 additions and 3 deletions

View File

@@ -6,6 +6,7 @@ const (
NotifyChannelTelegram = "telegram"
NotifyChannelLark = "lark"
NotifyChannelServerChan = "serverchan"
NotifyChannelMail = "mail"
)
type NotifyTestPushReq struct {

58
internal/notify/mail.go Normal file
View File

@@ -0,0 +1,58 @@
package notify
import (
"context"
"net/smtp"
)
type Mail struct {
senderAddress string
smtpHostAddr string
smtpHostPort string
smtpAuth smtp.Auth
receiverAddresses string
}
func NewMail(senderAddress, receiverAddresses, smtpHostAddr, smtpHostPort string) *Mail {
if(smtpHostPort == "") {
smtpHostPort = "25"
}
return &Mail{
senderAddress: senderAddress,
smtpHostAddr: smtpHostAddr,
smtpHostPort: smtpHostPort,
receiverAddresses: receiverAddresses,
}
}
func (m *Mail) SetAuth(username, password string) {
m.smtpAuth = smtp.PlainAuth("", username, password, m.smtpHostAddr)
}
func (m *Mail) Send(ctx context.Context, subject, message string) error {
// 构建邮件
from := m.senderAddress
to := []string{m.receiverAddresses}
msg := []byte(
"From: " + from + "\r\n" +
"To: " + m.receiverAddresses + "\r\n" +
"Subject: " + subject + "\r\n" +
"\r\n" +
message + "\r\n")
var smtpAddress string
// 组装邮箱服务器地址
if(m.smtpHostPort == "25"){
smtpAddress = m.smtpHostAddr
}else{
smtpAddress = m.smtpHostAddr + ":" + m.smtpHostPort
}
err := smtp.SendMail(smtpAddress, m.smtpAuth, from, to, msg)
if err != nil {
return err
}
return nil
}

View File

@@ -106,6 +106,8 @@ func getNotifier(channel string, conf map[string]any) (notifyPackage.Notifier, e
return getWebhookNotifier(conf), nil
case domain.NotifyChannelServerChan:
return getServerChanNotifier(conf), nil
case domain.NotifyChannelMail:
return getMailNotifier(conf), nil
}
return nil, fmt.Errorf("notifier not found")
@@ -166,6 +168,14 @@ func getLarkNotifier(conf map[string]any) notifyPackage.Notifier {
return lark.NewWebhookService(getString(conf, "webhookUrl"))
}
func getMailNotifier(conf map[string]any) notifyPackage.Notifier {
rs := NewMail(getString(conf, "senderAddress"),getString(conf,"receiverAddress"), getString(conf, "smtpHostAddr"), getString(conf, "smtpHostPort"))
rs.SetAuth(getString(conf, "username"), getString(conf, "password"))
return rs
}
func getString(conf map[string]any, key string) string {
if _, ok := conf[key]; !ok {
return ""