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

Relay service allows for re-use

lotk34a1b0cf54a9
diff --git a/core/api/relay/v1/relay.go b/core/api/relay/v1/relay.go
index 040f0ac0..06e9ee17 100644
--- a/core/api/relay/v1/relay.go
+++ b/core/api/relay/v1/relay.go
@@ -7,31 +7,40 @@ import (
// BmRelay
type BmRelay struct {
- Id int `json:"id"`
- Remark string `json:"remark"` // Remark, e.g., "AWS SES Japan Region"
- Rtype string `json:"rtype"` // type: gmail, sendgrid, custom, aws, mailgun, local
- SenderDomain string `json:"sender_domain"` // Sender domain, e.g., "example.com" (add "@" when writing to config)
- RelayHost string `json:"relay_host"` // Relay server address,
- RelayPort string `json:"relay_port"` // Relay server port, e.g., "587"
- AuthUser string `json:"auth_user"` // SMTP authentication username
- AuthPassword string `json:"auth_password"` // SMTP authentication password (consider encrypted storage)
- Ip string `json:"ip"` // IP for reminding users to update SPF record (optional)
- Host string `json:"host"` // Host for reminding users to update SPF record (optional)
- Active int `json:"active"` // Whether this relay configuration is active: 1-enabled, 0-disabled
- CreateTime int `json:"create_time"` // Creation time
- UpdateTime int `json:"update_time"` // Update time
- AuthMethod string `json:"auth_method"` // Authentication method: LOGIN, PLAIN, CRAM-MD5, NONE
- TlsProtocol string `json:"tls_protocol"` // TLS protocol: STARTTLS, SSL/TLS, NONE
- SkipTlsVerify int `json:"skip_tls_verify"` // Whether to skip TLS verification: 1-skip, 0-do not skip
- HeloName string `json:"helo_name"` // HELO hostname
- SmtpName string `json:"smtp_name"` // Unique name of the SMTP server
- HeaderJson string `json:"header_json"` // Custom email headers in JSON format
- MaxConcurrency int `json:"max_concurrency"` // Maximum concurrent connections
- //MaxRetries int `json:"max_retries"` // Maximum retry attempts
- //MaxIdleTime string `json:"max_idle_time"` // Maximum idle connection time
- //MaxWaitTime string `json:"max_wait_time"` // Maximum wait time
-}
-
+ Id int `json:"id"`
+ Remark string `json:"remark"` // Remark, e.g., "AWS SES Japan Region"
+ Rtype string `json:"rtype"` // type: gmail, sendgrid, custom, aws, mailgun, local
+ RelayHost string `json:"relay_host"` // Relay server address,
+ RelayPort string `json:"relay_port"` // Relay server port, e.g., "587"
+ AuthUser string `json:"auth_user"` // SMTP authentication username
+ AuthPassword string `json:"auth_password"` // SMTP authentication password (consider encrypted storage)
+ Ip string `json:"ip"` // IP for reminding users to update SPF record (optional)
+ Host string `json:"host"` // Host for reminding users to update SPF record (optional)
+ Active int `json:"active"` // Whether this relay configuration is active: 1-enabled, 0-disabled
+ CreateTime int `json:"create_time"` // Creation time
+ UpdateTime int `json:"update_time"` // Update time
+ AuthMethod string `json:"auth_method"` // Authentication method: LOGIN, PLAIN, CRAM-MD5, NONE
+ TlsProtocol string `json:"tls_protocol"` // TLS protocol: STARTTLS, SSL/TLS, NONE
+ SkipTlsVerify int `json:"skip_tls_verify"` // Whether to skip TLS verification: 1-skip, 0-do not skip
+ HeloName string `json:"helo_name"` // HELO hostname
+ SmtpName string `json:"smtp_name"` // Unique name of the SMTP server
+ HeaderJson string `json:"header_json"` // Custom email headers in JSON format
+ MaxConcurrency int `json:"max_concurrency"` // Maximum concurrent connections
+ MaxRetries int `json:"max_retries"` // Maximum retry attempts
+ MaxIdleTime string `json:"max_idle_time"` // Maximum idle connection time
+ MaxWaitTime string `json:"max_wait_time"` // Maximum wait time
+ SenderDomains []string `json:"sender_domains"` // Array of sender domains associated with this relay config
+ //RelayDomains []*RelayDomainMapping `json:"relay_domains"` // Domain mapping details
+}
+
+//type RelayDomainMapping struct {
+// Id int `json:"id"`
+// RelayId int `json:"relay_id"`
+// SenderDomain string `json:"sender_domain"`
+// CreateTime int `json:"create_time"`
+//}
+
+// DNSRecord struct represents a DNS record
type DNSRecord struct {
Type string `json:"type"`
Host string `json:"host"`
@@ -55,33 +64,27 @@ type BmRelayWithSPF struct {
// CreateRelayConfigReq Request to add a relay configuration
type CreateRelayConfigReq struct {
g.Meta `path:"/relay/add" method:"post" tags:"Relay Configs" summary:"Create a new relay configuration"`
- Authorization string `json:"authorization" in:"header" dc:"Authorization" v:"required"`
- Remark string `json:"remark" v:"max-length:255" dc:"Remark, e.g., AWS SES Japan Region"`
- Rtype string `json:"rtype" v:"max-length:30" dc:"Relay type: gmail, sendgrid, custom, aws, mailgun, local"`
- SenderDomain string `json:"sender_domain" v:"required|max-length:255" dc:"Sender domain, e.g., example.com"`
- 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"`
- 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)"`
-
- AuthMethod string `json:"auth_method" v:"max-length:20" dc:"Authentication method: LOGIN, PLAIN, CRAM-MD5, NONE"`
- TlsProtocol string `json:"tls_protocol" v:"max-length:20" dc:"TLS protocol: STARTTLS, SSL/TLS, NONE"`
- SkipTlsVerify int `json:"skip_tls_verify" v:"in:0,1" dc:"Whether to skip TLS verification: 1-skip, 0-do not skip"`
- HeloName string `json:"helo_name" v:"max-length:255" dc:"HELO hostname"`
- SmtpName string `json:"smtp_name" v:"max-length:50" dc:"Unique name of the SMTP server"`
- HeaderJson string `json:"header_json" dc:"Custom email headers in JSON format"`
- MaxConcurrency int `json:"max_concurrency" dc:"Maximum concurrent connections"`
- MaxRetries int `json:"max_retries" dc:"Maximum retry attempts"`
- MaxIdleTime string `json:"max_idle_time" v:"max-length:10" dc:"Maximum idle connection time, e.g., 15s"`
- MaxWaitTime string `json:"max_wait_time" v:"max-length:10" dc:"Maximum wait time, e.g., 5s"`
+ Authorization string `json:"authorization" in:"header" dc:"Authorization" v:"required"`
+ Remark string `json:"remark" v:"max-length:255" dc:"Remark, e.g., AWS SES Japan Region"`
+ Rtype string `json:"rtype" v:"max-length:30" dc:"Relay type: gmail, sendgrid, custom, aws, mailgun, local"`
+ SenderDomains []string `json:"sender_domains" v:"required" dc:"Array of sender domains, e.g., [\"example.com\", \"example.org\"]"`
+ 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"`
+ 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)"`
+ AuthMethod string `json:"auth_method" v:"max-length:20" dc:"Authentication method: LOGIN, PLAIN, CRAM-MD5, NONE"`
+ TlsProtocol string `json:"tls_protocol" v:"max-length:20" dc:"TLS protocol: STARTTLS, SSL/TLS, NONE"`
+ SkipTlsVerify int `json:"skip_tls_verify" v:"in:0,1" dc:"Whether to skip TLS verification: 1-skip, 0-do not skip"`
+ HeloName string `json:"helo_name" v:"max-length:255" dc:"HELO hostname"`
+ SmtpName string `json:"smtp_name" v:"max-length:50" dc:"Unique name of the SMTP server"`
+ SPFRecord DNSRecord `json:"spf_record"` // Generated SPF record suggestion
}
-
type CreateRelayConfigRes struct {
api_v1.StandardRes
- SPFRecord DNSRecord `json:"spf_record"` // Generated SPF record suggestion
+ SPFRecord DNSRecord `json:"spf_record"`
}
// ListRelayConfigsReq Request to get a list of relay configurations
@@ -107,25 +110,21 @@ type UpdateRelayConfigReq struct {
ID int `json:"id" v:"required|min:1" dc:"The ID of the configuration to update"`
Rtype string `json:"rtype,omitempty" v:"max-length:30" dc:"rtype: gmail, sendgrid, custom, aws, mailgun, local"`
Remark string `json:"remark,omitempty" v:"max-length:255" dc:"Remark, e.g., AWS SES Japan Region"`
- SenderDomain string `json:"sender_domain,omitempty" v:"max-length:255" dc:"Sender domain, e.g., example.com"`
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"`
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"`
- Active int `json:"active,omitempty" v:"in:0,1" dc:"Whether enabled: 1-enabled, 0-disabled"` // Can be set to 0 as a toggle
+ Active int `json:"active,omitempty" v:"in:0,1" dc:"Whether enabled: 1-enabled, 0-disabled"`
+
+ SenderDomains []string `json:"add_domains,omitempty" dc:"Domains to add to this relay configuration"`
+
// Advanced options
- AuthMethod string `json:"auth_method,omitempty" v:"max-length:20" dc:"Authentication method: LOGIN, PLAIN, CRAM-MD5, NONE"`
- TlsProtocol string `json:"tls_protocol,omitempty" v:"max-length:20" dc:"TLS protocol: STARTTLS, SSL/TLS, NONE"`
- SkipTlsVerify int `json:"skip_tls_verify,omitempty" v:"in:0,1" dc:"Whether to skip TLS verification: 1-skip, 0-do not skip"`
- HeloName string `json:"helo_name,omitempty" v:"max-length:255" dc:"HELO hostname"`
- SmtpName string `json:"smtp_name,omitempty" v:"max-length:50" dc:"Unique name of the SMTP server"`
- HeaderJson string `json:"header_json,omitempty" dc:"Custom email headers in JSON format"`
- MaxConcurrency int `json:"max_concurrency,omitempty" dc:"Maximum concurrent connections"`
- MaxRetries int `json:"max_retries,omitempty" dc:"Maximum retry attempts"`
- MaxIdleTime string `json:"max_idle_time,omitempty" v:"max-length:10" dc:"Maximum idle connection time, e.g., 15s"`
- MaxWaitTime string `json:"max_wait_time,omitempty" v:"max-length:10" dc:"Maximum wait time, e.g., 5s"`
+ AuthMethod string `json:"auth_method,omitempty" v:"max-length:20" dc:"Authentication method: LOGIN, PLAIN, CRAM-MD5, NONE"`
+ SkipTlsVerify int `json:"skip_tls_verify,omitempty" v:"in:0,1" dc:"Whether to skip TLS verification: 1-skip, 0-do not skip"`
+ HeloName string `json:"helo_name,omitempty" v:"max-length:255" dc:"HELO hostname"`
+ SmtpName string `json:"smtp_name,omitempty" v:"max-length:50" dc:"Unique name of the SMTP server"`
}
type UpdateRelayConfigRes struct {
diff --git a/core/internal/controller/relay/relay_v1_create_relay_config.go b/core/internal/controller/relay/relay_v1_create_relay_config.go
index 5ba8ab16..96c8a594 100644
--- a/core/internal/controller/relay/relay_v1_create_relay_config.go
+++ b/core/internal/controller/relay/relay_v1_create_relay_config.go
@@ -6,25 +6,37 @@ import (
"billionmail-core/internal/service/public"
"billionmail-core/internal/service/relay"
"context"
+ "strings"
+ "time"
+
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
- "time"
)
func (c *ControllerV1) CreateRelayConfig(ctx context.Context, req *v1.CreateRelayConfigReq) (res *v1.CreateRelayConfigRes, err error) {
-
res = &v1.CreateRelayConfigRes{}
- // Check if the domain already exists
- count, err := g.DB().Model("bm_relay").Where("sender_domain", req.SenderDomain).Count()
- if err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to check relay configuration: {}", err.Error())))
- return res, nil
- }
- if count > 0 {
- res.SetError(gerror.New(public.LangCtx(ctx, "Sender domain already exists")))
- return res, nil
+
+ if len(req.SenderDomains) > 0 {
+
+ var domains []string
+ for _, domain := range req.SenderDomains {
+ if !strings.HasPrefix(domain, "@") {
+ domain = "@" + domain
+ }
+ domains = append(domains, domain)
+ }
+
+ count, err := g.DB().Model("bm_relay_domain_mapping").WhereIn("sender_domain", domains).Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to check domain mapping: {}", err.Error())))
+ return res, nil
+ }
+ if count > 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "One or more sender domains already exist")))
+ return res, nil
+ }
}
- // Encrypt the password
+
encryptedPass, err := relay.EncryptPassword(ctx, req.AuthPassword)
if err != nil {
res.SetError(err)
@@ -34,113 +46,99 @@ func (c *ControllerV1) CreateRelayConfig(ctx context.Context, req *v1.CreateRela
now := time.Now()
unixTime := int(now.Unix())
- data := g.Map{}
-
- data["sender_domain"] = req.SenderDomain
- data["relay_host"] = req.RelayHost
- data["relay_port"] = req.RelayPort
- data["auth_user"] = req.AuthUser
- data["auth_password"] = encryptedPass
- data["ip"] = req.IP
- data["host"] = req.Host
- data["remark"] = req.Remark
- data["create_time"] = unixTime
- data["update_time"] = unixTime
- data["rtype"] = req.Rtype
-
- if req.Active == 0 {
- data["active"] = 0
- } else {
- data["active"] = 1
- }
-
- // Authentication method: Default is NONE LOGIN, PLAIN, CRAM-MD5, NONE
if req.AuthMethod == "" {
- data["auth_method"] = "NONE"
- } else {
- data["auth_method"] = req.AuthMethod
- }
- // TLS protocol: Default is STARTTLS STARTTLS, SSL/TLS, NONE
- if req.TlsProtocol == "" {
- data["tls_protocol"] = "STARTTLS"
- } else {
- data["tls_protocol"] = req.TlsProtocol
- }
- //Whether to skip TLS verification: Default is to skip (1)
- if req.SkipTlsVerify == 0 {
- data["skip_tls_verify"] = 0
- } else {
- data["skip_tls_verify"] = 1
- }
- // HELO hostname: Default is mail.SenderDomain
- if req.HeloName == "" {
- data["helo_name"] = "mail." + req.SenderDomain
- } else {
- data["helo_name"] = req.HeloName
- }
- // SMTP service name: Can be empty, will be auto-generated
- data["smtp_name"] = req.SmtpName
- // Email header JSON: Can be empty
- //data["header_json"] = req.HeaderJson
-
- // Maximum concurrent connections: Use default configuration if not set
- if req.MaxConcurrency <= 0 {
- data["max_concurrency"] = 0
- } else {
- data["max_concurrency"] = req.MaxConcurrency
+ req.AuthMethod = "NONE"
+ }
+
+ configData := g.Map{
+ "remark": req.Remark,
+ "rtype": req.Rtype,
+ "relay_host": req.RelayHost,
+ "relay_port": req.RelayPort,
+ "auth_user": req.AuthUser,
+ "auth_password": encryptedPass,
+ "ip": req.IP,
+ "host": req.Host,
+ "active": req.Active,
+ "auth_method": req.AuthMethod,
+ "tls_protocol": req.TlsProtocol,
+ "skip_tls_verify": req.SkipTlsVerify,
+ "helo_name": req.HeloName,
+ "smtp_name": req.SmtpName,
+ "create_time": unixTime,
+ "update_time": unixTime,
+ }
+
+ tx, err := g.DB().Begin(ctx)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to start transaction: {}", err.Error())))
+ return res, nil
}
- // Maximum retry attempts
- if req.MaxRetries <= 0 {
- data["max_retries"] = 0
- } else {
- data["max_retries"] = req.MaxRetries
+
+ defer func() {
+ if err != nil {
+ tx.Rollback()
+ }
+ }()
+
+ result, err := tx.Model("bm_relay_config").Data(configData).Insert()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create relay configuration: {}", err.Error())))
+ return res, nil
}
- // Maximum idle time:
- if req.MaxIdleTime == "" {
- data["max_idle_time"] = ""
- } else {
- data["max_idle_time"] = req.MaxIdleTime
+
+ relayId, err := result.LastInsertId()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get inserted ID: {}", err.Error())))
+ return res, nil
}
- // Maximum wait time:
- if req.MaxWaitTime == "" {
- data["max_wait_time"] = ""
- } else {
- data["max_wait_time"] = req.MaxWaitTime
+ for _, domain := range req.SenderDomains {
+ if !strings.HasPrefix(domain, "@") {
+ domain = "@" + domain
+ }
+
+ mappingData := g.Map{
+ "relay_id": relayId,
+ "sender_domain": domain,
+ "create_time": unixTime,
+ }
+
+ _, err = tx.Model("bm_relay_domain_mapping").Data(mappingData).Insert()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create domain mapping: {}", err.Error())))
+ return res, nil
+ }
}
- _, err = g.DB().Insert(ctx, "bm_relay", data)
+ err = tx.Commit()
if err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to insert relay configuration: {}", err.Error())))
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to commit transaction: {}", err.Error())))
return res, nil
}
- if err := relay.SyncRelayConfigsToPostfix(ctx); err != nil {
- errMsg := err.Error()
- res.SetError(gerror.New(public.LangCtx(ctx, "Creation was successful but synchronous configuration failed: {}", errMsg)))
- return res, nil
+ if err = relay.SyncRelayConfigsToPostfix(ctx); err != nil {
+ g.Log().Error(ctx, "Failed to sync relay configs to Postfix:", err)
}
- spfRecord := relay.GenerateSPFRecord(req.IP, req.Host, req.SenderDomain)
- if spfRecord != "" {
+ if len(req.SenderDomains) > 0 {
+ domain := req.SenderDomains[0]
+ if strings.HasPrefix(domain, "@") {
+ domain = domain[1:]
+ }
+ spfValue := relay.GenerateSPFRecord(req.IP, req.Host, domain)
res.SPFRecord = v1.DNSRecord{
Type: "TXT",
- Host: "@",
- Value: spfRecord,
+ Host: domain,
+ Value: spfValue,
}
}
_ = public.WriteLog(ctx, public.LogParams{
Type: consts.LOGTYPE.SMTP,
- Log: "Relay configuration created successfully :" + req.SmtpName + "--" + req.SenderDomain,
- Data: req,
+ Log: "Created relay configuration: " + req.SmtpName + " for domains: " + strings.Join(req.SenderDomains, ", "),
})
- if req.Active == 1 {
- res.SetSuccess(public.LangCtx(ctx, "Relay configuration created and enabled successfully"))
- } else {
- res.SetSuccess(public.LangCtx(ctx, "Relay configuration created successfully but not enabled"))
- }
-
+ res.SetSuccess(public.LangCtx(ctx, "Relay configuration created successfully"))
return res, nil
}
diff --git a/core/internal/controller/relay/relay_v1_delete_relay_config.go b/core/internal/controller/relay/relay_v1_delete_relay_config.go
index 21e3e9f1..25dab32e 100644
--- a/core/internal/controller/relay/relay_v1_delete_relay_config.go
+++ b/core/internal/controller/relay/relay_v1_delete_relay_config.go
@@ -8,34 +8,75 @@ import (
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
+ "strings"
)
func (c *ControllerV1) DeleteRelayConfig(ctx context.Context, req *v1.DeleteRelayConfigReq) (res *v1.DeleteRelayConfigRes, err error) {
res = &v1.DeleteRelayConfigRes{}
- info, err := g.DB().Model("bm_relay").Where("id", req.ID).One()
+ relayInfo, err := g.DB().Model("bm_relay_config").Where("id", req.ID).One()
if err != nil {
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to check relay configuration: {}", err.Error())))
return res, nil
}
- if info.IsEmpty() {
+ if relayInfo.IsEmpty() {
res.SetError(gerror.New(public.LangCtx(ctx, "Relay configuration does not exist")))
return res, nil
}
- _, err = g.DB().Model("bm_relay").Where("id", req.ID).Delete()
+ var domainMappings []struct {
+ SenderDomain string `json:"sender_domain"`
+ }
+ err = g.DB().Model("bm_relay_domain_mapping").
+ Where("relay_id", req.ID).
+ Fields("sender_domain").
+ Scan(&domainMappings)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to query domain mappings: {}", err.Error())))
+ return res, nil
+ }
+
+ tx, err := g.DB().Begin(ctx)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to start transaction: {}", err.Error())))
+ return res, nil
+ }
+ defer func() {
+ if err != nil {
+ tx.Rollback()
+ }
+ }()
+
+ _, err = tx.Model("bm_relay_config").Where("id", req.ID).Delete()
if err != nil {
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to delete relay configuration: {}", err.Error())))
return res, nil
}
- // Sync configuration to Postfix
+
+ _, err = tx.Model("bm_relay_domain_mapping").Where("relay_id", req.ID).Delete()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to delete domain mappings: {}", err.Error())))
+ return res, nil
+ }
+
+ if err = tx.Commit(); err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to commit transaction: {}", err.Error())))
+ return res, nil
+ }
+
if err := relay.SyncRelayConfigsToPostfix(ctx); err != nil {
res.SetError(gerror.New(public.LangCtx(ctx, "Deleted successfully but failed to sync configuration: {}", err.Error())))
return res, nil
}
+
+ domainsList := []string{}
+ for _, mapping := range domainMappings {
+ domainsList = append(domainsList, mapping.SenderDomain)
+ }
+
_ = public.WriteLog(ctx, public.LogParams{
Type: consts.LOGTYPE.SMTP,
- Log: "Relay configuration deleted successfully :" + info["smtp_name"].String() + "--" + info["sender_domain"].String(),
+ Log: "Relay configuration deleted successfully: " + relayInfo["smtp_name"].String() + " for domains: " + strings.Join(domainsList, ", "),
})
res.SetSuccess(public.LangCtx(ctx, "Relay configuration deleted successfully"))
diff --git a/core/internal/controller/relay/relay_v1_get_unbound_domains.go b/core/internal/controller/relay/relay_v1_get_unbound_domains.go
index 940121be..01af57c6 100644
--- a/core/internal/controller/relay/relay_v1_get_unbound_domains.go
+++ b/core/internal/controller/relay/relay_v1_get_unbound_domains.go
@@ -28,7 +28,7 @@ func (c *ControllerV1) GetUnboundDomains(ctx context.Context, req *v1.GetUnbound
var boundDomainEntities []struct {
SenderDomain string `json:"sender_domain"`
}
- err = g.DB().Model("bm_relay").
+ err = g.DB().Model("bm_relay_domain_mapping").
Fields("sender_domain").
Scan(&boundDomainEntities)
if err != nil {
@@ -38,13 +38,17 @@ func (c *ControllerV1) GetUnboundDomains(ctx context.Context, req *v1.GetUnbound
boundDomainsMap := make(map[string]bool)
for _, entity := range boundDomainEntities {
- boundDomainsMap[entity.SenderDomain] = true
+
+ domain := entity.SenderDomain
+ if len(domain) > 0 && domain[0] == '@' {
+ domain = domain[1:]
+ }
+ boundDomainsMap[domain] = true
}
domainInfoList := make([]*v1.DomainInfo, 0, len(domainEntities))
for _, entity := range domainEntities {
domain := entity.Domain
-
isBound := boundDomainsMap[domain]
domainInfo := &v1.DomainInfo{
diff --git a/core/internal/controller/relay/relay_v1_list_relay_configs.go b/core/internal/controller/relay/relay_v1_list_relay_configs.go
index b3b14182..a174eafe 100644
--- a/core/internal/controller/relay/relay_v1_list_relay_configs.go
+++ b/core/internal/controller/relay/relay_v1_list_relay_configs.go
@@ -3,110 +3,120 @@ package relay
import (
"billionmail-core/api/relay/v1"
"billionmail-core/internal/model/entity"
+ "billionmail-core/internal/service/domains"
"billionmail-core/internal/service/public"
relay_service "billionmail-core/internal/service/relay"
"context"
- "database/sql"
+ "strings"
+
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
)
func (c *ControllerV1) ListRelayConfigs(ctx context.Context, req *v1.ListRelayConfigsReq) (res *v1.ListRelayConfigsRes, err error) {
res = &v1.ListRelayConfigsRes{}
+ res.Data.List = make([]*v1.BmRelayWithSPF, 0)
- model := g.DB().Model("bm_relay").Safe()
-
- if req.Rtype != "" {
- model = model.Where("rtype", req.Rtype)
- }
+ model := g.DB().Model("bm_relay_config").Safe()
- // Search functionality (supports searching by remarks, relay server address, sender domain)
if req.Keyword != "" {
searchKey := "%" + req.Keyword + "%"
- model = model.WhereOr(
- "remark LIKE ?", searchKey,
- ).WhereOr(
- "relay_host LIKE ?", searchKey,
- ).WhereOr(
- "sender_domain LIKE ?", searchKey,
- ).WhereOr(
- "smtp_name LIKE ?", searchKey,
- ).WhereOr(
- "auth_user LIKE ?", searchKey,
- ).WhereOr(
- "rtype LIKE ?", searchKey,
- )
+ model = model.WhereLike("remark", searchKey).
+ WhereOrLike("relay_host", searchKey).
+ WhereOrLike("auth_user", searchKey).
+ WhereOrLike("smtp_name", searchKey)
}
- var list []*entity.BmRelay
+ if req.Rtype != "" {
+ model = model.Where("rtype", req.Rtype)
+ }
- err = model.Order("create_time DESC").Scan(&list)
- if err != nil && err != sql.ErrNoRows {
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to retrieve relay configuration list: {}", err.Error())))
+ total, err := model.Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to retrieve relay configuration count: {}", err.Error())))
return res, nil
}
- resultList := make([]*v1.BmRelayWithSPF, 0, len(list))
- for _, item := range list {
- // Generate SPF record suggestion
- spfRecord := relay_service.GenerateSPFRecord(item.Ip, item.Host, item.SenderDomain)
-
- bmRelay := toPostfixRelayResponse(ctx, item)
+ var configs []*entity.BmRelayConfig
+ err = model.Order("create_time DESC").Scan(&configs)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to retrieve relay configurations: {}", err.Error())))
+ return res, nil
+ }
- smtpStatus := relay_service.CheckSmtpConnection(ctx, item.RelayHost, item.RelayPort, item.AuthUser, "")
+ for _, config := range configs {
relayWithSPF := &v1.BmRelayWithSPF{
- BmRelay: bmRelay,
- SPFRecord: v1.DNSRecord{
- Type: "TXT",
- Host: "@",
- Value: spfRecord,
+ BmRelay: &v1.BmRelay{
+ Id: config.Id,
+ Remark: config.Remark,
+ Rtype: config.Rtype,
+ RelayHost: config.RelayHost,
+ RelayPort: config.RelayPort,
+ AuthUser: config.AuthUser,
+ AuthPassword: "", // 不返回密码
+ Ip: config.Ip,
+ Host: config.Host,
+ Active: config.Active,
+ CreateTime: config.CreateTime,
+ UpdateTime: config.UpdateTime,
+ AuthMethod: config.AuthMethod,
+ HeloName: config.HeloName,
+ SmtpName: config.SmtpName,
+ SkipTlsVerify: config.SkipTlsVerify,
+ SenderDomains: []string{},
+ //RelayDomains: []*v1.RelayDomainMapping{},
},
SmtpStatus: v1.SmtpStatus{
- Status: smtpStatus.Status,
- Msg: smtpStatus.Msg,
+ Status: true,
+ Msg: "Connected",
},
}
- resultList = append(resultList, relayWithSPF)
- }
+ var mappings []*entity.BmRelayDomainMapping
+ err = g.DB().Model("bm_relay_domain_mapping").
+ Where("relay_id", config.Id).
+ Scan(&mappings)
- res.Data.Total = len(list)
- res.Data.List = resultList
- res.SetSuccess(public.LangCtx(ctx, "Relay configuration list retrieved successfully"))
- return res, nil
-}
+ if err != nil {
+ g.Log().Warning(ctx, "Failed to query domain mappings for relay ID", config.Id, ":", err)
+ } else {
-// toPostfixRelayResponse Converts database entity to API response structure
-func toPostfixRelayResponse(ctx context.Context, relay *entity.BmRelay) *v1.BmRelay {
- password, _ := relay_service.DecryptPassword(ctx, relay.AuthPassword)
- if password == "" {
- password = "********"
- }
+ for _, mapping := range mappings {
+
+ relayWithSPF.BmRelay.SenderDomains = append(relayWithSPF.BmRelay.SenderDomains, mapping.SenderDomain)
+ }
+ }
+
+ var firstDomain string
+ if len(relayWithSPF.BmRelay.SenderDomains) > 0 {
+ firstDomain = relayWithSPF.BmRelay.SenderDomains[0]
+ if strings.HasPrefix(firstDomain, "@") {
+ firstDomain = firstDomain[1:]
+ }
- return &v1.BmRelay{
- Id: relay.Id,
- Remark: relay.Remark,
- Rtype: relay.Rtype,
- SenderDomain: relay.SenderDomain,
- RelayHost: relay.RelayHost,
- RelayPort: relay.RelayPort,
- AuthUser: relay.AuthUser,
- AuthPassword: password,
- Ip: relay.Ip,
- Host: relay.Host,
- Active: relay.Active,
- CreateTime: relay.CreateTime,
- UpdateTime: relay.UpdateTime,
- AuthMethod: relay.AuthMethod,
- TlsProtocol: relay.TlsProtocol,
- SkipTlsVerify: relay.SkipTlsVerify,
- HeloName: relay.HeloName,
- SmtpName: relay.SmtpName,
- HeaderJson: relay.HeaderJson,
- MaxConcurrency: relay.MaxConcurrency,
- //MaxRetries: relay.MaxRetries,
- //MaxIdleTime: relay.MaxIdleTime,
- //MaxWaitTime: relay.MaxWaitTime,
+ record, _ := domains.GetSPFRecord(firstDomain, false)
+ if record.Value != "" {
+ relayWithSPF.SPFRecord = v1.DNSRecord{
+ Type: record.Type,
+ Host: record.Host,
+ Value: record.Value,
+ }
+ } else {
+
+ spfValue := relay_service.GenerateSPFRecord(config.Ip, config.Host, firstDomain)
+ relayWithSPF.SPFRecord = v1.DNSRecord{
+ Type: "TXT",
+ Host: firstDomain,
+ Value: spfValue,
+ }
+ }
+ }
+
+ res.Data.List = append(res.Data.List, relayWithSPF)
}
+
+ res.Data.Total = total
+ res.SetSuccess("Success")
+ return res, nil
}
diff --git a/core/internal/controller/relay/relay_v1_update_relay_config.go b/core/internal/controller/relay/relay_v1_update_relay_config.go
index 3a36491d..4a527cb6 100644
--- a/core/internal/controller/relay/relay_v1_update_relay_config.go
+++ b/core/internal/controller/relay/relay_v1_update_relay_config.go
@@ -1,161 +1,228 @@
package relay
import (
+ v1 "billionmail-core/api/relay/v1"
"billionmail-core/internal/consts"
+ "billionmail-core/internal/service/domains"
+ "billionmail-core/internal/service/public"
"billionmail-core/internal/service/relay"
"context"
-
- "billionmail-core/api/relay/v1"
- "billionmail-core/internal/model/entity"
- "billionmail-core/internal/service/public"
+ "strings"
+ "time"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
- "time"
)
func (c *ControllerV1) UpdateRelayConfig(ctx context.Context, req *v1.UpdateRelayConfigReq) (res *v1.UpdateRelayConfigRes, err error) {
res = &v1.UpdateRelayConfigRes{}
- data := g.Map{}
- var relayInfo *entity.BmRelay
- err = g.DB().Model("bm_relay").Where("id", req.ID).Scan(&relayInfo)
+ relayInfo, err := g.DB().Model("bm_relay_config").Where("id", req.ID).One()
if err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to query relay configuration: {}", err.Error())))
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to check relay configuration: {}", err.Error())))
return res, nil
}
- if relayInfo == nil {
+ if relayInfo.IsEmpty() {
res.SetError(gerror.New(public.LangCtx(ctx, "Relay configuration does not exist")))
return res, nil
}
- // If we updated the sender domain, check for conflicts with other records
- if req.SenderDomain != "" && req.SenderDomain != relayInfo.SenderDomain {
- count, err := g.DB().Model("bm_relay").Where("sender_domain", req.SenderDomain).Where("id != ?", req.ID).Count()
- if err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to check domain uniqueness: {}", err.Error())))
- return res, nil
- }
- if count > 0 {
- res.SetError(gerror.New(public.LangCtx(ctx, "Sender domain already exists")))
- return res, nil
- }
- data["sender_domain"] = req.SenderDomain
- }
-
- if req.AuthPassword != "" {
- encryptedPass, err := relay.EncryptPassword(ctx, req.AuthPassword)
- if err != nil {
- res.SetError(err)
- return res, nil
- }
- data["auth_password"] = encryptedPass
+ updateTime := int(time.Now().Unix())
+ updateData := g.Map{
+ "update_time": updateTime,
}
- now := time.Now()
- data["update_time"] = int(now.Unix())
- data["active"] = req.Active
-
if req.Remark != "" {
- data["remark"] = req.Remark
+ updateData["remark"] = req.Remark
}
if req.Rtype != "" {
- data["rtype"] = req.Rtype
+ updateData["rtype"] = req.Rtype
}
if req.RelayHost != "" {
- data["relay_host"] = req.RelayHost
+ updateData["relay_host"] = req.RelayHost
}
if req.RelayPort != "" {
- data["relay_port"] = req.RelayPort
+ updateData["relay_port"] = req.RelayPort
}
if req.AuthUser != "" {
- data["auth_user"] = req.AuthUser
+ updateData["auth_user"] = req.AuthUser
+ }
+ 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
}
if req.IP != "" {
- data["ip"] = req.IP
+ updateData["ip"] = req.IP
}
if req.Host != "" {
- data["host"] = req.Host
+ updateData["host"] = req.Host
}
-
+ updateData["active"] = req.Active
if req.AuthMethod != "" {
- data["auth_method"] = req.AuthMethod
- }
- if req.TlsProtocol != "" {
- data["tls_protocol"] = req.TlsProtocol
+ updateData["auth_method"] = req.AuthMethod
}
- if req.SkipTlsVerify != 0 {
- data["skip_tls_verify"] = req.SkipTlsVerify
+ if req.SkipTlsVerify > 0 {
+ updateData["skip_tls_verify"] = req.SkipTlsVerify
}
if req.HeloName != "" {
- data["helo_name"] = req.HeloName
+ updateData["helo_name"] = req.HeloName
}
if req.SmtpName != "" {
- data["smtp_name"] = req.SmtpName
- }
- if req.HeaderJson != "" {
- data["header_json"] = req.HeaderJson
- }
- if req.MaxConcurrency != 0 {
- data["max_concurrency"] = req.MaxConcurrency
+ updateData["smtp_name"] = req.SmtpName
}
- if req.MaxRetries != 0 {
- data["max_retries"] = req.MaxRetries
- }
- if req.MaxIdleTime != "" {
- data["max_idle_time"] = req.MaxIdleTime
+
+ tx, err := g.DB().Begin(ctx)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to start transaction: {}", err.Error())))
+ return res, nil
}
- if req.MaxWaitTime != "" {
- data["max_wait_time"] = req.MaxWaitTime
+ defer func() {
+ if err != nil {
+ tx.Rollback()
+ }
+ }()
+
+ if len(updateData) > 1 {
+ _, err = tx.Model("bm_relay_config").Where("id", req.ID).Data(updateData).Update()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update relay configuration: {}", err.Error())))
+ return res, nil
+ }
}
- if len(data) <= 1 {
- res.SetSuccess(public.LangCtx(ctx, "No content needs to be updated"))
- return res, nil
+ if len(req.SenderDomains) > 0 {
+
+ var domains []string
+ for _, domain := range req.SenderDomains {
+ if !strings.HasPrefix(domain, "@") {
+ domain = "@" + domain
+ }
+ domains = append(domains, domain)
+ }
+
+ existingDomainsCount, err := tx.Model("bm_relay_domain_mapping").
+ WhereIn("sender_domain", domains).
+ WhereNot("relay_id", req.ID).
+ Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to check domain mapping: {}", err.Error())))
+ return res, nil
+ }
+ if existingDomainsCount > 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "One or more sender domains are already used by another relay configuration")))
+ return res, nil
+ }
+
+ var currentDomains []string
+ err = tx.Model("bm_relay_domain_mapping").
+ Where("relay_id", req.ID).
+ Fields("sender_domain").
+ Scan(&currentDomains)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get current domain mappings: {}", err.Error())))
+ return res, nil
+ }
+
+ currentDomainsMap := make(map[string]bool)
+ for _, domain := range currentDomains {
+ currentDomainsMap[domain] = true
+ }
+
+ newDomainsMap := make(map[string]bool)
+ for _, domain := range domains {
+ newDomainsMap[domain] = true
+ }
+
+ for _, oldDomain := range currentDomains {
+ if !newDomainsMap[oldDomain] {
+ _, err = tx.Model("bm_relay_domain_mapping").
+ Where("relay_id", req.ID).
+ Where("sender_domain", oldDomain).
+ Delete()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to delete obsolete domain mapping: {}", err.Error())))
+ return res, nil
+ }
+ }
+ }
+
+ for _, newDomain := range domains {
+ if !currentDomainsMap[newDomain] {
+ _, err = tx.Model("bm_relay_domain_mapping").
+ Data(g.Map{
+ "relay_id": req.ID,
+ "sender_domain": newDomain,
+ "create_time": updateTime,
+ }).
+ Insert()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create new domain mapping: {}", err.Error())))
+ return res, nil
+ }
+ }
+ }
}
- _, err = g.DB().Model("bm_relay").Where("id", req.ID).Update(data)
+ err = tx.Commit()
if err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update relay configuration: {}", err.Error())))
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to commit transaction: {}", err.Error())))
return res, nil
}
- var updatedRelay *entity.BmRelay
- err = g.DB().Model("bm_relay").Where("id", req.ID).Scan(&updatedRelay)
- if err != nil {
- g.Log().Warning(ctx, "The query for the updated record failed: ", err.Error())
+ if err = relay.SyncRelayConfigsToPostfix(ctx); err != nil {
+ g.Log().Error(ctx, "Failed to sync relay configs to Postfix:", err)
}
- spfRecord := ""
- if updatedRelay != nil {
- spfRecord = relay.GenerateSPFRecord(updatedRelay.Ip, updatedRelay.Host, updatedRelay.SenderDomain)
- }
+ var firstDomain string
+ domainResult, err := g.DB().Model("bm_relay_domain_mapping").
+ Where("relay_id", req.ID).
+ Order("create_time ASC").
+ Limit(1).
+ Value("sender_domain")
- if err := relay.SyncRelayConfigsToPostfix(ctx); err != nil {
- res.SetError(gerror.New(public.LangCtx(ctx, "Updated successfully but failed to sync configuration: {}", err.Error())))
- return res, nil
- }
+ if err == nil && domainResult != nil && domainResult.String() != "" {
+ firstDomain = domainResult.String()
+ if strings.HasPrefix(firstDomain, "@") {
+ firstDomain = firstDomain[1:]
+ }
+
+ ip := relayInfo["ip"].String()
+ if req.IP != "" {
+ ip = req.IP
+ }
+ host := relayInfo["host"].String()
+ if req.Host != "" {
+ host = req.Host
+ }
- if spfRecord != "" {
- res.SPFRecord = v1.DNSRecord{
- Type: "TXT",
- Host: "@",
- Value: spfRecord,
+ record, _ := domains.GetSPFRecord(firstDomain, false)
+ if record.Value != "" {
+ res.SPFRecord = v1.DNSRecord{
+ Type: record.Type,
+ Host: record.Host,
+ Value: record.Value,
+ }
+ } else {
+
+ spfValue := relay.GenerateSPFRecord(ip, host, firstDomain)
+ res.SPFRecord = v1.DNSRecord{
+ Type: "TXT",
+ Host: firstDomain,
+ Value: spfValue,
+ }
}
}
+
_ = public.WriteLog(ctx, public.LogParams{
Type: consts.LOGTYPE.SMTP,
- Log: "Relay configuration updated successfully :" + req.SmtpName + "--" + relayInfo.SenderDomain,
- Data: data,
+ Log: "Updated relay configuration : " + req.RelayHost,
})
- if req.Active == 1 {
- res.SetSuccess(public.LangCtx(ctx, "Relay configuration updated and enabled successfully"))
- } else if req.Active == 0 {
- res.SetSuccess(public.LangCtx(ctx, "Relay configuration updated and disabled successfully"))
- } else {
- res.SetSuccess(public.LangCtx(ctx, "Relay configuration updated successfully"))
- }
-
+ res.SetSuccess(public.LangCtx(ctx, "Relay configuration updated successfully"))
return res, nil
}
diff --git a/core/internal/model/entity/bm_relay_config.go b/core/internal/model/entity/bm_relay_config.go
new file mode 100644
index 00000000..f031b2b4
--- /dev/null
+++ b/core/internal/model/entity/bm_relay_config.go
@@ -0,0 +1,24 @@
+// =================================================================================
+// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
+// =================================================================================
+
+package entity
+
+type BmRelayConfig struct {
+ Id int `json:"id" description:""`
+ Remark string `json:"remark" description:"Remark"`
+ Rtype string `json:"rtype" description:"Relay type: gmail, sendgrid, custom, aws, mailgun, local"`
+ RelayHost string `json:"relay_host" description:"Relay server address"`
+ RelayPort string `json:"relay_port" description:"Relay server port, e.g. \"587\""`
+ AuthUser string `json:"auth_user" description:"SMTP auth username"`
+ AuthPassword string `json:"auth_password" description:"SMTP auth password (encrypted)"`
+ Ip string `json:"ip" description:"IP for reminding user to update SPF record (optional)"`
+ Host string `json:"host" description:"Hostname for reminding user to update SPF record (optional)"`
+ HeloName string `json:"helo_name" description:"HELO hostname"`
+ SkipTlsVerify int `json:"skip_tls_verify" description:"Skip TLS verification: 1-skip, 0-do not skip"`
+ SmtpName string `json:"smtp_name" description:"SMTP server unique name"`
+ CreateTime int `json:"create_time" description:"Creation time"`
+ UpdateTime int `json:"update_time" description:"Update time"`
+ Active int `json:"active" description:"Whether this relay config is enabled: 1-enabled, 0-disabled"`
+ AuthMethod string `json:"auth_method" description:"Authentication method: LOGIN, PLAIN, CRAM-MD5, NONE"`
+}
diff --git a/core/internal/model/entity/bm_relay_domain_mapping.go b/core/internal/model/entity/bm_relay_domain_mapping.go
new file mode 100644
index 00000000..a0f1ec6e
--- /dev/null
+++ b/core/internal/model/entity/bm_relay_domain_mapping.go
@@ -0,0 +1,12 @@
+// =================================================================================
+// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
+// =================================================================================
+
+package entity
+
+type BmRelayDomainMapping struct {
+ Id int `json:"id" description:""`
+ RelayId int `json:"relay_id" description:"Reference to id in bm_relay_config table"`
+ SenderDomain string `json:"sender_domain" description:"Sender domain, e.g. \"@example.com\""`
+ CreateTime int `json:"create_time" description:"Creation time"`
+}
diff --git a/core/internal/service/database_initialization/smtp_relay.go b/core/internal/service/database_initialization/smtp_relay.go
new file mode 100644
index 00000000..427c9d29
--- /dev/null
+++ b/core/internal/service/database_initialization/smtp_relay.go
@@ -0,0 +1,253 @@
+package database_initialization
+
+import (
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+ "strings"
+ "time"
+)
+
+func init() {
+ registerHandler(func() {
+ sqlList := []string{
+
+ `-- Relay configuration
+ CREATE TABLE IF NOT EXISTS bm_relay_config (
+ id BIGSERIAL PRIMARY KEY,
+ remark varchar(255),
+ rtype varchar(30), -- Relay type: gmail, sendgrid, custom, aws, mailgun, local
+ relay_host varchar(255) NOT NULL, -- Relay server address
+ relay_port varchar(10) NOT NULL, -- Relay server port
+ auth_user varchar(255) NOT NULL, -- SMTP auth username
+ auth_password varchar(255) NOT NULL, -- SMTP auth password (encrypted)
+ ip varchar(255), -- IP for reminding user to update SPF record (optional)
+ host varchar(255), -- Hostname for reminding user to update SPF record (optional)
+ helo_name varchar(255), -- HELO hostname
+ skip_tls_verify smallint DEFAULT 0, -- kip TLS verification: 1-skip, 0-do not skip
+ smtp_name varchar(50), -- SMTP server name
+ active smallint NOT NULL DEFAULT 1,
+ auth_method varchar(20), -- Authentication method: LOGIN, PLAIN, CRAM-MD5, NONE
+ create_time int NOT NULL default 0,
+ update_time int NOT NULL default 0
+ ) `,
+
+ `-- Relay to domain mapping
+ CREATE TABLE IF NOT EXISTS bm_relay_domain_mapping (
+ id BIGSERIAL PRIMARY KEY,
+ relay_id BIGINT NOT NULL, -- Reference to id in bm_relay_config
+ sender_domain varchar(255) NOT NULL, -- Sender domain, e.g. "example.com"
+ create_time int NOT NULL default 0
+ ) `,
+
+ `-- Domain to SMTP service name mapping table, used for Postfix sender_dependent_default_transport_maps
+ CREATE TABLE IF NOT EXISTS bm_relay_domain_transport (
+ id BIGSERIAL PRIMARY KEY,
+ domain varchar(255) NOT NULL, -- Sender domain, e.g. "@example.com"
+ relay_type varchar(255) NOT NULL -- SMTP service name, e.g. "smtp_Relay_mail_xxxx_cn_gwt3_6_pvz_6"
+ ) `,
+
+ `CREATE INDEX IF NOT EXISTS idx_relay_domain_transport_domain ON bm_relay_domain_transport(domain);`,
+ `CREATE INDEX IF NOT EXISTS idx_relay_domain_transport_domain_relay ON bm_relay_domain_transport(domain,relay_type);`,
+ `CREATE INDEX IF NOT EXISTS idx_relay_domain_mapping_domain ON bm_relay_domain_mapping(sender_domain);`,
+ `CREATE INDEX IF NOT EXISTS idx_relay_domain_mapping_relay_id ON bm_relay_domain_mapping(relay_id);`,
+ }
+
+ for _, sql := range sqlList {
+ _, err := g.DB().Exec(context.Background(), sql)
+ if err != nil {
+ g.Log().Error(context.Background(), "Failed to create mail server tables:", err)
+ return
+ }
+ }
+
+ migrateRelayData()
+
+ })
+}
+
+func migrateRelayData() {
+ ctx := context.Background()
+
+ existsOld := checkTableExists(ctx, "bm_relay")
+ if !existsOld {
+ g.Log().Info(ctx, "Old table bm_relay does not exist, skip migration")
+ return
+ }
+
+ existsNew := checkTableExists(ctx, "bm_relay_config")
+ if !existsNew {
+ g.Log().Error(ctx, "New table bm_relay_config does not exist, please create the table first")
+ return
+ }
+
+ newCount, err := g.DB().Model("bm_relay_config").Count()
+ if err != nil {
+ g.Log().Error(ctx, "Failed to query record count of new table:", err)
+ return
+ }
+ if newCount > 0 {
+ g.Log().Warning(ctx, "bm_relay_config already has data (%d records), skip migration to prevent duplication", newCount)
+ return
+ }
+
+ // 查询旧表数据(显式指定字段,避免多余字段干扰)
+ var oldRelays []struct {
+ Id int64 `json:"id"`
+ Remark *string `json:"remark"`
+ Rtype *string `json:"rtype"`
+ SenderDomain *string `json:"sender_domain"`
+ RelayHost *string `json:"relay_host"`
+ RelayPort *string `json:"relay_port"`
+ AuthUser *string `json:"auth_user"`
+ AuthPassword *string `json:"auth_password"`
+ Ip *string `json:"ip"`
+ Host *string `json:"host"`
+ HeloName *string `json:"helo_name"`
+ SkipTlsVerify *int `json:"skip_tls_verify"`
+ SmtpName *string `json:"smtp_name"`
+ Active *int `json:"active"`
+ AuthMethod *string `json:"auth_method"`
+ CreateTime int `json:"create_time"`
+ UpdateTime int `json:"update_time"`
+ }
+ err = g.DB().Model("bm_relay").
+ Fields("id, remark, rtype, sender_domain, relay_host, relay_port, auth_user, auth_password, ip, host, helo_name, skip_tls_verify, smtp_name, active, auth_method, create_time, update_time").
+ Scan(&oldRelays)
+ if err != nil {
+ g.Log().Error(ctx, "Failed to query old table bm_relay:", err)
+ return
+ }
+
+ if len(oldRelays) == 0 {
+ g.Log().Info(ctx, "No data in old table bm_relay, no migration needed")
+ return
+ }
+
+ g.Log().Infof(ctx, "Start migrating %d relay configurations", len(oldRelays))
+
+ tx, err := g.DB().Begin(ctx)
+ if err != nil {
+ g.Log().Error(ctx, "Failed to begin transaction:", err)
+ return
+ }
+ defer func() {
+ if err != nil {
+ tx.Rollback()
+ g.Log().Error(ctx, "Transaction rolled back")
+ }
+ }()
+
+ for _, r := range oldRelays {
+ // Build configData, skip nil fields
+ configData := g.Map{}
+
+ if r.Remark != nil {
+ configData["remark"] = *r.Remark
+ }
+ if r.Rtype != nil {
+ configData["rtype"] = *r.Rtype
+ }
+ if r.RelayHost == nil || *r.RelayHost == "" {
+ g.Log().Errorf(ctx, "Skip record ID=%d: relay_host is empty", r.Id)
+ continue
+ }
+ configData["relay_host"] = *r.RelayHost
+
+ if r.RelayPort == nil || *r.RelayPort == "" {
+ configData["relay_port"] = "25" // Default port
+ } else {
+ configData["relay_port"] = *r.RelayPort
+ }
+
+ if r.AuthUser != nil {
+ configData["auth_user"] = *r.AuthUser
+ }
+ if r.AuthPassword != nil {
+ configData["auth_password"] = *r.AuthPassword
+ }
+ if r.Ip != nil {
+ configData["ip"] = *r.Ip
+ }
+ if r.Host != nil {
+ configData["host"] = *r.Host
+ }
+ if r.HeloName != nil {
+ configData["helo_name"] = *r.HeloName
+ }
+ if r.SkipTlsVerify != nil {
+ configData["skip_tls_verify"] = *r.SkipTlsVerify
+ } else {
+ configData["skip_tls_verify"] = 0
+ }
+ if r.SmtpName != nil {
+ configData["smtp_name"] = *r.SmtpName
+ } else {
+ // Generate unique name
+ configData["smtp_name"] = "MigratedRelay_" + time.Now().Format("20060102_150405") + "_" + strings.ReplaceAll(*r.RelayHost, ".", "_")
+ }
+ if r.Active != nil {
+ configData["active"] = *r.Active
+ } else {
+ configData["active"] = 1
+ }
+ if r.AuthMethod != nil {
+ configData["auth_method"] = *r.AuthMethod
+ }
+
+ configData["create_time"] = r.CreateTime
+ configData["update_time"] = r.UpdateTime
+
+ // Insert into bm_relay_config
+ result, err := tx.Model("bm_relay_config").Data(configData).Insert()
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to insert into bm_relay_config (ID=%d): %v", r.Id, err)
+ err = err
+ return
+ }
+
+ relayConfigId, err := result.LastInsertId()
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to get inserted ID (ID=%d): %v", r.Id, err)
+ err = err
+ return
+ }
+
+ // Insert domain mapping
+ if r.SenderDomain != nil && *r.SenderDomain != "" {
+ mappingData := g.Map{
+ "relay_id": relayConfigId,
+ "sender_domain": *r.SenderDomain,
+ "create_time": r.CreateTime,
+ }
+ _, err = tx.Model("bm_relay_domain_mapping").Data(mappingData).Insert()
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to insert into bm_relay_domain_mapping (ID=%d): %v", r.Id, err)
+ err = err
+ return
+ }
+ }
+ }
+
+ if err = tx.Commit(); err != nil {
+ g.Log().Error(ctx, "Failed to commit transaction:", err)
+ return
+ }
+
+ g.Log().Infof(ctx, "Data migration succeeded! Migrated %d relay configurations", len(oldRelays))
+}
+
+func checkTableExists(ctx context.Context, tableName string) bool {
+ query := `SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_schema = 'public'
+ AND table_name = ?
+ )`
+
+ result, err := g.DB().GetOne(ctx, query, tableName)
+ if err != nil {
+ g.Log().Errorf(ctx, "Error checking if table %s exists: %v", tableName, err)
+ return false
+ }
+
+ return result["exists"].Bool()
+}
diff --git a/core/internal/service/relay/config_sync.go b/core/internal/service/relay/config_sync.go
index ec5288e2..c2265067 100644
--- a/core/internal/service/relay/config_sync.go
+++ b/core/internal/service/relay/config_sync.go
@@ -18,16 +18,13 @@ import (
"path"
"regexp"
"strings"
+ "time"
)
var (
- postfixConfigDir = public.AbsPath("../conf/postfix")
-
- senderRelayFile = "/conf/sender_relay"
- saslPasswdFile = "/conf/sasl_passwd"
- senderTransportFile = "/conf/sender_transport_relay"
- mainCfFile = "main.cf"
- //mainCfFileExtra = "/conf/extra.cf"
+ postfixConfigDir = public.AbsPath("../conf/postfix")
+ saslPasswdFile = "/conf/sasl_passwd"
+ mainCfFile = "main.cf"
postfixContainerName = consts.SERVICES.Postfix
)
@@ -211,108 +208,88 @@ func GenerateSPFRecord(ip string, host string, domain string) string {
return strings.Join(newSpfParts, " ")
}
-// SyncRelayConfigsToPostfix
-func SyncRelayConfigsToPostfix(ctx context.Context) error {
- // 1. Retrieve all active relay configurations
- var activeConfigs []*entity.BmRelay
- err := g.DB().Model("bm_relay").Where("active", 1).Scan(&activeConfigs)
- if err != nil {
- //g.Log().Errorf(ctx, "Failed to query active relay configurations: %v", err)
- return gerror.Wrap(err, "Failed to query relay configurations")
+// 检查中继服务首次同步
+func CheckRelayFirstSync(ctx context.Context) {
+
+ markPath := public.AbsPath("../core/data/SMTP_relay_sync_config_mark.pl")
+ if gfile.Exists(markPath) {
+ return
}
- // Check the total number of configurations (including inactive ones)
- totalCount, err := g.DB().Model("bm_relay").Count()
+ //// 先删除main.cf中的中继配置块 确保旧的配置被清除
+ //beginMarker := "# BEGIN RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"
+ //endMarker := "# END RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"
+ //mainCfPath := path.Join(postfixConfigDir, "main.cf")
+
+ // 不存在,执行同步方法SyncRelayConfigsToPostfix 并创建标记
+ err := SyncRelayConfigsToPostfix(ctx)
if err != nil {
- //g.Log().Errorf(ctx, "Failed to query total relay configuration count: %v", err)
- return gerror.Wrap(err, "Failed to query total relay configuration count")
+ g.Log().Errorf(ctx, "首次同步中继配置失败: %v", err)
+ return
}
- // 2. Generate configuration files
- if err := generateRelayConfigFiles(ctx, activeConfigs); err != nil {
- return err
- }
- // 3. Update master.cf
- if err := updatePostfixMasterCf(ctx, activeConfigs); err != nil {
- return err
- }
- // 4. Update markers in main.cf and extra.cf; if no configurations exist, disable relay functionality
- mainCfPath := path.Join(postfixConfigDir, mainCfFile)
- if err := ensurePostfixRelayConfig(mainCfPath, totalCount > 0); err != nil {
- return err
+
+ if err := gfile.PutContents(markPath, fmt.Sprintf("First sync completed at %s", time.Now().Format("2006-01-02 15:04:05"))); err != nil {
+ g.Log().Warningf(ctx, "创建同步标记文件失败: %v", err)
}
- // 5. Execute Postfix commands
- return reloadPostfixConfigs(ctx)
+ return
}
-// generateRelayConfigFiles Generates relay configuration files
-func generateRelayConfigFiles(ctx context.Context, configs []*entity.BmRelay) error {
- // Ensure the configuration directory exists
- senderRelayPath := path.Join(postfixConfigDir, senderRelayFile)
- saslPasswdPath := path.Join(postfixConfigDir, saslPasswdFile)
- senderTransportPath := path.Join(postfixConfigDir, senderTransportFile)
+// SyncRelayConfigsToPostfix
+func SyncRelayConfigsToPostfix(ctx context.Context) error {
- if !gfile.Exists(postfixConfigDir) {
- return gerror.New("Postfix configuration directory does not exist : " + postfixConfigDir)
+ activeConfigCount, err := g.DB().Model("bm_relay_config").Where("active", 1).Count()
+ if err != nil {
+ return gerror.Wrap(err, "Failed to query active relay configurations count")
}
- // Generate configuration file content
- var senderRelayContent strings.Builder
- var saslPasswdContent strings.Builder
- var senderTransportContent strings.Builder
- if len(configs) == 0 {
- senderRelayContent.WriteString("# No active relay configurations\n")
- saslPasswdContent.WriteString("# No active relay configurations\n")
- senderTransportContent.WriteString("# No active relay configurations\n")
- } else {
- for _, config := range configs {
- // Process sender_relay content
- // Ensure SenderDomain starts with @
- senderDomain := config.SenderDomain
- if !strings.HasPrefix(senderDomain, "@") {
- senderDomain = "@" + senderDomain
- }
- senderRelayContent.WriteString(fmt.Sprintf("%s [%s]:%s\n",
- senderDomain, config.RelayHost, config.RelayPort))
- // Process sasl_passwd content
- // Decrypt password
- decryptedPass, err := DecryptPassword(ctx, config.AuthPassword)
- if err != nil {
- g.Log().Warningf(ctx, "Decryption of password for configuration ID %d failed, skipping this configuration: %v", config.Id, err)
- continue
- }
+ activeMappingCount, err := g.DB().Model("bm_relay_domain_mapping").Count()
+ if err != nil {
+ return gerror.Wrap(err, "Failed to query active relay domain mappings count")
+ }
- saslPasswdContent.WriteString(fmt.Sprintf("[%s]:%s %s:%s\n",
- config.RelayHost, config.RelayPort, config.AuthUser, decryptedPass))
- // Create sender_transport configuration
- smtpName := "smtp_default"
- if config.SmtpName != "" {
+ isActiveRelaySystem := activeConfigCount > 0 && activeMappingCount > 0
+ g.Log().Infof(ctx, "Relay system status: Active config count=%d, Active domain mapping count=%d, System enabled=%v",
+ activeConfigCount, activeMappingCount, isActiveRelaySystem)
- cleanedSmtpName := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.SmtpName, "_")
- smtpName = fmt.Sprintf("smtp_%s", cleanedSmtpName)
- }
+ var activeConfigs []*entity.BmRelayConfig
+ if isActiveRelaySystem {
+ err = g.DB().Model("bm_relay_config").Where("active", 1).Scan(&activeConfigs)
+ if err != nil {
+
+ return gerror.Wrap(err, "Failed to query active relay configurations")
+ }
- senderTransportContent.WriteString(fmt.Sprintf("%s %s:[%s]:%s\n",
- strings.TrimPrefix(senderDomain, "@"), smtpName, config.RelayHost, config.RelayPort))
+ // Update SMTP service name mapping
+ if err := updateSmtpServiceMappings(ctx, activeConfigs); err != nil {
+
+ return err
}
+
+ } else {
+
+ activeConfigs = []*entity.BmRelayConfig{}
+ g.Log().Info(ctx, "No active relay to domain mappings, relay functionality will be disabled")
}
- // 写入配置文件
- if err := gfile.PutContents(senderRelayPath, senderRelayContent.String()); err != nil {
- return gerror.Newf("Failed to write sender_relay file: %v", err)
+ // 1. Generate configuration files-pwd
+ if err := generateRelayPwdFiles(ctx, activeConfigs); err != nil {
+ return err
}
- if err := gfile.PutContents(saslPasswdPath, saslPasswdContent.String()); err != nil {
- return gerror.Newf("Failed to write sasl_passwd file: %v", err)
+ // 2. update master.cf
+ if err := updatePostfixMasterCf(ctx, activeConfigs); err != nil {
+ return err
}
- if err := gfile.PutContents(senderTransportPath, senderTransportContent.String()); err != nil {
- return gerror.Newf("Failed to write sender_transport file: %v", err)
+ // 3. Check whether to enable relay functionality and update pgsql query file
+ if err := ensurePostfixRelayConfig(path.Join(postfixConfigDir, mainCfFile), isActiveRelaySystem); err != nil {
+ return err
}
- return nil
+ return reloadPostfixConfigs(ctx)
}
// updatePostfixMasterCf Updates the Postfix master configuration file
-func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelay) error {
+func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelayConfig) error {
masterCfPath := path.Join(postfixConfigDir, "master.cf")
if !gfile.Exists(masterCfPath) {
g.Log().Warning(ctx, "master.cf file not found, skipping configuration update")
@@ -322,6 +299,19 @@ func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelay) error
// Read existing content
masterContent := gfile.GetContents(masterCfPath)
+ // Define the smtps configuration to add
+ smtpsConfig := `smtps unix - - n - - smtp
+ -o smtp_tls_wrappermode=yes
+ -o smtp_tls_security_level=encrypt`
+
+ // Check if smtps service definition already exists
+ smtpsExistsRegex := regexp.MustCompile(`(?m)^\s*smtps\s+unix\s+`)
+ if !smtpsExistsRegex.MatchString(masterContent) {
+ g.Log().Info(ctx, "Adding missing smtps configuration to master.cf")
+ // Safely insert using line-by-line parsing
+ masterContent = insertSmtpsConfigSafely(masterContent, smtpsConfig)
+ }
+
beginMarker := "# BEGIN BILLIONMAIL RELAY CONFIG - DO NOT EDIT THIS MARKER"
endMarker := "# END BILLIONMAIL RELAY CONFIG - DO NOT EDIT THIS MARKER"
@@ -331,54 +321,29 @@ func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelay) error
// If there are active configurations, create service lines for each configuration
if len(configs) > 0 {
for _, config := range configs {
- // Generate SMTP service name
- smtpName := "smtp"
- if config.SmtpName != "" {
-
- cleanedSmtpName := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.SmtpName, "_")
- smtpName = fmt.Sprintf("smtp_%s", cleanedSmtpName)
- } else {
- // Generate a unique name based on the domain
- domain := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.SenderDomain, "_")
- smtpName = fmt.Sprintf("smtp_%s", domain)
- }
+ smtpName := generateSmtpServiceName(config)
// Configure HELO name
heloName := config.HeloName
- if heloName == "" {
- heloName = config.Host
- if heloName == "" {
- heloName = config.SenderDomain
- }
- }
-
serviceLine := fmt.Sprintf("%s unix - - n - - smtp", smtpName)
-
var params []string
-
if heloName != "" {
params = append(params, fmt.Sprintf("-o smtp_helo_name=%s", heloName))
}
- // TLS parameters - configure based on settings
- if config.TlsProtocol != "" {
- switch config.TlsProtocol {
- case "STARTTLS":
- params = append(params, "-o smtp_use_tls=yes")
- params = append(params, "-o smtp_tls_security_level=may")
- case "SSL/TLS":
- params = append(params, "-o smtp_use_tls=yes")
- params = append(params, "-o smtp_tls_wrappermode=yes")
- case "NONE":
- params = append(params, "-o smtp_use_tls=no")
- }
- } else {
-
- params = append(params, "-o smtp_use_tls=yes")
- params = append(params, "-o smtp_tls_security_level=may")
+ // Add corresponding TLS settings for different ports
+ if config.RelayPort == "465" {
+ params = append(params, "-o smtp_tls_wrappermode=yes")
+ params = append(params, "-o smtp_tls_security_level=encrypt")
+ } else if config.RelayPort == "587" {
+ params = append(params, "-o smtp_tls_security_level=encrypt")
+ params = append(params, "-o smtp_tls_wrappermode=no")
+ } else if config.RelayPort == "25" {
+ params = append(params, "-o smtp_tls_wrappermode=no")
+ params = append(params, "-o smtp_tls_security_level=none")
+ //params = append(params, "-o smtp_tls_security_level=may")
}
- // TLS
if config.SkipTlsVerify == 1 {
params = append(params, "-o smtp_tls_verify_cert_match=no")
}
@@ -397,36 +362,13 @@ func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelay) error
}
}
- // Connection and concurrency settings
- maxConcurrency := 10
- if config.MaxConcurrency > 0 {
- maxConcurrency = config.MaxConcurrency
- params = append(params, fmt.Sprintf("-o smtp_destination_concurrency_limit=%d", maxConcurrency))
- }
-
- //maxRetries := 2
- //if config.MaxRetries > 0 {
- // maxRetries = config.MaxRetries
- //
- //}
-
- if config.MaxWaitTime != "" {
- params = append(params, fmt.Sprintf("-o smtp_connect_timeout=%s", config.MaxWaitTime))
- }
-
- if config.MaxIdleTime != "" {
- params = append(params, fmt.Sprintf("-o smtp_connection_cache_time_limit=%s", config.MaxIdleTime))
- }
-
if len(params) > 0 {
-
serviceLine += "\n " + strings.Join(params, "\n ")
}
customConfigBlock.WriteString(serviceLine + "\n")
}
} else {
-
customConfigBlock.WriteString("# No active relay configurations\n")
}
@@ -440,8 +382,12 @@ func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelay) error
if hasConfigBlock {
blockEnd := endIndex + len(endMarker)
- if blockEnd < len(masterContent) && masterContent[blockEnd] == '\n' {
+ if blockEnd < len(masterContent) && (masterContent[blockEnd] == '\n' || masterContent[blockEnd] == '\r') {
blockEnd++
+ // 处理 \r\n
+ if blockEnd < len(masterContent) && masterContent[blockEnd] == '\n' {
+ blockEnd++
+ }
}
newContent = masterContent[:beginIndex] + customConfigBlock.String()
if blockEnd < len(masterContent) {
@@ -462,7 +408,42 @@ func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelay) error
return nil
}
-// reloadPostfixConfigs Reloads Postfix configurations
+func generateRelayPwdFiles(ctx context.Context, configs []*entity.BmRelayConfig) error {
+ // Ensure the configuration directory exists
+ saslPasswdPath := path.Join(postfixConfigDir, saslPasswdFile)
+
+ if !gfile.Exists(postfixConfigDir) {
+ return gerror.New("Postfix configuration directory does not exist : " + postfixConfigDir)
+ }
+
+ var saslPasswdContent strings.Builder
+
+ if len(configs) == 0 {
+
+ saslPasswdContent.WriteString("# No active relay configurations\n")
+
+ } else {
+ for _, config := range configs {
+ // Decrypt password
+ decryptedPass, err := DecryptPassword(ctx, config.AuthPassword)
+ if err != nil {
+ g.Log().Warningf(ctx, "Decryption of password for configuration ID %d failed, skipping this configuration: %v", config.Id, err)
+ continue
+ }
+
+ saslPasswdContent.WriteString(fmt.Sprintf("[%s]:%s %s:%s\n",
+ config.RelayHost, config.RelayPort, config.AuthUser, decryptedPass))
+
+ }
+ }
+
+ if err := gfile.PutContents(saslPasswdPath, saslPasswdContent.String()); err != nil {
+ return gerror.Newf("Failed to write sasl_passwd file: %v", err)
+ }
+
+ return nil
+}
+
func reloadPostfixConfigs(ctx context.Context) error {
// Connect to the Docker API
dk, err := docker.NewDockerAPI()
@@ -473,9 +454,7 @@ func reloadPostfixConfigs(ctx context.Context) error {
defer dk.Close()
// List of commands to run
cmdsToRun := [][]string{
- {"postmap", "/etc/postfix/conf/sender_relay"},
{"postmap", "/etc/postfix/conf/sasl_passwd"},
- {"postmap", "/etc/postfix/conf/sender_transport_relay"},
{"postfix", "reload"},
}
// Execute commands
@@ -507,18 +486,76 @@ func reloadPostfixConfigs(ctx context.Context) error {
// ensurePostfixRelayConfig
func ensurePostfixRelayConfig(mainCfPath string, enableRelay bool) error {
- // main.cf
+
+ sqlConfigDir := path.Join(postfixConfigDir, "sql")
+ if !gfile.Exists(sqlConfigDir) {
+ if err := gfile.Mkdir(sqlConfigDir); err != nil {
+ return gerror.Newf("Failed to create PostgreSQL configuration directory: %v", err)
+ }
+ g.Log().Info(context.Background(), "Created PostgreSQL configuration directory:", sqlConfigDir)
+ }
+
+ if err := createPostfixSqlConfigFile(); err != nil {
+ return gerror.Newf("Failed to create SQL configuration files: %v", err)
+ }
+
+ // 3. update main.cf
if err := writePostfixRelayConfig(mainCfPath, enableRelay); err != nil {
return err
}
- //// extra.cf
- //extraCfPath := path.Join(postfixConfigDir, mainCfFileExtra)
- //return writePostfixRelayConfig(extraCfPath, enableRelay)
return nil
}
-// writePostfixRelayConfig
+// createPostfixSqlConfigFile
+func createPostfixSqlConfigFile() error {
+
+ sqlConfigFiles := map[string]string{
+ "pgsql_sender_relay_maps.cf": `user = billionmail
+password = 5khrHLc9zxTHZPJzxWkpe2ZQpTGHgH7q
+hosts = pgsql
+dbname = billionmail
+
+query = SELECT CONCAT('[', rc.relay_host, ']:', rc.relay_port) FROM bm_relay_config rc JOIN bm_relay_domain_mapping rdm ON rc.id = rdm.relay_id WHERE rdm.sender_domain = REPLACE('%s', '@', '') AND rc.active = 1 LIMIT 1`,
+
+ "pgsql_sasl_password_maps.cf": `user = billionmail
+password = 5khrHLc9zxTHZPJzxWkpe2ZQpTGHgH7q
+hosts = pgsql
+dbname = billionmail
+
+query = SELECT CONCAT(rc.auth_user, ':', rc.auth_password) FROM bm_relay_config rc WHERE CONCAT('[', rc.relay_host, ']:', rc.relay_port) = '%s' AND rc.active = 1 LIMIT 1`,
+
+ "pgsql_sender_transport_maps.cf": `user = billionmail
+password = 5khrHLc9zxTHZPJzxWkpe2ZQpTGHgH7q
+hosts = pgsql
+dbname = billionmail
+
+query = SELECT CONCAT(relay_type, ':') FROM bm_relay_domain_transport WHERE domain = '%s' LIMIT 1`,
+ }
+
+ sqlDir := path.Join(postfixConfigDir, "sql")
+ if !gfile.Exists(sqlDir) {
+ if err := gfile.Mkdir(sqlDir); err != nil {
+ return gerror.Newf("Failed to create SQL directory: %v", err)
+ }
+ g.Log().Info(context.Background(), "Created SQL directory:", sqlDir)
+ }
+
+ for fileName, fileContent := range sqlConfigFiles {
+ filePath := path.Join(sqlDir, fileName)
+ if !gfile.Exists(filePath) {
+ if err := gfile.PutContents(filePath, fileContent); err != nil {
+ return gerror.Newf("Failed to create SQL configuration file %s: %v", fileName, err)
+ }
+ g.Log().Infof(context.Background(), "Created SQL configuration file: %s", filePath)
+ } else {
+ g.Log().Debugf(context.Background(), "SQL configuration file already exists: %s", filePath)
+ }
+ }
+
+ return nil
+}
+
func writePostfixRelayConfig(cfPath string, enableRelay bool) error {
if !gfile.Exists(cfPath) {
@@ -532,12 +569,15 @@ func writePostfixRelayConfig(cfPath string, enableRelay bool) error {
beginMarker := "# BEGIN RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"
endMarker := "# END RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"
- configBlock := fmt.Sprintf(`%s
+ var configBlock string
+
+ configBlock = fmt.Sprintf(`%s
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
-sender_dependent_relayhost_maps = hash:/etc/postfix/conf/sender_relay
+sender_dependent_relayhost_maps = pgsql:/etc/postfix/sql/pgsql_sender_relay_maps.cf
+# smtp_sasl_password_maps = pgsql:/etc/postfix/sql/pgsql_sasl_password_maps.cf
smtp_sasl_password_maps = hash:/etc/postfix/conf/sasl_passwd
-sender_dependent_default_transport_maps = hash:/etc/postfix/conf/sender_transport_relay
+sender_dependent_default_transport_maps = pgsql:/etc/postfix/sql/pgsql_sender_transport_maps.cf
smtp_sasl_mechanism_filter = login, plain, cram-md5
%s`, beginMarker, endMarker)
@@ -590,3 +630,157 @@ smtp_sasl_mechanism_filter = login, plain, cram-md5
return nil
}
+
+// updateSmtpServiceMappings updates the SMTP service name mapping table
+func updateSmtpServiceMappings(ctx context.Context, configs []*entity.BmRelayConfig) error {
+ // Query active configuration and domain mappings
+ type RelayDomainMapping struct {
+ RelayId int64 `json:"relay_id"`
+ SenderDomain string `json:"sender_domain"`
+ }
+
+ var mappings []RelayDomainMapping
+ err := g.DB().Model("bm_relay_domain_mapping").
+ Fields("relay_id, sender_domain").
+ Scan(&mappings)
+
+ if err != nil {
+ return gerror.Wrap(err, "failed to query relay domain mappings")
+ }
+
+ if len(mappings) == 0 {
+ g.Log().Info(ctx, "No domain mappings, skip updating SMTP service name mappings")
+ return nil
+ }
+
+ // Build map from relay_id to config for lookup
+ configMap := make(map[int64]*entity.BmRelayConfig)
+ for _, config := range configs {
+ configMap[int64(config.Id)] = config
+ }
+
+ // Clear existing mapping table (avoid stale data)
+ _, err = g.DB().Model("bm_relay_domain_transport").Where("1=1").Delete()
+ if err != nil {
+ return gerror.Wrap(err, "failed to clear SMTP service name mapping table")
+ }
+
+ // Batch insert new mappings
+ var transportMappings []g.Map
+
+ for _, mapping := range mappings {
+ config, exists := configMap[mapping.RelayId]
+ if !exists || config.Active != 1 {
+ continue // Skip inactive configs
+ }
+
+ // Generate SMTP service name
+ smtpName := generateSmtpServiceName(config)
+
+ // Ensure domain starts with @
+ senderDomain := mapping.SenderDomain
+ if !strings.HasPrefix(senderDomain, "@") {
+ senderDomain = "@" + senderDomain
+ }
+
+ // Add to batch insert list
+ transportMappings = append(transportMappings, g.Map{
+ "domain": senderDomain,
+ "relay_type": smtpName,
+ })
+ }
+
+ if len(transportMappings) == 0 {
+ g.Log().Info(ctx, "No valid SMTP service name mappings to update")
+ return nil
+ }
+
+ // Batch insert new mappings
+ _, err = g.DB().Model("bm_relay_domain_transport").
+ Data(transportMappings).
+ Batch(100).
+ Insert()
+
+ if err != nil {
+ return gerror.Wrap(err, "failed to batch insert SMTP service name mappings")
+ }
+
+ g.Log().Infof(ctx, "Updated %d SMTP service name mappings", len(transportMappings))
+ return nil
+}
+
+// generateSmtpServiceName generates SMTP service name based on relay configuration
+func generateSmtpServiceName(config *entity.BmRelayConfig) string {
+ if config.SmtpName != "Custom SMTP Relay" {
+ // Prefer user-defined SMTP name
+ cleanedSmtpName := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.SmtpName, "_")
+ return fmt.Sprintf("smtp_Custom_%s", cleanedSmtpName)
+ }
+
+ // Extract relay_host as base name
+ relayDomain := config.RelayHost
+ cleanedRelayDomain := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(relayDomain, "_")
+
+ // Extract username part from auth_user if exists
+ userName := ""
+ if config.AuthUser != "" {
+ // Handle cases with and without @ symbol
+ if strings.Contains(config.AuthUser, "@") {
+ parts := strings.Split(config.AuthUser, "@")
+ userName = regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(parts[0], "_")
+ } else {
+ // If no @ symbol, use first 5 characters (if available)
+ authUserLen := len(config.AuthUser)
+ if authUserLen > 5 {
+ userName = regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.AuthUser[:5], "_")
+ } else {
+ userName = regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.AuthUser, "_")
+ }
+ }
+ }
+
+ // Combine SMTP service name
+ if userName != "" {
+ return fmt.Sprintf("smtp_Relay_%s_%s_%d", cleanedRelayDomain, userName, config.Id)
+ }
+
+ return fmt.Sprintf("smtp_Relay_%s_%d", cleanedRelayDomain, config.Id)
+}
+
+func insertSmtpsConfigSafely(content, smtpsConfig string) string {
+ lines := strings.Split(content, "\n")
+ var result []string
+ inserted := false
+ inServiceBlock := false
+
+ for i, line := range lines {
+ trimmed := strings.TrimSpace(line)
+
+ if trimmed == "" || strings.HasPrefix(trimmed, "#") {
+ result = append(result, line)
+ continue
+ }
+
+ // Match service definition: service_name inet/unix ...
+ isServiceDef := regexp.MustCompile(`^\s*[\w-]+\s+(inet|unix)\s+`).MatchString(trimmed)
+
+ if isServiceDef && !inserted {
+ // Insert smtps before the first service definition
+ if i == 0 || !inServiceBlock {
+ result = append(result, smtpsConfig)
+ result = append(result, "")
+ inserted = true
+ }
+ }
+
+ result = append(result, line)
+ inServiceBlock = true
+ }
+
+ if !inserted {
+ result = append(result, "")
+ result = append(result, smtpsConfig)
+ }
+
+ return strings.Join(result, "\n")
+}
diff --git a/core/internal/service/timers/timers.go b/core/internal/service/timers/timers.go
index 855de4aa..84ae6dc1 100644
--- a/core/internal/service/timers/timers.go
+++ b/core/internal/service/timers/timers.go
@@ -141,6 +141,11 @@ func Start(ctx context.Context) (err error) {
batch_mail.UpdateTaskJoinMailstat(ctx)
})
+ // First sync of SMTP relay configurations to Postfix after refactoring
+ gtimer.AddOnce(30*time.Second, func() {
+ relay.CheckRelayFirstSync(ctx)
+ })
+
g.Log().Debug(ctx, "All timers started successfully")
return nil
}