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
Fix path issues The timing task gets the smtp connection status
lotk2cc93dc0a5bc
diff --git a/core/api/mail_services/v1/common.go b/core/api/mail_services/v1/common.goindex 7f1379ba..775d807f 100644--- a/core/api/mail_services/v1/common.go+++ b/core/api/mail_services/v1/common.go@@ -9,7 +9,7 @@ import (type ServiceType stringvar (- BaseConfigDir = public.AbsPath("./conf")+ BaseConfigDir = public.AbsPath("../conf")ServiceType_Postfix = BaseConfigDir + "/postfix/main.cf"ServiceType_Dovecot = BaseConfigDir + "/dovecot/dovecot.conf"ServiceType_Rspamd = BaseConfigDir + "/rspamd/rspamd.conf"diff --git a/core/internal/controller/mail_services/mail_services.go b/core/internal/controller/mail_services/mail_services.goindex 0e7b6bd6..412a5558 100644--- a/core/internal/controller/mail_services/mail_services.go+++ b/core/internal/controller/mail_services/mail_services.go@@ -41,7 +41,7 @@ func processForwardUsers(forwardUsers string) []string {func SyncBccToPostfix(ctx context.Context) error {// configPath- postfixConfigDir := public.AbsPath("./conf/postfix/conf")+ postfixConfigDir := public.AbsPath("../conf/postfix/conf")senderBccFile := path.Join(postfixConfigDir, "sender_bcc")recipientBccFile := path.Join(postfixConfigDir, "recipient_bcc")mainCfFile := path.Join(postfixConfigDir, "main.cf")diff --git a/core/internal/controller/relay/relay.go b/core/internal/controller/relay/relay.goindex 2cd83dba..afa4b34d 100644--- a/core/internal/controller/relay/relay.go+++ b/core/internal/controller/relay/relay.go@@ -26,7 +26,7 @@ import ()var (- postfixConfigDir = public.AbsPath("./conf/postfix")+ postfixConfigDir = public.AbsPath("../conf/postfix")senderRelayFile = "/conf/sender_relay"saslPasswdFile = "/conf/sasl_passwd"@@ -229,6 +229,7 @@ func GenerateSPFRecord(ip string, host string, domain string) string {// SyncRelayConfigsToPostfixfunc SyncRelayConfigsToPostfix(ctx context.Context) error {// 首先检查配置目录是否存在+if !gfile.Exists(postfixConfigDir) {return gerror.New(public.LangCtx(ctx, "Postfix configuration directory does not exist: {}", postfixConfigDir))}diff --git a/core/internal/controller/relay/relay_v1_list_relay_configs.go b/core/internal/controller/relay/relay_v1_list_relay_configs.goindex 358f1534..d186b4a9 100644--- a/core/internal/controller/relay/relay_v1_list_relay_configs.go+++ b/core/internal/controller/relay/relay_v1_list_relay_configs.go@@ -52,7 +52,7 @@ func (c *ControllerV1) ListRelayConfigs(ctx context.Context, req *v1.ListRelayCobmRelay := toPostfixRelayResponse(ctx, item)- smtpStatus := relay_service.CheckSmtpConnection(ctx, item.RelayHost, item.RelayPort, item.AuthUser, bmRelay.AuthPassword)+ smtpStatus := relay_service.CheckSmtpConnection(ctx, item.RelayHost, item.RelayPort, item.AuthUser, "")relayWithSPF := &v1.BmRelayWithSPF{BmRelay: bmRelay,diff --git a/core/internal/service/relay/smtp_connection_helper.go b/core/internal/service/relay/smtp_connection_helper.goindex 75f15a35..f1f30d1a 100644--- a/core/internal/service/relay/smtp_connection_helper.go+++ b/core/internal/service/relay/smtp_connection_helper.go@@ -2,14 +2,20 @@ package relayimport ("billionmail-core/api/relay/v1"+ "billionmail-core/internal/model/entity""billionmail-core/internal/service/public""context""crypto/tls"+ "encoding/hex""fmt"+ "github.com/gogf/gf/v2/crypto/gaes"+ "github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g""github.com/gogf/gf/v2/os/gcache""net""net/smtp""strings"+ "sync""time")@@ -197,12 +203,75 @@ func TestSmtpConnection(host, port, user, password string) *SmtpConnectionTestRereturn result}-// CheckSmtpConnection Checks the SMTP connection status with caching support.+// UpdateRelayStatus Periodically updates the SMTP connection status of all relay configurations.+func UpdateRelayStatus(ctx context.Context) {+ g.Log().Debug(ctx, "Starting periodic update of SMTP connection statuses...")++ // Query all active relay configurations.+ var relayConfigs []*entity.BmRelay+ err := g.DB().Model("bm_relay").Where("active", 1).Scan(&relayConfigs)+ if err != nil {+ //g.Log().Error(ctx, "Failed to query relay configurations:", err)+ return+ }++ if len(relayConfigs) == 0 {+ //g.Log().Debug(ctx, "No active relay configurations found, skipping SMTP status update.")+ return+ }++ //g.Log().Debugf(ctx, "Found %d active relay configurations, starting to check SMTP connection statuses.", len(relayConfigs))++ // Use WaitGroup to wait for all checks to complete.+ var wg sync.WaitGroup+ // Limit concurrency to avoid establishing too many connections simultaneously.+ semaphore := make(chan struct{}, 5)++ for _, config := range relayConfigs {+ wg.Add(1)++ // Use goroutines for concurrent checks.+ go func(cfg *entity.BmRelay) {+ defer wg.Done()++ // Acquire semaphore to limit concurrency.+ semaphore <- struct{}{}+ defer func() { <-semaphore }()++ // Decrypt password.+ password, err := DecryptPassword1(ctx, cfg.AuthPassword)+ if err != nil {+ g.Log().Warningf(ctx, "Failed to decrypt password for relay configuration ID=%d: %v", cfg.Id, err)+ return+ }++ // Perform SMTP connection check.+ status := checkSmtpConnectionImpl(cfg.RelayHost, cfg.RelayPort, cfg.AuthUser, password)++ // Generate cache key.+ cacheKey := fmt.Sprintf(smtpStatusCacheKeyFormat, cfg.RelayHost, cfg.RelayPort, cfg.AuthUser)++ // Store result in cache.+ err = smtpStatusCache.Set(ctx, cacheKey, status, smtpStatusCacheExpire)+ if err != nil {+ g.Log().Warningf(ctx, "Failed to cache SMTP status for relay configuration ID=%d: %v", cfg.Id, err)+ }++ g.Log().Debugf(ctx, "Updated SMTP status for relay configuration (ID=%d, Host=%s:%s): %v - %s",+ cfg.Id, cfg.RelayHost, cfg.RelayPort, status.Status, status.Msg)+ }(config)+ }++ // Wait for all checks to complete.+ wg.Wait()+ g.Log().Debug(ctx, "All SMTP connection statuses have been updated.")+}++// CheckSmtpConnectionfunc CheckSmtpConnection(ctx context.Context, host, port, user, password string) *SmtpConnectionStatus {- // Generate cache key+cacheKey := fmt.Sprintf(smtpStatusCacheKeyFormat, host, port, user)- // Try to retrieve status from cacheif v, err := smtpStatusCache.Get(ctx, cacheKey); err == nil && v != nil {var status SmtpConnectionStatusif err := v.Scan(&status); err == nil {@@ -210,14 +279,21 @@ func CheckSmtpConnection(ctx context.Context, host, port, user, password string)}}- // Cache miss, perform actual check+ return &SmtpConnectionStatus{+ Status: false,+ Msg: "Status unknown (under check)",+ LastTime: time.Now().Unix(),+ }+}++// ForceCheckSmtpConnection+func ForceCheckSmtpConnection(ctx context.Context, host, port, user, password string) *SmtpConnectionStatus {+status := checkSmtpConnectionImpl(host, port, user, password)- // Store result in cache- err := smtpStatusCache.Set(ctx, cacheKey, status, smtpStatusCacheExpire)- if err != nil {- return nil- }+ cacheKey := fmt.Sprintf(smtpStatusCacheKeyFormat, host, port, user)++ smtpStatusCache.Set(ctx, cacheKey, status, smtpStatusCacheExpire)return status}@@ -308,3 +384,61 @@ func ForceRefreshSmtpStatus(ctx context.Context, relayConfig *v1.BmRelay) *SmtpCfunc ClearSmtpStatusCache(ctx context.Context) error {return smtpStatusCache.Clear(ctx)}++func DecryptPassword1(ctx context.Context, encryptedHex string) (string, error) {++ password, err := DecryptPassword(ctx, encryptedHex)+ if password == "" {+ password = "********"+ }+ return password, err+}++func DecryptPassword(ctx context.Context, encryptedHex string) (string, error) {+ if encryptedHex == "" {+ return "", nil+ }++ encryptedBytes, err := hex.DecodeString(encryptedHex)+ if err != nil {+ //g.Log().Errorf(ctx, "Decryption failed, invalid hex format: %v", err)+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Password format is incorrect"))+ }++ relayEncryptionKey, err := GetRelayEncryptionKey()+ if err != nil {+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to retrieve encryption key"))+ }++ keyBytes, err := hex.DecodeString(relayEncryptionKey)+ if err != nil {+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to parse encryption key"))+ }++ if len(keyBytes) < 16 {+ return "", gerror.New(public.LangCtx(ctx, "Encryption key length is insufficient"))+ }+ keyBytes = keyBytes[:16]++ decrypted, err := gaes.Decrypt(encryptedBytes, keyBytes)+ if err != nil {+ //g.Log().Errorf(ctx, "Password decryption failed: %v", err)+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Password decryption failed"))+ }++ return string(decrypted), nil+}++func GetRelayEncryptionKey() (string, error) {++ val, _ := g.DB().Model("bm_options").+ Where("name", "relay_encryption_key").+ Value("value")++ if val != nil && val.String() != "" {+ return val.String(), nil+ } else {+ return "", gerror.New("Failed to insert new key and retrieve key again")+ }++}diff --git a/core/internal/service/timers/timers.go b/core/internal/service/timers/timers.goindex 6729b351..86d9bcf6 100644--- a/core/internal/service/timers/timers.go+++ b/core/internal/service/timers/timers.go@@ -4,6 +4,7 @@ import ("billionmail-core/internal/service/batch_mail""billionmail-core/internal/service/domains""billionmail-core/internal/service/maillog_stat"+ "billionmail-core/internal/service/relay""context""github.com/gogf/gf/os/gtimer""github.com/gogf/gf/v2/frame/g"@@ -65,6 +66,15 @@ func Start(ctx context.Context) (err error) {g.Log().Debug(ctx, "Idle task executors cleanup completed")})+ // Test the smtp relay configuration connection status+ gtimer.AddOnce(5*time.Second, func() {+ relay.UpdateRelayStatus(ctx)+ })++ gtimer.Add(5*time.Minute, func() {+ relay.UpdateRelayStatus(ctx)+ })+g.Log().Debug(ctx, "All timers started successfully")return nil}