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
Refactor SMTP configuration handling to support optional authentication, improve validation, and enhance error messaging for no-auth relays
lotk314bac1389f0
diff --git a/core/api/relay/v1/relay.go b/core/api/relay/v1/relay.goindex 721d38b3..c93a3036 100644--- a/core/api/relay/v1/relay.go+++ b/core/api/relay/v1/relay.go@@ -76,8 +76,8 @@ type CreateRelayConfigReq struct {SenderDomains []string `json:"sender_domains" v:"required" dc:"Array of sender domains"`RelayHost string `json:"relay_host" v:"required|max-length:255" dc:"Relay server address"`RelayPort string `json:"relay_port" v:"required|max-length:10" dc:"Relay server port, e.g., 587"`- AuthUser string `json:"auth_user" v:"required|max-length:255" dc:"SMTP authentication username"`- AuthPassword string `json:"auth_password" v:"required|max-length:255" dc:"SMTP authentication password"`+ AuthUser string `json:"auth_user" v:"max-length:255" dc:"SMTP authentication username (optional for no-auth relays)"`+ AuthPassword string `json:"auth_password" v:"max-length:255" dc:"SMTP authentication password (optional for no-auth relays)"`IP string `json:"ip" v:"max-length:255" dc:"IP for reminding users to update SPF record, e.g., +ip4:23.158.104.237"`Host string `json:"host" v:"max-length:255" dc:"Host for reminding users to update SPF record, e.g., include:lootk.cn"`Active int `json:"active" d:"1" v:"in:0,1" dc:"Whether enabled: 1-enabled, 0-disabled (default is 1)"`@@ -118,7 +118,7 @@ type UpdateRelayConfigReq struct {Remark string `json:"remark,omitempty" v:"max-length:255" dc:"Remark, e.g., AWS SES Japan Region"`RelayHost string `json:"relay_host,omitempty" v:"max-length:255" dc:"Relay server address"`RelayPort string `json:"relay_port,omitempty" v:"max-length:10" dc:"Relay server port, e.g., 587"`- AuthUser string `json:"auth_user,omitempty" v:"max-length:255" dc:"SMTP authentication username"`+ AuthUser string `json:"auth_user,omitempty" v:"max-length:255" dc:"SMTP authentication username (optional for no-auth relays)"`AuthPassword string `json:"auth_password,omitempty" v:"max-length:255" dc:"SMTP authentication password (no update if not provided)"`IP string `json:"ip,omitempty" v:"max-length:255" dc:"IP for reminding users to update SPF record, e.g., +ip4:23.158.104.237"`Host string `json:"host,omitempty" v:"max-length:255" dc:"Host for reminding users to update SPF record, e.g., include:lootk.cn"`@@ -171,8 +171,8 @@ type TestSmtpConnectionReq struct {Authorization string `json:"authorization" in:"header" dc:"Authorization" v:"required"`RelayHost string `json:"relay_host" v:"required|max-length:255" dc:"Relay server address"`RelayPort string `json:"relay_port" v:"required|max-length:10" dc:"Relay server port, e.g., 587"`- AuthUser string `json:"auth_user" v:"max-length:255" dc:"SMTP authentication username"`- AuthPassword string `json:"auth_password" v:"max-length:255" dc:"SMTP authentication password"`+ AuthUser string `json:"auth_user" v:"max-length:255" dc:"SMTP authentication username (optional for no-auth relays)"`+ AuthPassword string `json:"auth_password" v:"max-length:255" dc:"SMTP authentication password (optional for no-auth relays)"`}// TestSmtpConnectionRes Test SMTP connection responsediff --git a/core/internal/controller/relay/relay_v1_create_relay_config.go b/core/internal/controller/relay/relay_v1_create_relay_config.goindex a63d5c62..a9cb2088 100644--- a/core/internal/controller/relay/relay_v1_create_relay_config.go+++ b/core/internal/controller/relay/relay_v1_create_relay_config.go@@ -35,19 +35,37 @@ func (c *ControllerV1) CreateRelayConfig(ctx context.Context, req *v1.CreateRela}}- encryptedPass, err := relay.EncryptPassword(ctx, req.AuthPassword)- if err != nil {- res.SetError(err)- return res, nil+ // Handle password encryption only if authentication is required+ var encryptedPass string++ if req.AuthUser != "" || req.AuthPassword != "" {+ // If either username or password is provided, both are required+ if req.AuthUser == "" || req.AuthPassword == "" {+ res.SetError(gerror.New(public.LangCtx(ctx, "Both auth_user and auth_password must be provided when using authentication")))+ return res, nil+ }++ encryptedPass, err = relay.EncryptPassword(ctx, req.AuthPassword)+ if err != nil {+ res.SetError(err)+ return res, nil+ }++ // Set default auth method if not specified for authenticated relays+ if req.AuthMethod == "" {+ req.AuthMethod = "LOGIN"+ }+ } else {+ // No authentication required+ encryptedPass = ""+ if req.AuthMethod == "" {+ req.AuthMethod = "NONE"+ }}now := time.Now()unixTime := int(now.Unix())- if req.AuthMethod == "" {- req.AuthMethod = "NONE"- }-configData := g.Map{"remark": req.Remark,"rtype": req.Rtype,diff --git a/core/internal/controller/relay/relay_v1_update_relay_config.go b/core/internal/controller/relay/relay_v1_update_relay_config.goindex 3bd8c3fb..aae92a48 100644--- a/core/internal/controller/relay/relay_v1_update_relay_config.go+++ b/core/internal/controller/relay/relay_v1_update_relay_config.go@@ -44,18 +44,47 @@ func (c *ControllerV1) UpdateRelayConfig(ctx context.Context, req *v1.UpdateRelaif req.RelayPort != "" {updateData["relay_port"] = req.RelayPort}++ // Handle authentication updates - support clearing auth info+ authUserProvided := false+ authPasswordProvided := false++ // Check if AuthUser is explicitly provided (even if empty)if req.AuthUser != "" {updateData["auth_user"] = req.AuthUser+ authUserProvided = true+ } else {+ // If AuthUser is explicitly set to empty string, clear authentication+ updateData["auth_user"] = ""+ updateData["auth_password"] = ""+ authUserProvided = true}- if req.AuthPassword != "" {+ if req.AuthPassword != "" {encryptedPwd, err := relay.EncryptPassword(ctx, req.AuthPassword)if err != nil {res.SetError(gerror.New(public.LangCtx(ctx, "Failed to encrypt password: {}", err.Error())))return res, nil}updateData["auth_password"] = encryptedPwd+ authPasswordProvided = true+ }++ // Update AuthMethod based on authentication status+ if req.AuthMethod != "" {+ updateData["auth_method"] = req.AuthMethod+ } else if authUserProvided {+ // Auto-set AuthMethod based on whether authentication is being used+ if updateData["auth_user"].(string) == "" {+ updateData["auth_method"] = "NONE"+ } else if !authPasswordProvided {+ // If user is provided but password is not updated, keep existing auth method or default to LOGIN+ if req.AuthMethod == "" {+ updateData["auth_method"] = "LOGIN"+ }+ }}+if req.IP != "" {updateData["ip"] = req.IP}diff --git a/core/internal/service/relay/config_sync.go b/core/internal/service/relay/config_sync.goindex 77c45a3f..ba47ab4a 100644--- a/core/internal/service/relay/config_sync.go+++ b/core/internal/service/relay/config_sync.go@@ -522,7 +522,7 @@ func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelayConfig)blockEnd := endIndex + len(endMarker)if blockEnd < len(masterContent) && (masterContent[blockEnd] == '\n' || masterContent[blockEnd] == '\r') {blockEnd++- // 处理 \r\n+if blockEnd < len(masterContent) && masterContent[blockEnd] == '\n' {blockEnd++}@@ -557,11 +557,17 @@ func generateRelayPwdFiles(ctx context.Context, configs []*entity.BmRelayConfig)var saslPasswdContent strings.Builderif len(configs) == 0 {-saslPasswdContent.WriteString("# No active relay configurations\n")-} else {+ hasAuthConfigs := falsefor _, config := range configs {+ // Only generate SASL entries for configurations that require authentication+ if config.AuthUser == "" {+ g.Log().Debugf(ctx, "Skipping SASL entry for relay ID %d (no authentication required): [%s]:%s",+ config.Id, config.RelayHost, config.RelayPort)+ continue+ }+// Decrypt passworddecryptedPass, err := DecryptPassword(ctx, config.AuthPassword)if err != nil {@@ -571,7 +577,11 @@ func generateRelayPwdFiles(ctx context.Context, configs []*entity.BmRelayConfig)saslPasswdContent.WriteString(fmt.Sprintf("[%s]:%s %s:%s\n",config.RelayHost, config.RelayPort, config.AuthUser, decryptedPass))+ hasAuthConfigs = true+ }+ if !hasAuthConfigs {+ saslPasswdContent.WriteString("# No relay configurations require authentication\n")}}diff --git a/core/internal/service/relay/smtp_connection_helper.go b/core/internal/service/relay/smtp_connection_helper.goindex 9d645941..afa2749d 100644--- a/core/internal/service/relay/smtp_connection_helper.go+++ b/core/internal/service/relay/smtp_connection_helper.go@@ -8,6 +8,7 @@ import ("fmt""github.com/gogf/gf/v2/frame/g""github.com/gogf/gf/v2/os/gcache"+ "strings""sync""time")@@ -55,16 +56,38 @@ func TestSmtpConnection(host, port, user, password string) *SmtpConnectionTestRestartTime := time.Now()+ // Validate basic required parameters+ host = strings.TrimSpace(host)+ port = strings.TrimSpace(port)+ user = strings.TrimSpace(user)+ password = strings.TrimSpace(password)++ if host == "" || port == "" {+ result.Message = public.Lang("SMTP host and port are required.")+ return result+ }++ // Validate authentication parameters - if user is provided, password must also be provided+ if user != "" && password == "" {+ result.Message = public.Lang("Password is required when username is provided.")+ return result+ }+sender := mail_service.NewEmailSender()sender.Host = hostsender.Port = portsender.Email = "[email protected]" // Temporary email for testing- sender.UserName = user- sender.Password = password- if !sender.IsConfigured() {- result.Message = public.Lang("SMTP configuration is incomplete.")- return result+ // Handle authentication based on whether credentials are provided+ isAuthRequired := user != "" && password != ""+ if isAuthRequired {+ sender.UserName = user+ sender.Password = password+ } else {+ // For no-auth relays, ensure UserName and Password are empty+ // This should signal the mail service not to attempt SASL authentication+ sender.UserName = ""+ sender.Password = ""}defer sender.Close()@@ -73,6 +96,37 @@ func TestSmtpConnection(host, port, user, password string) *SmtpConnectionTestReerr := sender.Connect()if err != nil {+ // Check if this is an authentication-related error for a no-auth relay+ if !isAuthRequired {+ authErrorPatterns := []string{+ "authentication not enabled",+ "AUTH not enabled",+ "503 5.5.1",+ "AUTH command not supported",+ }++ errorMsg := strings.ToLower(err.Error())+ isAuthError := false+ for _, pattern := range authErrorPatterns {+ if strings.Contains(errorMsg, strings.ToLower(pattern)) {+ isAuthError = true+ break+ }+ }++ if isAuthError {+ // This is expected for no-auth relays, treat as success+ result.Success = true+ result.Message = "SMTP connection test succeeded (no authentication required)."+ result.AuthStatus = "No authentication (server has authentication disabled)."+ result.ConnectionTime = time.Since(startTime).Milliseconds()+ if result.ConnectionTime < 1000 {+ result.RecommendConfig = true+ }+ return result+ }+ }+result.Message = public.Lang("SMTP connection failed: {}", err.Error())return result}@@ -85,8 +139,15 @@ func TestSmtpConnection(host, port, user, password string) *SmtpConnectionTestReresult.Success = trueresult.Message = "SMTP connection test succeeded."- // Provide configuration recommendations based on connection time and authentication status- if connectionTime < 1000 && result.AuthStatus == "Authentication succeeded." {+ // Set authentication status based on whether credentials were used+ if isAuthRequired {+ result.AuthStatus = "Authentication succeeded."+ } else {+ result.AuthStatus = "No authentication (direct connection)."+ }++ // Provide configuration recommendations based on connection time and setup+ if connectionTime < 1000 {result.RecommendConfig = true}