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

Add relay services

lotk0b782e7e2d88
diff --git a/core/api/relay/relay.go b/core/api/relay/relay.go
new file mode 100644
index 00000000..57b352b5
--- /dev/null
+++ b/core/api/relay/relay.go
@@ -0,0 +1,18 @@
+// =================================================================================
+// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
+// =================================================================================
+
+package relay
+
+import (
+ "context"
+
+ "billionmail-core/api/relay/v1"
+)
+
+type IRelayV1 interface {
+ CreateRelayConfig(ctx context.Context, req *v1.CreateRelayConfigReq) (res *v1.CreateRelayConfigRes, err error)
+ ListRelayConfigs(ctx context.Context, req *v1.ListRelayConfigsReq) (res *v1.ListRelayConfigsRes, err error)
+ UpdateRelayConfig(ctx context.Context, req *v1.UpdateRelayConfigReq) (res *v1.UpdateRelayConfigRes, err error)
+ DeleteRelayConfig(ctx context.Context, req *v1.DeleteRelayConfigReq) (res *v1.DeleteRelayConfigRes, err error)
+}
diff --git a/core/api/relay/v1/relay.go b/core/api/relay/v1/relay.go
new file mode 100644
index 00000000..25cb6e9c
--- /dev/null
+++ b/core/api/relay/v1/relay.go
@@ -0,0 +1,102 @@
+package v1
+
+import (
+ "billionmail-core/utility/types/api_v1"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+// BmRelay
+type BmRelay struct {
+ Id int `json:"id"`
+ Remark string `json:"remark"` // Remark, e.g., "AWS SES Japan Region"
+ 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) +ip4:23.158.104.237
+ Host string `json:"host"` // Host for reminding users to update SPF record (optional) include:lootk.cn
+ 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
+}
+
+type DNSRecord struct {
+ Type string `json:"type"`
+ Host string `json:"host"`
+ Value string `json:"value"`
+}
+type BmRelayWithSPF struct {
+ *BmRelay
+ SPFRecord DNSRecord `json:"spf_record"`
+}
+
+// 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"`
+ 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)"`
+}
+
+type CreateRelayConfigRes struct {
+ api_v1.StandardRes
+ SPFRecord DNSRecord `json:"spf_record"` // Generated SPF record suggestion
+}
+
+// ListRelayConfigsReq Request to get a list of relay configurations
+type ListRelayConfigsReq struct {
+ g.Meta `path:"/relay/list" method:"get" tags:"Relay Configs" summary:"Get the list of relay configurations"`
+ Authorization string `json:"authorization" in:"header" dc:"Authorization" v:"required"`
+ //Active int `json:"active,omitempty" v:"in:0,1" dc:"Filter by status: 1-enabled, 0-disabled"`
+ Page int `json:"page" v:"required|min:1" dc:"Page number"`
+ PageSize int `json:"page_size" v:"required|min:1" dc:"Page size"`
+ Keyword string `json:"keyword" dc:"search"` // Search by remark, relay server address, or sender domain
+}
+
+type ListRelayConfigsRes struct {
+ api_v1.StandardRes
+ Data struct {
+ Total int `json:"total" dc:"Total records count"`
+ List []*BmRelayWithSPF `json:"list" dc:"Relay configuration list"`
+ } `json:"data"`
+}
+
+// UpdateRelayConfigReq Request to update a relay configuration
+type UpdateRelayConfigReq struct {
+ g.Meta `path:"/relay/edit" method:"post" tags:"Relay Configs" summary:"Update a relay configuration"`
+ Authorization string `json:"authorization" in:"header" dc:"Authorization" v:"required"`
+ ID int `json:"id" v:"required|min:1" dc:"The ID of the configuration to update"`
+ 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
+}
+
+type UpdateRelayConfigRes struct {
+ api_v1.StandardRes
+ SPFRecord DNSRecord `json:"spf_record"`
+}
+
+// DeleteRelayConfigReq Request to delete a relay configuration
+type DeleteRelayConfigReq struct {
+ g.Meta `path:"/relay/delete" method:"post" tags:"Relay Configs" summary:"Delete a relay configuration"`
+ Authorization string `json:"authorization" in:"header" dc:"Authorization" v:"required"`
+ ID int64 `json:"id" v:"required|min:1" dc:"The ID of the configuration to delete"`
+}
+
+type DeleteRelayConfigRes struct {
+ api_v1.StandardRes
+}
diff --git a/core/internal/cmd/cmd.go b/core/internal/cmd/cmd.go
index 1d929528..ad3407e2 100644
--- a/core/internal/cmd/cmd.go
+++ b/core/internal/cmd/cmd.go
@@ -14,6 +14,7 @@ import (
"billionmail-core/internal/controller/mail_services"
"billionmail-core/internal/controller/overview"
"billionmail-core/internal/controller/rbac"
+ "billionmail-core/internal/controller/relay"
"billionmail-core/internal/service/database_initialization"
docker "billionmail-core/internal/service/dockerapi"
"billionmail-core/internal/service/maillog_stat"
@@ -184,6 +185,7 @@ var (
abnormal_recipient.NewV1(),
languages.NewV1(),
mail_services.NewV1(),
+ relay.NewV1(),
)
})
diff --git a/core/internal/controller/relay/relay.go b/core/internal/controller/relay/relay.go
new file mode 100644
index 00000000..6e6b4068
--- /dev/null
+++ b/core/internal/controller/relay/relay.go
@@ -0,0 +1,386 @@
+// =================================================================================
+// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
+// =================================================================================
+
+package relay
+
+import (
+ domainsV1 "billionmail-core/api/domains/v1"
+ "billionmail-core/internal/model/entity"
+ docker "billionmail-core/internal/service/dockerapi"
+ "billionmail-core/internal/service/domains"
+ "billionmail-core/internal/service/public"
+ "context"
+ "crypto/rand"
+ "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/gfile"
+ "path"
+ "strings"
+)
+
+const (
+ // Postfix-related configuration paths
+ postfixConfigDir = "/opt/Billion-Mail/conf/postfix"
+ senderRelayFile = "/conf/sender_relay"
+ saslPasswdFile = "/conf/sasl_passwd"
+ mainCfFile = "main.cf"
+ postfixContainerName = "billionmail-postfix-billionmail-1"
+)
+
+func GetRelayEncryptionKey() (string, error) {
+ // 1. Retrieve key from the database
+ val, err := g.DB().Model("bm_options").
+ Where("name", "relay_encryption_key").
+ Value("value")
+
+ if val != nil && val.String() != "" {
+ return val.String(), nil
+ }
+
+ // 2. Generate key
+ newSecret, err := generateRandomKey(16)
+ if err != nil {
+ return "", gerror.Wrap(err, "Failed to generate new relay encryption key")
+ }
+
+ // 3. Save the new key to the database
+ _, err = g.DB().Model("bm_options").
+ Data(g.Map{
+ "name": "relay_encryption_key",
+ "value": newSecret,
+ }).
+ Insert()
+ if err != nil {
+ // If insert fails, attempt to retrieve the key again
+ val, err = g.DB().Model("bm_options").
+ Where("name", "relay_encryption_key").
+ Value("value")
+
+ if val != nil && val.String() != "" {
+ return val.String(), nil
+ }
+ return "", gerror.New("Failed to insert new key and retrieve key again")
+ }
+
+ return newSecret, nil
+}
+
+// generateRandomKey generates a random key of the specified length.
+func generateRandomKey(length int) (string, error) {
+ key := make([]byte, length)
+ _, err := rand.Read(key)
+ if err != nil {
+ return "", err
+ }
+
+ return hex.EncodeToString(key), nil
+}
+
+func EncryptPassword(ctx context.Context, plainText string) (string, error) {
+ if plainText == "" {
+ return "", gerror.New(public.LangCtx(ctx, "Password cannot be empty"))
+ }
+ relayEncryptionKey, err := GetRelayEncryptionKey()
+ if err != nil {
+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to retrieve encryption key"))
+ }
+
+ keyBytes, err := hex.DecodeString(relayEncryptionKey)
+ if err != nil {
+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to parse encryption key"))
+ }
+
+ if len(keyBytes) < 16 {
+ return "", gerror.New(public.LangCtx(ctx, "Encryption key length is insufficient"))
+ }
+ keyBytes = keyBytes[:16]
+
+ encrypted, err := gaes.Encrypt([]byte(plainText), keyBytes)
+ if err != nil {
+ g.Log().Errorf(ctx, "Password encryption failed: %v", err)
+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Password encryption failed"))
+ }
+
+ return hex.EncodeToString(encrypted), nil
+}
+
+func DecryptPassword(ctx context.Context, encryptedHex string) (string, error) {
+ if encryptedHex == "" {
+ return "", nil
+ }
+
+ encryptedBytes, err := hex.DecodeString(encryptedHex)
+ if err != nil {
+ g.Log().Errorf(ctx, "Decryption failed, invalid hex format: %v", err)
+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Password format is incorrect"))
+ }
+
+ relayEncryptionKey, err := GetRelayEncryptionKey()
+ if err != nil {
+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to retrieve encryption key"))
+ }
+
+ keyBytes, err := hex.DecodeString(relayEncryptionKey)
+ if err != nil {
+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to parse encryption key"))
+ }
+
+ if len(keyBytes) < 16 {
+ return "", gerror.New(public.LangCtx(ctx, "Encryption key length is insufficient"))
+ }
+ keyBytes = keyBytes[:16]
+
+ decrypted, err := gaes.Decrypt(encryptedBytes, keyBytes)
+ if err != nil {
+ g.Log().Errorf(ctx, "Password decryption failed: %v", err)
+ return "", gerror.Wrap(err, public.LangCtx(ctx, "Password decryption failed"))
+ }
+
+ return string(decrypted), nil
+}
+
+func buildCacheKey(domain, recordType string) string {
+ return fmt.Sprintf("DOMAIN_DNS_RECORDS_:%s:_%s", domain, recordType)
+}
+
+// GenerateSPFRecord generates SPF record hints based on IP and host.
+func GenerateSPFRecord(ip string, host string, domain string) string {
+ // Retrieve the current SPF record for the domain
+ var existingValue string
+ var newSpfParts []string
+
+ // Fetch SPF record from cache or domains service
+ spfRecord := public.GetCache(buildCacheKey(domain, "SPF"))
+
+ if spfRecord != nil {
+ if v, ok := spfRecord.(domainsV1.DNSRecord); ok {
+ existingValue = v.Value
+ }
+ }
+
+ // If cache is empty, attempt to fetch from domains service
+ if existingValue == "" {
+ record, _ := domains.GetSPFRecord(domain, false)
+ existingValue = record.Value
+ }
+
+ // Create a basic record if none exists
+ if existingValue == "" {
+ existingValue = "v=spf1 +a +mx"
+ }
+
+ // Analyze the existing record to avoid duplications
+ parts := strings.Split(existingValue, " ")
+ existingParts := make(map[string]bool)
+ var allMechanism string
+
+ for _, part := range parts {
+ part = strings.TrimSpace(part)
+ if part == "" {
+ continue
+ }
+ existingParts[part] = true
+ if strings.HasSuffix(part, "all") {
+ allMechanism = part
+ continue
+ }
+ newSpfParts = append(newSpfParts, part)
+ }
+
+ // Add IP if provided and not duplicated
+ if ip != "" {
+ var ipPart string
+ if strings.Contains(ip, ":") {
+ ipPart = fmt.Sprintf("+ip6:%s", ip)
+ } else {
+ ipPart = fmt.Sprintf("+ip4:%s", ip)
+ }
+ if !existingParts[ipPart] {
+ newSpfParts = append(newSpfParts, ipPart)
+ }
+ }
+
+ // Add host if provided and not duplicated
+ if host != "" {
+ var hostPart string
+
+ hostPart = fmt.Sprintf("include:%s", host)
+
+ if !existingParts[hostPart] {
+ newSpfParts = append(newSpfParts, hostPart)
+ }
+ }
+
+ if allMechanism != "" {
+ newSpfParts = append(newSpfParts, allMechanism)
+ } else {
+ newSpfParts = append(newSpfParts, "~all")
+ }
+
+ return strings.Join(newSpfParts, " ")
+}
+
+// SyncRelayConfigsToPostfix
+func SyncRelayConfigsToPostfix(ctx context.Context) error {
+ // 1. Ensure the configuration directory exists
+ senderRelayPath := path.Join(postfixConfigDir, senderRelayFile)
+ saslPasswdPath := path.Join(postfixConfigDir, saslPasswdFile)
+ mainCfPath := path.Join(postfixConfigDir, mainCfFile)
+
+ if !gfile.Exists(postfixConfigDir) {
+ return gerror.Newf(public.LangCtx(ctx, "Postfix configuration directory does not exist : %s", postfixConfigDir))
+ }
+ // 2. Query all enabled relay configurations
+ var activeConfigs []*entity.BmRelay
+ err := g.DB().Model("bm_relay").Where("active", 1).Scan(&activeConfigs)
+ if err != nil {
+ return gerror.Wrap(err, public.LangCtx(ctx, "Failed to query relay configurations"))
+ }
+ // 3. Generate sender_relay file content
+ var senderRelayContent strings.Builder
+ var saslPasswdContent strings.Builder
+
+ if len(activeConfigs) == 0 {
+ senderRelayContent.WriteString("# No active relay configurations\n")
+ saslPasswdContent.WriteString("# No active relay configurations\n")
+ } else {
+ for _, config := range activeConfigs {
+ 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
+ decryptedPass, err := DecryptPassword(ctx, config.AuthPassword)
+ if err != nil {
+
+ continue
+ }
+
+ saslPasswdContent.WriteString(fmt.Sprintf("[%s]:%s %s:%s\n",
+ config.RelayHost, config.RelayPort, config.AuthUser, decryptedPass))
+ }
+ }
+ // 4. Write configuration files
+ if err := gfile.PutContents(senderRelayPath, senderRelayContent.String()); err != nil {
+ return gerror.Newf("Failed to write sender_relay file: %v", err)
+ }
+
+ if err := gfile.PutContents(saslPasswdPath, saslPasswdContent.String()); err != nil {
+ return gerror.Newf("Failed to write sasl_passwd file: %v", err)
+ }
+ // 5. Decide whether to enable relay functionality based on active configurations
+ if err := ensurePostfixRelayConfig(mainCfPath, len(activeConfigs) > 0); err != nil {
+ return err
+ }
+ // 6. Execute Postfix commands
+ dk, dockerErr := docker.NewDockerAPI()
+ if dockerErr != nil {
+ g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)
+ return gerror.Wrap(dockerErr, public.LangCtx(ctx, "Failed to connect to Docker service"))
+ }
+ defer dk.Close()
+
+ cmdsToRun := [][]string{
+ {"postmap", "/etc/postfix/conf/sender_relay"},
+ {"postmap", "/etc/postfix/conf/sasl_passwd"},
+ {"postfix", "reload"},
+ }
+
+ for _, cmd := range cmdsToRun {
+ cmdStr := strings.Join(cmd, " ")
+ g.Log().Infof(ctx, "Executing command in container %s: %s", postfixContainerName, cmdStr)
+ result, err := dk.ExecCommandByName(ctx, postfixContainerName, cmd, "root")
+
+ if err != nil {
+ g.Log().Errorf(ctx, "Failed to execute command: %v, Command: %s", err, cmdStr)
+ return gerror.Newf("Failed to execute command: %v, Command: %s", err, cmdStr)
+ }
+
+ if result == nil {
+ g.Log().Errorf(ctx, "Command execution result is empty: %s", cmdStr)
+ return gerror.Newf("Command execution result is empty: %s", cmdStr)
+ }
+
+ if result.ExitCode != 0 {
+ g.Log().Errorf(ctx, "Command execution returned non-zero status: %d, Output: %s, Command: %s",
+ result.ExitCode, result.Output, cmdStr)
+ return gerror.Newf("Command execution failed, Exit code: %d, Output: %s, Command: %s",
+ result.ExitCode, result.Output, cmdStr)
+ }
+ g.Log().Infof(ctx, "Command executed successfully: %s, Output: %s", cmdStr, result.Output)
+ }
+ g.Log().Info(ctx, "Relay configurations synchronized to Postfix successfully")
+ return nil
+}
+
+// ensurePostfixRelayConfig Ensures that the Postfix main.cf configuration file contains necessary relay configurations
+func ensurePostfixRelayConfig(mainCfPath string, enableRelay bool) error {
+ content := gfile.GetContents(mainCfPath)
+ // Define the start and end markers for the configuration block
+ beginMarker := "# BEGIN RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"
+ endMarker := "# END RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"
+
+ // Construct the complete configuration block
+ configBlock := fmt.Sprintf(`%s
+smtp_sasl_auth_enable = yes
+smtp_sasl_security_options = noanonymous
+sender_dependent_relayhost_maps = hash:/etc/postfix/conf/sender_relay
+smtp_sasl_password_maps = hash:/etc/postfix/conf/sasl_passwd
+%s`, beginMarker, endMarker)
+
+ // Find the existing configuration block
+ beginIndex := strings.Index(content, beginMarker)
+ endIndex := strings.Index(content, endMarker)
+
+ // Check if the configuration block exists
+ hasConfigBlock := beginIndex != -1 && endIndex != -1 && beginIndex < endIndex
+
+ // Decide the operation based on whether relay is enabled and if the configuration block exists
+ modified := false
+
+ if enableRelay {
+ if hasConfigBlock {
+ g.Log().Debug(nil, "Relay configuration block already exists, no modification needed")
+ } else {
+ // Need to add the configuration block
+ if strings.HasSuffix(content, "\n") {
+ content = content + configBlock + "\n"
+ } else {
+ content = content + "\n" + configBlock + "\n"
+ }
+ modified = true
+ }
+ } else {
+ if hasConfigBlock {
+ // Need to remove the configuration block
+ blockStart := beginIndex
+ blockEnd := endIndex + len(endMarker)
+
+ if blockEnd < len(content) && content[blockEnd] == '\n' {
+ blockEnd++
+ }
+
+ newContent := content[:blockStart]
+ if blockEnd < len(content) {
+ newContent += content[blockEnd:]
+ }
+ content = newContent
+ modified = true
+ }
+ }
+ // If there are modifications, write to the file
+ if modified {
+ if err := gfile.PutContents(mainCfPath, content); err != nil {
+ return gerror.Newf("Failed to write main.cf file: %v", err)
+ }
+ }
+
+ return nil
+}
diff --git a/core/internal/controller/relay/relay_new.go b/core/internal/controller/relay/relay_new.go
new file mode 100644
index 00000000..f4f3f3af
--- /dev/null
+++ b/core/internal/controller/relay/relay_new.go
@@ -0,0 +1,15 @@
+// =================================================================================
+// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
+// =================================================================================
+
+package relay
+
+import (
+ "billionmail-core/api/relay"
+)
+
+type ControllerV1 struct{}
+
+func NewV1() relay.IRelayV1 {
+ return &ControllerV1{}
+}
diff --git a/core/internal/controller/relay/relay_v1_create_relay_config.go b/core/internal/controller/relay/relay_v1_create_relay_config.go
new file mode 100644
index 00000000..8fe77a83
--- /dev/null
+++ b/core/internal/controller/relay/relay_v1_create_relay_config.go
@@ -0,0 +1,67 @@
+package relay
+
+import (
+ "context"
+
+ "billionmail-core/api/relay/v1"
+ "billionmail-core/internal/service/public"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "time"
+)
+
+// CreateRelayConfig Creates a relay configuration
+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, "Relay configuration for this sender domain already exists: {}", req.SenderDomain)))
+ return res, nil
+ }
+ // Encrypt the password
+ encryptedPass, err := EncryptPassword(ctx, req.AuthPassword)
+ if err != nil {
+ res.SetError(err)
+ return res, nil
+ }
+ // Prepare data
+ now := time.Now().Unix()
+ _, err = g.DB().Model("bm_relay").Insert(g.Map{
+ "remark": req.Remark,
+ "sender_domain": req.SenderDomain,
+ "relay_host": req.RelayHost,
+ "relay_port": req.RelayPort,
+ "auth_user": req.AuthUser,
+ "auth_password": encryptedPass,
+ "ip": req.IP,
+ "host": req.Host,
+ "create_time": now,
+ "update_time": now,
+ "active": req.Active,
+ })
+
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create relay configuration: {}", err.Error())))
+ return res, nil
+ }
+ // Sync configuration to Postfix
+ if err := SyncRelayConfigsToPostfix(ctx); err != nil {
+ // g.Log().Error(ctx, "Failed to sync relay configuration to Postfix:", err)
+ res.SetError(gerror.New(public.LangCtx(ctx, "Created successfully but failed to sync configuration: {}", err.Error())))
+ return res, nil
+ }
+ // Generate SPF record suggestion
+ spfRecord := GenerateSPFRecord(req.IP, req.Host, req.SenderDomain)
+ res.SPFRecord = v1.DNSRecord{
+ Type: "TXT",
+ Host: "@",
+ Value: spfRecord,
+ }
+ 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
new file mode 100644
index 00000000..ffa76acf
--- /dev/null
+++ b/core/internal/controller/relay/relay_v1_delete_relay_config.go
@@ -0,0 +1,36 @@
+package relay
+
+import (
+ "billionmail-core/api/relay/v1"
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+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()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to check relay configuration: {}", err.Error())))
+ return res, nil
+ }
+ if info.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()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to delete relay configuration: {}", err.Error())))
+ return res, nil
+ }
+ // Sync configuration to Postfix
+ if err := SyncRelayConfigsToPostfix(ctx); err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Deleted successfully but failed to sync configuration: {}", err.Error())))
+ return res, nil
+ }
+ res.SetSuccess(public.LangCtx(ctx, "Relay configuration deleted successfully"))
+ return res, nil
+}
diff --git a/core/internal/controller/relay/relay_v1_list_relay_configs.go b/core/internal/controller/relay/relay_v1_list_relay_configs.go
new file mode 100644
index 00000000..89b8de7e
--- /dev/null
+++ b/core/internal/controller/relay/relay_v1_list_relay_configs.go
@@ -0,0 +1,90 @@
+package relay
+
+import (
+ "billionmail-core/api/relay/v1"
+ "billionmail-core/internal/model/entity"
+ "billionmail-core/internal/service/public"
+ "context"
+ "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{}
+
+ model := g.DB().Model("bm_relay").Safe()
+
+ //if req.Active > 0 {
+ // model = model.Where("active", req.Active)
+ //}
+ // 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,
+ )
+ }
+
+ count, err := model.Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to retrieve relay configuration count: {}", err.Error())))
+ return res, nil
+ }
+
+ var list []*entity.BmRelay
+ err = model.Page(req.Page, req.PageSize).Order("create_time DESC").Scan(&list)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to retrieve relay configuration list: {}", err.Error())))
+ return res, nil
+ }
+
+ resultList := make([]*v1.BmRelayWithSPF, 0, len(list))
+ for _, item := range list {
+ // Generate SPF record suggestion
+ spfRecord := GenerateSPFRecord(item.IP, item.Host, item.SenderDomain)
+
+ bmRelay := toPostfixRelayResponse(ctx, item)
+
+ relayWithSPF := &v1.BmRelayWithSPF{
+ BmRelay: bmRelay,
+ SPFRecord: v1.DNSRecord{
+ Type: "TXT",
+ Host: "@",
+ Value: spfRecord,
+ },
+ }
+
+ resultList = append(resultList, relayWithSPF)
+ }
+
+ res.Data.Total = count
+ res.Data.List = resultList
+ res.SetSuccess(public.LangCtx(ctx, "Relay configuration list retrieved successfully"))
+ return res, nil
+}
+
+// toPostfixRelayResponse Converts database entity to API response structure
+func toPostfixRelayResponse(ctx context.Context, relay *entity.BmRelay) *v1.BmRelay {
+ password, _ := DecryptPassword(ctx, relay.AuthPassword)
+ if password == "" {
+ password = "********"
+ }
+ return &v1.BmRelay{
+ Id: relay.Id,
+ Remark: relay.Remark,
+ 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,
+ }
+}
diff --git a/core/internal/controller/relay/relay_v1_update_relay_config.go b/core/internal/controller/relay/relay_v1_update_relay_config.go
new file mode 100644
index 00000000..171ae3b1
--- /dev/null
+++ b/core/internal/controller/relay/relay_v1_update_relay_config.go
@@ -0,0 +1,117 @@
+package relay
+
+import (
+ "billionmail-core/internal/model/entity"
+ "context"
+
+ "billionmail-core/api/relay/v1"
+ "billionmail-core/internal/service/public"
+
+ "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{}
+
+ var relayInfo entity.BmRelay
+ err = g.DB().Model("bm_relay").Where("id", req.ID).Scan(&relayInfo)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to check relay configuration: {}", err.Error())))
+ return res, nil
+ }
+ if relayInfo.Id == 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Relay configuration does not exist")))
+ return res, nil
+ }
+ // Domain updates are not allowed
+ // If the domain is updated, check if the domain is already used by another record
+ //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, "Relay configuration for this sender domain already exists: {}", req.SenderDomain)))
+ // return res, nil
+ // }
+ //}
+
+ updateData := g.Map{
+ "update_time": time.Now().Unix(),
+ }
+ // Update only the provided fields
+ if req.Remark != "" {
+ updateData["remark"] = req.Remark
+ }
+ //if req.SenderDomain != "" {
+ // updateData["sender_domain"] = req.SenderDomain
+ //}
+ if req.RelayHost != "" {
+ updateData["relay_host"] = req.RelayHost
+ }
+ if req.RelayPort != "" {
+ updateData["relay_port"] = req.RelayPort
+ }
+ if req.AuthUser != "" {
+ updateData["auth_user"] = req.AuthUser
+ }
+ // Special handling for password - encrypt and store if a new password is provided
+ if req.AuthPassword != "" && req.AuthPassword != "********" {
+ encryptedPass, err := EncryptPassword(ctx, req.AuthPassword)
+ if err != nil {
+ res.SetError(err)
+ return res, nil
+ }
+ updateData["auth_password"] = encryptedPass
+ }
+ if req.IP != "" {
+ updateData["ip"] = req.IP
+ }
+ if req.Host != "" {
+ updateData["host"] = req.Host
+ }
+ // Active can be updated separately to 0 as a disable operation
+ if req.Active >= 0 {
+ updateData["active"] = req.Active
+ }
+
+ _, err = g.DB().Model("bm_relay").Where("id", req.ID).Update(updateData)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update relay configuration: {}", err.Error())))
+ return res, nil
+ }
+ // Sync configuration to Postfix
+ if err := SyncRelayConfigsToPostfix(ctx); err != nil {
+
+ res.SetError(gerror.New(public.LangCtx(ctx, "Updated successfully but failed to sync configuration: {}", err.Error())))
+ return res, nil
+ }
+ // Retrieve the latest information for generating SPF records
+ var latestRelayInfo entity.BmRelay
+ _ = g.DB().Model("bm_relay").Where("id", req.ID).Scan(&latestRelayInfo)
+
+ spfRecord := GenerateSPFRecord(latestRelayInfo.IP, latestRelayInfo.Host, latestRelayInfo.SenderDomain)
+ res.SPFRecord = v1.DNSRecord{
+ Type: "TXT",
+ Host: "@",
+ Value: spfRecord,
+ }
+
+ if len(updateData) > 2 { // In addition to update_time, other fields have been updated
+ res.SetSuccess(public.LangCtx(ctx, "Relay configuration updated successfully"))
+ } else if req.Active == 1 {
+ res.SetSuccess(public.LangCtx(ctx, "Relay configuration has been enabled"))
+ } else if req.Active == 0 {
+ res.SetSuccess(public.LangCtx(ctx, "Relay configuration has been disabled"))
+ } else {
+ res.SetSuccess(public.LangCtx(ctx, "Relay configuration updated successfully"))
+ }
+
+ return res, nil
+}
diff --git a/core/internal/model/entity/bm_relay.go b/core/internal/model/entity/bm_relay.go
new file mode 100644
index 00000000..580416cf
--- /dev/null
+++ b/core/internal/model/entity/bm_relay.go
@@ -0,0 +1,17 @@
+package entity
+
+// BmBcc
+type BmRelay struct {
+ Id int `json:"id"`
+ Remark string `json:"remark"` // Remark, e.g., "AWS SES Japan Region"
+ 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) +ip4:23.158.104.237
+ Host string `json:"host"` // Host for reminding users to update SPF record (optional) include:lootk.cn
+ 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
+}