Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

implement automatic domain blacklist checking and alerting

lotk7b04a4506768
diff --git a/core/api/settings/settings.go b/core/api/settings/settings.go
index 967a9a53..cc4b6988 100644
--- a/core/api/settings/settings.go
+++ b/core/api/settings/settings.go
@@ -24,4 +24,7 @@ type ISettingsV1 interface {
DeleteReverseProxyDomain(ctx context.Context, req *v1.DeleteReverseProxyDomainReq) (res *v1.DeleteReverseProxyDomainRes, err error)
RegenerateAPIToken(ctx context.Context, req *v1.RegenerateAPITokenReq) (res *v1.RegenerateAPITokenRes, err error)
SetAPIDocSwagger(ctx context.Context, req *v1.SetAPIDocSwaggerReq) (res *v1.SetAPIDocSwaggerRes, err error)
+ SetBlacklistAutoScan(ctx context.Context, req *v1.SetBlacklistAutoScanReq) (res *v1.SetBlacklistAutoScanRes, err error)
+ SetBlacklistAlert(ctx context.Context, req *v1.SetBlacklistAlertReq) (res *v1.SetBlacklistAlertRes, err error)
+ SetBlacklistAlertSettings(ctx context.Context, req *v1.SetBlacklistAlertSettingsReq) (res *v1.SetBlacklistAlertSettingsRes, err error)
}
diff --git a/core/api/settings/v1/settings.go b/core/api/settings/v1/settings.go
index 66a09aa3..18a5398c 100644
--- a/core/api/settings/v1/settings.go
+++ b/core/api/settings/v1/settings.go
@@ -2,6 +2,7 @@ package v1
import (
"billionmail-core/utility/types/api_v1"
+
"github.com/gogf/gf/v2/frame/g"
)
@@ -93,6 +94,24 @@ type SystemConfig struct {
APIDocEnabled bool `json:"api_doc_enabled" dc:"enable API documentation and Swagger UI"`
APIToken string `json:"api_token" dc:"API access token"`
} `json:"api_doc_swagger" dc:"API doc and Swagger UI configuration"`
+
+ // blacklist config
+ BlacklistConfig BlacklistConfig `json:"blacklist_config" dc:"blacklist configuration"`
+}
+
+type BlacklistConfig struct {
+ AutoScanEnabled bool `json:"auto_scan_enabled" dc:"Automatic scanning switch"`
+ AlertEnabled bool `json:"alert_enabled" dc:"Alarm switch"`
+ AlertSettings *BlacklistAlertSettings `json:"alert_settings" dc:"Alarm settings"`
+}
+
+type BlacklistAlertSettings struct {
+ Name string `json:"name" dc:"Alarm sender's name"`
+ SenderEmail string `json:"sender_email" dc:"sender email" v:"required|email"`
+ SMTPPassword string `json:"smtp_password" dc:"SMTP password" v:"required"`
+ SMTPServer string `json:"smtp_server" dc:"SMTP server" v:"required"`
+ SMTPPort int `json:"smtp_port" dc:"SMTP port" v:"required|between:1,65535" d:"587"`
+ RecipientList []string `json:"recipient_list" dc:"recipient list" v:"required"`
}
type GetVersionReq struct {
@@ -229,7 +248,7 @@ type RegenerateAPITokenRes struct {
} `json:"data" dc:"Generated API Token"`
}
-// 设置api文档和Swagger的开启状态
+// Set the status of the API documentation and Swagger
type SetAPIDocSwaggerReq struct {
g.Meta `path:"/settings/set_api_doc_swagger" tags:"Settings" method:"post" summary:"Set API Doc and Swagger UI configuration"`
Authorization string `json:"authorization" in:"header" dc:"Authorization" v:"required"`
@@ -238,3 +257,33 @@ type SetAPIDocSwaggerReq struct {
type SetAPIDocSwaggerRes struct {
api_v1.StandardRes
}
+
+type SetBlacklistAutoScanReq struct {
+ g.Meta `path:"/settings/set_blacklist_auto_scan" tags:"Settings" method:"post" summary:"Set blacklist auto scan switch"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ Enabled bool `json:"enabled" dc:"Automatic scanning switch" v:"required"`
+}
+
+type SetBlacklistAutoScanRes struct {
+ api_v1.StandardRes
+}
+
+type SetBlacklistAlertReq struct {
+ g.Meta `path:"/settings/set_blacklist_alert" tags:"Settings" method:"post" summary:"Set blacklist alert switch"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ Enabled bool `json:"enabled" dc:"Blacklist alarm switch" v:"required"`
+}
+
+type SetBlacklistAlertRes struct {
+ api_v1.StandardRes
+}
+
+type SetBlacklistAlertSettingsReq struct {
+ g.Meta `path:"/settings/set_blacklist_alert_settings" tags:"Settings" method:"post" summary:"Set blacklist alert settings"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ Settings BlacklistAlertSettings `json:"settings" dc:"Alarm settings" v:"required"`
+}
+
+type SetBlacklistAlertSettingsRes struct {
+ api_v1.StandardRes
+}
diff --git a/core/internal/controller/settings/settings_v1_get_system_config.go b/core/internal/controller/settings/settings_v1_get_system_config.go
index 4751014a..df8ff1d8 100644
--- a/core/internal/controller/settings/settings_v1_get_system_config.go
+++ b/core/internal/controller/settings/settings_v1_get_system_config.go
@@ -5,8 +5,11 @@ import (
"billionmail-core/internal/service/domains"
"billionmail-core/internal/service/public"
"context"
+ "encoding/json"
+
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gfile"
)
func (c *ControllerV1) GetSystemConfig(ctx context.Context, req *v1.GetSystemConfigReq) (res *v1.GetSystemConfigRes, err error) {
@@ -64,6 +67,18 @@ func (c *ControllerV1) GetSystemConfig(ctx context.Context, req *v1.GetSystemCon
config.APIDocSwagger.APIDocURL = BaseURL + "/api.json"
config.APIDocSwagger.SwaggerURL = BaseURL + "/swagger"
+ // Load blacklist configuration
+ blacklistConfig, err := loadBlacklistConfig(ctx)
+ if err == nil {
+ config.BlacklistConfig = *blacklistConfig
+ } else {
+ config.BlacklistConfig = v1.BlacklistConfig{
+ AutoScanEnabled: true,
+ AlertEnabled: false,
+ AlertSettings: &v1.BlacklistAlertSettings{},
+ }
+ }
+
res.Data = config
res.SetSuccess(public.LangCtx(ctx, "Successfully retrieved system configuration"))
@@ -71,7 +86,6 @@ func (c *ControllerV1) GetSystemConfig(ctx context.Context, req *v1.GetSystemCon
}
func GetIPWhitelist() ([]g.Map, error) {
-
result, err := g.DB().Model("bm_console_ip_whitelist").
Fields("id, ip").
All()
@@ -94,3 +108,50 @@ func GetIPWhitelist() ([]g.Map, error) {
return whitelist, nil
}
+
+func loadBlacklistConfig(ctx context.Context) (*v1.BlacklistConfig, error) {
+ config := &v1.BlacklistConfig{
+ AutoScanEnabled: true,
+ AlertEnabled: false,
+ AlertSettings: &v1.BlacklistAlertSettings{},
+ }
+
+ var autoScanEnabled bool
+ err := public.OptionsMgrInstance.GetOption(ctx, "blacklist_auto_scan_enabled", &autoScanEnabled)
+ if err == nil {
+ config.AutoScanEnabled = autoScanEnabled
+ }
+
+ var alertEnabled bool
+ err = public.OptionsMgrInstance.GetOption(ctx, "blacklist_alert_enabled", &alertEnabled)
+ if err == nil {
+ config.AlertEnabled = alertEnabled
+ }
+
+ alertSettings, err := loadBlacklistAlertSettings()
+ if err == nil && alertSettings != nil {
+ config.AlertSettings = alertSettings
+ }
+
+ return config, nil
+}
+
+func loadBlacklistAlertSettings() (*v1.BlacklistAlertSettings, error) {
+ alertSettingsFile := public.AbsPath("../core/data/blacklist_alert_settings.json")
+ if !gfile.Exists(alertSettingsFile) {
+ return nil, nil
+ }
+
+ content := gfile.GetContents(alertSettingsFile)
+ if content == "" {
+ return nil, nil
+ }
+
+ var settings v1.BlacklistAlertSettings
+ err := json.Unmarshal([]byte(content), &settings)
+ if err != nil {
+ return nil, gerror.Wrap(err, "Failed to parse alert settings")
+ }
+
+ return &settings, nil
+}
diff --git a/core/internal/controller/settings/settings_v1_set_blacklist_alert.go b/core/internal/controller/settings/settings_v1_set_blacklist_alert.go
new file mode 100644
index 00000000..05a50d4a
--- /dev/null
+++ b/core/internal/controller/settings/settings_v1_set_blacklist_alert.go
@@ -0,0 +1,23 @@
+package settings
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/settings/v1"
+)
+
+func (c *ControllerV1) SetBlacklistAlert(ctx context.Context, req *v1.SetBlacklistAlertReq) (res *v1.SetBlacklistAlertRes, err error) {
+ res = &v1.SetBlacklistAlertRes{}
+
+ err = public.OptionsMgrInstance.SetOption(ctx, "blacklist_alert_enabled", req.Enabled)
+ if err != nil {
+ res.SetError(gerror.Newf(public.LangCtx(ctx, "Failed to set alert switch: %v", err)))
+ return res, nil
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "Alert switch updated successfully"))
+ return res, nil
+}
diff --git a/core/internal/controller/settings/settings_v1_set_blacklist_alert_settings.go b/core/internal/controller/settings/settings_v1_set_blacklist_alert_settings.go
new file mode 100644
index 00000000..b644fb62
--- /dev/null
+++ b/core/internal/controller/settings/settings_v1_set_blacklist_alert_settings.go
@@ -0,0 +1,196 @@
+package settings
+
+import (
+ "billionmail-core/api/settings/v1"
+ "billionmail-core/internal/service/mail_service"
+ "billionmail-core/internal/service/public"
+ "billionmail-core/internal/service/relay"
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gfile"
+)
+
+func (c *ControllerV1) SetBlacklistAlertSettings(ctx context.Context, req *v1.SetBlacklistAlertSettingsReq) (res *v1.SetBlacklistAlertSettingsRes, err error) {
+ res = &v1.SetBlacklistAlertSettingsRes{}
+
+ if err := validateAlertSettings(&req.Settings); err != nil {
+ res.SetError(gerror.Newf(public.LangCtx(ctx, "Parameter validation failed: {}", err.Error())))
+ return res, nil
+ }
+
+ //g.Log().Info(ctx, "Testing SMTP connection...")
+ if err := testSMTPConnectionWithRelay(ctx, &req.Settings); err != nil {
+ res.SetError(gerror.Newf(public.LangCtx(ctx, "SMTP connection test failed: {}", err.Error())))
+ return res, nil
+ }
+
+ //g.Log().Info(ctx, "Sending test email...")
+ if err := sendTestEmailWithMailService(ctx, &req.Settings); err != nil {
+ res.SetError(gerror.Newf(public.LangCtx(ctx, "Failed to send test email: {}", err.Error())))
+ return res, nil
+ }
+
+ alertSettingsFile := public.AbsPath("../core/data/blacklist_alert_settings.json")
+
+ jsonData, err := json.MarshalIndent(req.Settings, "", " ")
+ if err != nil {
+ res.SetError(gerror.Newf(public.LangCtx(ctx, "Failed to encode alert settings: {}", err.Error())))
+ return res, nil
+ }
+
+ err = gfile.PutContents(alertSettingsFile, string(jsonData))
+ if err != nil {
+ res.SetError(gerror.Newf(public.LangCtx(ctx, "Failed to save alert settings: {}", err.Error())))
+ return res, nil
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "Alert settings saved successfully and test email sent"))
+ return res, nil
+}
+
+func validateAlertSettings(settings *v1.BlacklistAlertSettings) error {
+ if settings.SenderEmail == "" {
+ return fmt.Errorf("sender email is required")
+ }
+
+ if !strings.Contains(settings.SenderEmail, "@") {
+ return fmt.Errorf("invalid sender email format")
+ }
+
+ if settings.SMTPServer == "" {
+ return fmt.Errorf("SMTP server is required")
+ }
+
+ if settings.SMTPPort < 1 || settings.SMTPPort > 65535 {
+ return fmt.Errorf("SMTP port must be between 1 and 65535")
+ }
+
+ if settings.SMTPPassword == "" {
+ return fmt.Errorf("SMTP password is required")
+ }
+
+ if len(settings.RecipientList) == 0 {
+ return fmt.Errorf("at least one recipient is required")
+ }
+
+ for _, recipient := range settings.RecipientList {
+ if !strings.Contains(recipient, "@") {
+ return fmt.Errorf("invalid recipient email format: %s", recipient)
+ }
+ }
+
+ return nil
+}
+
+func testSMTPConnectionWithRelay(ctx context.Context, settings *v1.BlacklistAlertSettings) error {
+ //g.Log().Infof(ctx, "Testing SMTP connection to %s:%d", settings.SMTPServer, settings.SMTPPort)
+
+ result := relay.TestSmtpConnection(
+ settings.SMTPServer,
+ fmt.Sprintf("%d", settings.SMTPPort),
+ settings.SenderEmail,
+ settings.SMTPPassword,
+ )
+
+ if !result.Success {
+ return fmt.Errorf("%s", result.Message)
+ }
+
+ //g.Log().Infof(ctx, "SMTP connection test successful: %s", result.Message)
+ return nil
+}
+
+func sendTestEmailWithMailService(ctx context.Context, settings *v1.BlacklistAlertSettings) error {
+ //g.Log().Infof(ctx, "Sending test email to %v", settings.RecipientList)
+
+ subject := "Blacklist Alert Test - BillionMail"
+ body := buildTestEmailHTML(settings)
+
+ sender := mail_service.NewEmailSender()
+ sender.Host = settings.SMTPServer
+ sender.Port = fmt.Sprintf("%d", settings.SMTPPort)
+ sender.Email = settings.SenderEmail
+ sender.UserName = settings.SenderEmail
+ sender.Password = settings.SMTPPassword
+
+ err := sender.Connect()
+ if err != nil {
+ return fmt.Errorf("failed to connect to SMTP server: %v", err)
+ }
+ defer sender.Close()
+
+ var failedRecipients []string
+ for _, recipient := range settings.RecipientList {
+
+ message := mail_service.NewMessage(subject, body)
+ message.SetRealName(settings.Name)
+ messageId := sender.GenerateMessageID()
+ message.SetMessageID(messageId)
+
+ err = sender.Send(message, []string{recipient})
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to send test email to %s: %v", recipient, err)
+ failedRecipients = append(failedRecipients, recipient)
+ } else {
+ g.Log().Infof(ctx, "Test email sent successfully to %s", recipient)
+ }
+ }
+
+ if len(failedRecipients) > 0 {
+ return fmt.Errorf("failed to send test email to %d recipient(s): %v", len(failedRecipients), failedRecipients)
+ }
+
+ g.Log().Infof(ctx, "Test email sent successfully to all %d recipients", len(settings.RecipientList))
+ return nil
+}
+
+func buildTestEmailHTML(settings *v1.BlacklistAlertSettings) string {
+ return fmt.Sprintf(`
+<html>
+<head>
+ <style>
+ body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
+ .container { max-width: 600px; margin: 0 auto; padding: 20px; }
+ .header { background: #4CAF50; color: white; padding: 10px 20px; border-radius: 5px; }
+ .content { padding: 20px; background: #f9f9f9; border-radius: 5px; margin-top: 20px; }
+ .footer { margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd; font-size: 12px; color: #777; }
+ .success { color: #4CAF50; font-weight: bold; }
+ ul { list-style: none; padding-left: 0; }
+ ul li { padding: 5px 0; }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <div class="header">
+ <h2>✅ Blacklist Alert Configuration Test</h2>
+ </div>
+ <div class="content">
+ <p>Hello,</p>
+ <p>This is a test email from BillionMail blacklist monitoring system.</p>
+ <p class="success">✓ Your alert settings have been configured successfully!</p>
+ <p><strong>Configuration Details:</strong></p>
+ <ul>
+ <li><strong>Configuration Name:</strong> %s</li>
+ <li><strong>Sender Email:</strong> %s</li>
+ <li><strong>SMTP Server:</strong> %s:%d</li>
+ <li><strong>Recipients:</strong> %d email(s)</li>
+ </ul>
+ <p>When a domain is detected on a blacklist, you will receive an alert email similar to this one.</p>
+ <p><strong>Test Time:</strong> %s</p>
+ </div>
+ <div class="footer">
+ <p>This is an automated message from BillionMail Blacklist Monitoring System.</p>
+ <p>If you did not configure this alert, please contact your system administrator.</p>
+ </div>
+ </div>
+</body>
+</html>
+`, settings.Name, settings.SenderEmail, settings.SMTPServer, settings.SMTPPort,
+ len(settings.RecipientList), time.Now().Format("2006-01-02 15:04:05"))
+}
diff --git a/core/internal/controller/settings/settings_v1_set_blacklist_auto_scan.go b/core/internal/controller/settings/settings_v1_set_blacklist_auto_scan.go
new file mode 100644
index 00000000..ecb49fcc
--- /dev/null
+++ b/core/internal/controller/settings/settings_v1_set_blacklist_auto_scan.go
@@ -0,0 +1,23 @@
+package settings
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/settings/v1"
+)
+
+func (c *ControllerV1) SetBlacklistAutoScan(ctx context.Context, req *v1.SetBlacklistAutoScanReq) (res *v1.SetBlacklistAutoScanRes, err error) {
+ res = &v1.SetBlacklistAutoScanRes{}
+
+ err = public.OptionsMgrInstance.SetOption(ctx, "blacklist_auto_scan_enabled", req.Enabled)
+ if err != nil {
+ res.SetError(gerror.Newf(public.LangCtx(ctx, "Failed to set auto scan switch: %v", err)))
+ return res, nil
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "Auto scan switch updated successfully"))
+ return res, nil
+}
diff --git a/core/internal/service/domains/blacklist.go b/core/internal/service/domains/blacklist.go
index e4a51be8..6883dbe5 100644
--- a/core/internal/service/domains/blacklist.go
+++ b/core/internal/service/domains/blacklist.go
@@ -2,6 +2,7 @@ package domains
import (
"billionmail-core/internal/model"
+ "billionmail-core/internal/service/mail_service"
"billionmail-core/internal/service/public"
"context"
"encoding/json"
@@ -9,6 +10,7 @@ import (
"strings"
"time"
+ "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gtime"
"github.com/miekg/dns"
@@ -185,6 +187,61 @@ var (
DOMAIN_SCAN_LOG_PATH = public.AbsPath("../core/data")
)
+// The blacklist for detecting scheduled task invocations
+func CheckDomainsBlacklist(ctx context.Context) {
+
+ var autoScanEnabled bool
+ err := public.OptionsMgrInstance.GetOption(ctx, "blacklist_auto_scan_enabled", &autoScanEnabled)
+ if err != nil {
+ autoScanEnabled = true
+ }
+ if !autoScanEnabled {
+ return
+ }
+
+ domains, err := All(ctx)
+ if err != nil {
+ return
+ }
+
+ if len(domains) == 0 {
+ return
+ }
+
+ var waitDuration time.Duration
+ if len(domains) <= 8 {
+ waitDuration = 3 * time.Hour
+ } else {
+ hoursPerDomain := 24.0 / float64(len(domains))
+ waitDuration = time.Duration(hoursPerDomain * float64(time.Hour))
+ }
+
+ for i, domain := range domains {
+
+ if domain.ARecord == "" {
+ continue
+ }
+
+ ip, err := ResolveA(domain.ARecord, nil)
+ if err != nil {
+ //g.Log().Errorf(ctx, "Failed to parse the A record of domain name %s: %v. Skipping the check.", domain.ARecord, err)
+ continue
+ }
+
+ _, err = IsDomainBlacklisted(ctx, ip, domain.ARecord, nil)
+ if err != nil {
+ continue
+ }
+
+ if i < len(domains)-1 {
+ //g.Log().Infof(ctx, "Wait for %.0f minutes and then check the next domain name...", waitDuration.Minutes())
+ time.Sleep(waitDuration)
+ }
+ }
+
+ //g.Log().Infof(ctx, "The blacklist check task has been completed. A total of %d domain names were checked.", len(domains))
+}
+
// IsDomainBlacklisted
func IsDomainBlacklisted(ctx context.Context, ip, domain string, dns_servers []string) (*model.BlacklistCheckResult, error) {
result := &model.BlacklistCheckResult{
@@ -267,24 +324,11 @@ func IsDomainBlacklisted(ctx context.Context, ip, domain string, dns_servers []s
addBlacklist(domain, result)
- //// 有黑名单,检查告警并推送
- //if result.Blacklisted > 0 {
- // args := &public.SendMailDataArgs{
- // Keyword: "mail_domain_black",
- // Domain: domain,
- // }
- // var blacklists []string
- // for _, b := range result.BlackList {
- // blacklists = append(blacklists, b.Blacklist)
- // }
- // body := []string{
- // fmt.Sprintf(">Send content: Your IP [%s] is on the email blacklist.", ip),
- // fmt.Sprintf(">Results for %s.", domain),
- // fmt.Sprintf(">Blacklisted: %v.", blacklists),
- // }
- // args.Body = body
- // public.SendMailData(ctx, args)
- //}
+ // Check the alerts and push them
+ if result.Blacklisted > 0 {
+
+ go sendBlacklistAlert(ctx, ip, domain, result)
+ }
return result, nil
}
@@ -369,3 +413,216 @@ func GetBlacklistLogPath(domain string) string {
logPath := fmt.Sprintf("%s/%s_blcheck.txt", DOMAIN_SCAN_LOG_PATH, domain)
return logPath
}
+
+func sendBlacklistAlert(ctx context.Context, ip, domain string, result *model.BlacklistCheckResult) {
+
+ var alertEnabled bool
+ err := public.OptionsMgrInstance.GetOption(ctx, "blacklist_alert_enabled", &alertEnabled)
+ if err != nil || !alertEnabled {
+ //g.Log().Infof(ctx, "Blacklist alert is disabled, skipping alert for domain: %s", domain)
+ return
+ }
+
+ alertSettings, err := loadBlacklistAlertSettingsForAlert()
+ if err != nil || alertSettings == nil {
+ g.Log().Errorf(ctx, "Failed to load alert settings, skipping alert for domain: %s, error: %v", domain, err)
+ return
+ }
+
+ if alertSettings.SenderEmail == "" || alertSettings.SMTPServer == "" || len(alertSettings.RecipientList) == 0 {
+ g.Log().Errorf(ctx, "Alert settings incomplete, skipping alert for domain: %s", domain)
+ return
+ }
+
+ subject := fmt.Sprintf("⚠️ Blacklist Alert - %s", domain)
+ body := buildBlacklistAlertEmailHTML(ip, domain, result)
+
+ err = sendAlertEmail(ctx, alertSettings, subject, body)
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to send blacklist alert for domain: %s, error: %v", domain, err)
+ return
+ }
+
+ g.Log().Infof(ctx, "✅ Blacklist alert sent successfully for domain: %s to %d recipients", domain, len(alertSettings.RecipientList))
+}
+
+type BlacklistAlertSettings struct {
+ Name string `json:"name"`
+ SenderEmail string `json:"sender_email"`
+ SMTPPassword string `json:"smtp_password"`
+ SMTPServer string `json:"smtp_server"`
+ SMTPPort int `json:"smtp_port"`
+ RecipientList []string `json:"recipient_list"`
+}
+
+func loadBlacklistAlertSettingsForAlert() (*BlacklistAlertSettings, error) {
+ alertSettingsFile := public.AbsPath("../core/data/blacklist_alert_settings.json")
+
+ if !gfile.Exists(alertSettingsFile) {
+ return nil, fmt.Errorf("alert settings file not found")
+ }
+
+ content := gfile.GetContents(alertSettingsFile)
+ if content == "" {
+ return nil, fmt.Errorf("alert settings file is empty")
+ }
+
+ var settings BlacklistAlertSettings
+ err := json.Unmarshal([]byte(content), &settings)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse alert settings: %v", err)
+ }
+
+ return &settings, nil
+}
+
+func sendAlertEmail(ctx context.Context, settings *BlacklistAlertSettings, subject, body string) error {
+
+ sender := mail_service.NewEmailSender()
+ sender.Host = settings.SMTPServer
+ sender.Port = fmt.Sprintf("%d", settings.SMTPPort)
+ sender.Email = settings.SenderEmail
+ sender.UserName = settings.SenderEmail
+ sender.Password = settings.SMTPPassword
+
+ err := sender.Connect()
+ if err != nil {
+ return fmt.Errorf("failed to connect to SMTP server: %v", err)
+ }
+ defer sender.Close()
+
+ var failedRecipients []string
+ for _, recipient := range settings.RecipientList {
+
+ message := mail_service.NewMessage(subject, body)
+ message.SetRealName(settings.Name)
+ messageId := sender.GenerateMessageID()
+ message.SetMessageID(messageId)
+
+ err = sender.Send(message, []string{recipient})
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to send alert email to %s: %v", recipient, err)
+ failedRecipients = append(failedRecipients, recipient)
+ } else {
+ g.Log().Infof(ctx, "Alert email sent successfully to %s", recipient)
+ }
+ }
+
+ if len(failedRecipients) > 0 {
+ return fmt.Errorf("failed to send alert email to %d recipient(s): %v", len(failedRecipients), failedRecipients)
+ }
+
+ return nil
+}
+
+func buildBlacklistAlertEmailHTML(ip, domain string, result *model.BlacklistCheckResult) string {
+
+ var blacklistItems string
+ for i, bl := range result.BlackList {
+ blacklistItems += fmt.Sprintf(" <li><strong>%d. %s</strong> (Response: %s)</li>\n",
+ i+1, bl.Blacklist, bl.Response)
+ }
+
+ return fmt.Sprintf(`
+<html>
+<head>
+ <style>
+ body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
+ .container { max-width: 600px; margin: 0 auto; padding: 20px; }
+ .header { background: #f44336; color: white; padding: 15px 20px; border-radius: 5px; }
+ .content { padding: 20px; background: #fff3cd; border-radius: 5px; margin-top: 20px; border: 2px solid #f44336; }
+ .alert-box { background: #ffebee; padding: 15px; border-left: 4px solid #f44336; margin: 15px 0; }
+ .info-table { width: 100%%; border-collapse: collapse; margin: 15px 0; }
+ .info-table td { padding: 8px; border-bottom: 1px solid #ddd; }
+ .info-table td:first-child { font-weight: bold; width: 150px; }
+ .blacklist-list { background: #fff; padding: 15px; border-radius: 5px; margin: 15px 0; }
+ .blacklist-list ul { list-style: none; padding-left: 0; }
+ .blacklist-list li { padding: 5px 0; color: #d32f2f; }
+ .footer { margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd; font-size: 12px; color: #777; }
+ .warning { color: #f44336; font-weight: bold; font-size: 18px; }
+ .action-needed { background: #f44336; color: white; padding: 10px; border-radius: 5px; margin: 15px 0; text-align: center; }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <div class="header">
+ <h2>⚠️ Blacklist Alert - Action Required</h2>
+ </div>
+ <div class="content">
+ <div class="alert-box">
+ <p class="warning">⚠️ Your domain has been detected on email blacklists!</p>
+ <p>Immediate action is required to prevent email delivery issues.</p>
+ </div>
+
+ <h3>Domain Information</h3>
+ <table class="info-table">
+ <tr>
+ <td>Domain:</td>
+ <td><strong>%s</strong></td>
+ </tr>
+ <tr>
+ <td>IP Address:</td>
+ <td><strong>%s</strong></td>
+ </tr>
+ <tr>
+ <td>Detection Time:</td>
+ <td>%s</td>
+ </tr>
+ </table>
+
+ <h3>Check Results</h3>
+ <table class="info-table">
+ <tr>
+ <td>Total Tested:</td>
+ <td>%d blacklists</td>
+ </tr>
+ <tr>
+ <td>Passed:</td>
+ <td style="color: green;">%d ✓</td>
+ </tr>
+ <tr>
+ <td>Invalid:</td>
+ <td>%d</td>
+ </tr>
+ <tr>
+ <td>Blacklisted:</td>
+ <td style="color: red; font-weight: bold;">%d ✗</td>
+ </tr>
+ </table>
+
+ <div class="blacklist-list">
+ <h3>Blacklisted On:</h3>
+ <ul>
+%s
+ </ul>
+ </div>
+
+ <div class="action-needed">
+ <strong>Action Needed:</strong> Please investigate and resolve these blacklist issues immediately.
+ </div>
+
+ <h3>Recommended Actions:</h3>
+ <ol>
+ <li>Check recent email sending activities</li>
+ <li>Review server security and spam policies</li>
+ <li>Submit delisting requests to affected blacklists</li>
+ <li>Monitor email delivery rates</li>
+ <li>Contact support if assistance is needed</li>
+ </ol>
+
+ <p><strong>View detailed log:</strong> <code>%s</code></p>
+ </div>
+ <div class="footer">
+ <p>This is an automated alert from BillionMail Blacklist Monitoring System.</p>
+ <p>Alert Time: %s</p>
+ <p>If you have resolved this issue, you can ignore this alert.</p>
+ </div>
+ </div>
+</body>
+</html>
+`, domain, ip, time.Unix(result.Time, 0).Format("2006-01-02 15:04:05"),
+ result.Tested, result.Passed, result.Invalid, result.Blacklisted,
+ blacklistItems,
+ GetBlacklistLogPath(domain),
+ time.Now().Format("2006-01-02 15:04:05"))
+}
diff --git a/core/internal/service/domains/domains.go b/core/internal/service/domains/domains.go
index e9657dea..bc6538af 100644
--- a/core/internal/service/domains/domains.go
+++ b/core/internal/service/domains/domains.go
@@ -302,6 +302,7 @@ func Get(ctx context.Context, keyword string, page, pageSize int) ([]v1.Domain,
}(i, domain)
+ // Blacklist check
wg.Add(1)
go func(i int, domain v1.Domain) {
defer wg.Done()
diff --git a/core/internal/service/timers/timers.go b/core/internal/service/timers/timers.go
index d9730c09..072b1a2c 100644
--- a/core/internal/service/timers/timers.go
+++ b/core/internal/service/timers/timers.go
@@ -183,6 +183,11 @@ func Start(ctx context.Context) (err error) {
relay.EnsurePostfixConfExists(ctx)
})
+ // Check the domain name blacklist
+ gtimer.Add(30*time.Minute, func() {
+ domains.CheckDomainsBlacklist(ctx)
+ })
+
g.Log().Debug(ctx, "All timers started successfully")
return nil
}