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
Performance Improvements and Stability Fixes:
Jackd11a0cff4cdc
diff --git a/core/internal/controller/relay/relay_v1_test_smtp_connection.go b/core/internal/controller/relay/relay_v1_test_smtp_connection.goindex 3d098df0..ca6e6635 100644--- a/core/internal/controller/relay/relay_v1_test_smtp_connection.go+++ b/core/internal/controller/relay/relay_v1_test_smtp_connection.go@@ -5,46 +5,9 @@ import ("billionmail-core/internal/service/public""billionmail-core/internal/service/relay""context"- "fmt""github.com/gogf/gf/v2/errors/gerror"- "net/smtp")-// customPlainAuth A custom PLAIN authentication method that allows authentication over unencrypted connections-type customPlainAuth struct {- identity, username, password string- host string-}--func (a *customPlainAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {- //Ignoring connection status and host checks, PLAIN authentication is enforced- resp := []byte{}- resp = append(resp, []byte(a.identity)...)- resp = append(resp, 0)- resp = append(resp, []byte(a.username)...)- resp = append(resp, 0)- resp = append(resp, []byte(a.password)...)-- return "PLAIN", resp, nil-}--func (a *customPlainAuth) Next(fromServer []byte, more bool) ([]byte, error) {- if more {-- return nil, fmt.Errorf("unexpected server challenge")- }- return nil, nil-}--func newCustomPlainAuth(identity, username, password, host string) smtp.Auth {- return &customPlainAuth{- identity: identity,- username: username,- password: password,- host: host,- }-}-// TestSmtpConnectionfunc (c *ControllerV1) TestSmtpConnection(ctx context.Context, req *v1.TestSmtpConnectionReq) (res *v1.TestSmtpConnectionRes, err error) {res = &v1.TestSmtpConnectionRes{}diff --git a/core/internal/service/public/common.go b/core/internal/service/public/common.goindex 4e004194..b6ca638f 100644--- a/core/internal/service/public/common.go+++ b/core/internal/service/public/common.go@@ -723,13 +723,15 @@ func FileAppend(filename string, content string) (err error) {// Get languagefunc GetLanguage() string {- defaultLanguage := "en"- r := GetReq()- if r == nil {- return defaultLanguage- }+ //defaultLanguage := "en"+ //r := GetReq()+ //if r == nil {+ // return defaultLanguage+ //}- return GetLanguageFromCtx(r.Context())+ //return GetLanguageFromCtx(r.Context())++ return GetLanguageFromCtx(context.Background())}// Get language list@@ -780,20 +782,18 @@ func GetLanguageList() []map[string]interface{} {// Get language from contextfunc GetLanguageFromCtx(ctx context.Context) string {r := g.RequestFromCtx(ctx)- if r == nil {- return getDefaultLanguageFromDB("en")- }-- // 1. URL- if lang := r.Get("lang").String(); lang != "" {- cleanLang := strings.ToLower(strings.Split(lang, "-")[0])- r.Session.Set("language", cleanLang)- return cleanLang- }+ if r != nil {+ // 1. URL+ if lang := r.Get("lang").String(); lang != "" {+ cleanLang := strings.ToLower(strings.Split(lang, "-")[0])+ _ = r.Session.Set("language", cleanLang)+ return cleanLang+ }- // 2. Session- if language, err := r.Session.Get("language"); err == nil && !language.IsEmpty() {- return language.String()+ // 2. Session+ if language, err := r.Session.Get("language"); err == nil && !language.IsEmpty() {+ return language.String()+ }}// 3. Cache@@ -807,27 +807,29 @@ func GetLanguageFromCtx(ctx context.Context) string {}// 5. Accept- acceptLang := r.Header.Get("Accept-Language")- if acceptLang != "" {-- browserLang := strings.ToLower(strings.Split(acceptLang, ",")[0])- browserLang = strings.Split(browserLang, "-")[0]-- // check if the language is supported- languages := GetLanguageList()- for _, v := range languages {- if v["name"] == browserLang {- // save to db- _, err := g.DB().Model("bm_options").- Where("name", "CurrentLanguage").- Data(g.Map{"value": browserLang}).- Save()-- if err == nil {- SetCache("language", browserLang, 3600)- return browserLang+ if r != nil {+ acceptLang := r.Header.Get("Accept-Language")+ if acceptLang != "" {++ browserLang := strings.ToLower(strings.Split(acceptLang, ",")[0])+ browserLang = strings.Split(browserLang, "-")[0]++ // check if the language is supported+ languages := GetLanguageList()+ for _, v := range languages {+ if v["name"] == browserLang {+ // save to db+ _, err := g.DB().Model("bm_options").+ Where("name", "CurrentLanguage").+ Data(g.Map{"value": browserLang}).+ Save()++ if err == nil {+ SetCache("language", browserLang, 3600)+ return browserLang+ }+ break}- break}}}diff --git a/core/internal/service/relay/smtp_connection_helper.go b/core/internal/service/relay/smtp_connection_helper.goindex f1f30d1a..cb556e41 100644--- a/core/internal/service/relay/smtp_connection_helper.go+++ b/core/internal/service/relay/smtp_connection_helper.go@@ -1,60 +1,20 @@package relayimport (- "billionmail-core/api/relay/v1""billionmail-core/internal/model/entity"+ "billionmail-core/internal/service/mail_service""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")-// customPlainAuth Custom implementation of PLAIN authentication method, allowing authentication over non-encrypted connections.-type customPlainAuth struct {- identity, username, password string- host string-}--func (a *customPlainAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {- // Ignore connection status and host checks, force PLAIN authentication.- resp := []byte{}- resp = append(resp, []byte(a.identity)...)- resp = append(resp, 0)- resp = append(resp, []byte(a.username)...)- resp = append(resp, 0)- resp = append(resp, []byte(a.password)...)-- return "PLAIN", resp, nil-}--func (a *customPlainAuth) Next(fromServer []byte, more bool) ([]byte, error) {- if more {- // Should not be called.- return nil, fmt.Errorf("unexpected server challenge")- }- return nil, nil-}--// NewCustomPlainAuth Creates a custom authentication method.-func NewCustomPlainAuth(identity, username, password, host string) smtp.Auth {- return &customPlainAuth{- identity: identity,- username: username,- password: password,- host: host,- }-}-// Cache instance for storing SMTP connection states.var smtpStatusCache = gcache.New()@@ -98,93 +58,25 @@ func TestSmtpConnection(host, port, user, password string) *SmtpConnectionTestRestartTime := time.Now()- // Set default values- tlsProtocol := "STARTTLS"- skipTlsVerify := 1-- // Connection timeout setting- timeout := 10 * time.Second+ sender := mail_service.NewEmailSender()+ sender.Host = host+ sender.Port = port+ sender.Email = user+ sender.Password = password- // Attempt to connect to the SMTP server- serverAddr := fmt.Sprintf("%s:%s", host, port)-- // First, try a plain TCP connection- conn, err := net.DialTimeout("tcp", serverAddr, timeout)- if err != nil {- result.Message = fmt.Sprintf("Unable to connect to SMTP server: %v", err)+ if !sender.IsConfigured() {+ result.Message = public.Lang("SMTP configuration is incomplete.")return result}- defer conn.Close()- // Create an SMTP client- client, err := smtp.NewClient(conn, host)- if err != nil {- result.Message = fmt.Sprintf("Failed to create SMTP client: %v", err)- return result- }- defer client.Close()-- // Record server information- result.ServerInfo = fmt.Sprintf("Connected to %s", serverAddr)-- // Automatically determine whether TLS is needed based on the port- isTLS := false- if port == "465" {- // Port 465 typically requires direct SSL/TLS, but we already established a plain connection, so we just record the state.- result.TlsStatus = "Port 465 typically requires direct TLS connection."- } else if port == "587" || strings.ToUpper(tlsProtocol) == "STARTTLS" {- // Port 587 typically uses STARTTLS- tlsConfig := &tls.Config{- ServerName: host,- InsecureSkipVerify: skipTlsVerify == 1,- MinVersion: tls.VersionTLS12,- }-- if err = client.StartTLS(tlsConfig); err != nil {- result.TlsStatus = fmt.Sprintf("STARTTLS failed: %v", err)- } else {- result.TlsStatus = "STARTTLS enabled."- isTLS = true- }- } else {- // Other ports (e.g., 25) default to plaintext- result.TlsStatus = "TLS not enabled (plaintext connection)."- }+ defer sender.Close()- // 发送EHLO命令- //if err = client.Hello(heloName); err != nil {- // result.Message = fmt.Sprintf("EHLO命令失败: %v", err)- // return result- //}+ // Attempt to establish a connection+ err := sender.Connect()- // Check if AUTH is supported- if ok, _ := client.Extension("AUTH"); ok {- result.SupportedAuth = "Server supports authentication."- } else {- result.SupportedAuth = "Server does not support authentication or requires TLS."- }-- // If authentication information is provided, attempt authentication- if user != "" && password != "" {- var auth smtp.Auth-- // Select authentication method based on the port and TLS status- if port == "25" && !isTLS {- // Port 25 with no TLS uses custom authentication method- auth = NewCustomPlainAuth("", user, password, host)- } else {- // Other cases use standard authentication method- auth = smtp.PlainAuth("", user, password, host)- }-- if err = client.Auth(auth); err != nil {- result.AuthStatus = fmt.Sprintf("Authentication failed: %v", err)- result.Message = fmt.Sprintf("SMTP authentication failed: %v", err)- return result- }- result.AuthStatus = "Authentication succeeded."- } else {- result.AuthStatus = "No authentication information provided."+ if err != nil {+ result.Message = public.Lang("SMTP connection failed: {}", err.Error())+ return result}// Calculate connection time@@ -286,18 +178,6 @@ func CheckSmtpConnection(ctx context.Context, host, port, user, password string)}}-// ForceCheckSmtpConnection-func ForceCheckSmtpConnection(ctx context.Context, host, port, user, password string) *SmtpConnectionStatus {-- status := checkSmtpConnectionImpl(host, port, user, password)-- cacheKey := fmt.Sprintf(smtpStatusCacheKeyFormat, host, port, user)-- smtpStatusCache.Set(ctx, cacheKey, status, smtpStatusCacheExpire)-- return status-}-// checkSmtpConnectionImpl Actual implementation of SMTP connection checking.func checkSmtpConnectionImpl(host, port, user, password string) *SmtpConnectionStatus {status := &SmtpConnectionStatus{@@ -306,59 +186,12 @@ func checkSmtpConnectionImpl(host, port, user, password string) *SmtpConnectionSLastTime: time.Now().Unix(),}- // Connection timeout setting (short time for batch checks)- timeout := 5 * time.Second+ ret := TestSmtpConnection(host, port, user, password)- // Attempt TCP connection- serverAddr := fmt.Sprintf("%s:%s", host, port)- conn, err := net.DialTimeout("tcp", serverAddr, timeout)- if err != nil {- status.Msg = public.Lang("Connection failed: {}", err)+ if !ret.Success {+ status.Msg = ret.Messagereturn status}- defer conn.Close()-- // Create SMTP client- client, err := smtp.NewClient(conn, host)- if err != nil {- status.Msg = public.Lang("Failed to create SMTP client: {}", err)- return status- }- defer client.Close()-- // Determine if TLS is needed based on the port- if port == "587" {- // Port 587 typically uses STARTTLS- tlsConfig := &tls.Config{- ServerName: host,- InsecureSkipVerify: true,- MinVersion: tls.VersionTLS12,- }-- if err = client.StartTLS(tlsConfig); err != nil {- status.Msg = public.Lang("STARTTLS failed: {}", err)- return status- }- }-- // If authentication information is provided, attempt authentication- if user != "" && password != "" {- var auth smtp.Auth-- // Select authentication method based on the port- if port == "25" {- // Port 25 uses custom authentication method- auth = NewCustomPlainAuth("", user, password, host)- } else {- // Other cases use standard authentication method- auth = smtp.PlainAuth("", user, password, host)- }-- if err = client.Auth(auth); err != nil {- status.Msg = public.Lang("Authentication failed: {}", err)- return status- }- }// All checks passedstatus.Status = true@@ -366,25 +199,6 @@ func checkSmtpConnectionImpl(host, port, user, password string) *SmtpConnectionSreturn status}-// ForceRefreshSmtpStatus Forces refresh of the SMTP connection status cache.-func ForceRefreshSmtpStatus(ctx context.Context, relayConfig *v1.BmRelay) *SmtpConnectionStatus {- // Generate cache key- cacheKey := fmt.Sprintf(smtpStatusCacheKeyFormat, relayConfig.RelayHost, relayConfig.RelayPort, relayConfig.AuthUser)-- // Perform actual check- status := checkSmtpConnectionImpl(relayConfig.RelayHost, relayConfig.RelayPort, relayConfig.AuthUser, relayConfig.AuthPassword)-- // Update cache- smtpStatusCache.Set(ctx, cacheKey, status, smtpStatusCacheExpire)-- return status-}--// ClearSmtpStatusCache Clears the SMTP status cache.-func ClearSmtpStatusCache(ctx context.Context) error {- return smtpStatusCache.Clear(ctx)-}-func DecryptPassword1(ctx context.Context, encryptedHex string) (string, error) {password, err := DecryptPassword(ctx, encryptedHex)