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
Postfix Mail Queue Management
lotkea4591c90d61
diff --git a/core/api/mail_services/mail_services.go b/core/api/mail_services/mail_services.goindex 655e06fa..81203751 100644--- a/core/api/mail_services/mail_services.go+++ b/core/api/mail_services/mail_services.go@@ -21,4 +21,12 @@ type IMailServicesV1 interface {AddMailForward(ctx context.Context, req *v1.AddMailForwardReq) (res *v1.AddMailForwardRes, err error)EditMailForward(ctx context.Context, req *v1.EditMailForwardReq) (res *v1.EditMailForwardRes, err error)DeleteMailForward(ctx context.Context, req *v1.DeleteMailForwardReq) (res *v1.DeleteMailForwardRes, err error)+ GetPostfixQueueList(ctx context.Context, req *v1.GetPostfixQueueListReq) (res *v1.GetPostfixQueueListRes, err error)+ GetPostfixQueueInfo(ctx context.Context, req *v1.GetPostfixQueueInfoReq) (res *v1.GetPostfixQueueInfoRes, err error)+ DeletePostfixQueueById(ctx context.Context, req *v1.DeletePostfixQueueByIdReq) (res *v1.DeletePostfixQueueByIdRes, err error)+ DeleteAllDeferredQueue(ctx context.Context, req *v1.DeleteAllDeferredQueueReq) (res *v1.DeleteAllDeferredQueueRes, err error)+ FlushPostfixQueue(ctx context.Context, req *v1.FlushPostfixQueueReq) (res *v1.FlushPostfixQueueRes, err error)+ FlushPostfixQueueById(ctx context.Context, req *v1.FlushPostfixQueueByIdReq) (res *v1.FlushPostfixQueueByIdRes, err error)+ SetPostfixConfig(ctx context.Context, req *v1.SetPostfixConfigReq) (res *v1.SetPostfixConfigRes, err error)+ GetPostfixConfig(ctx context.Context, req *v1.GetPostfixConfigReq) (res *v1.GetPostfixConfigRes, err error)}diff --git a/core/api/mail_services/v1/postfix_queue.go b/core/api/mail_services/v1/postfix_queue.gonew file mode 100644index 00000000..2fb87272--- /dev/null+++ b/core/api/mail_services/v1/postfix_queue.go@@ -0,0 +1,106 @@+package v1++import (+ "billionmail-core/utility/types/api_v1"+ "github.com/gogf/gf/v2/frame/g"+)++type QueueMailItem struct {+ QueueID string `json:"queue_id" dc:"Queue ID"`+ Sender string `json:"sender" dc:"Sender"`+ Recipients []Recipient `json:"recipients" dc:"Recipient list"`+ ArrivalTime int64 `json:"arrival_time" dc:"Arrival timestamp"`+ DelayReason string `json:"delay_reason,omitempty" dc:"Delay reason"`+ MessageSize int `json:"message_size,omitempty" dc:"Message size in bytes"`+ QueueName string `json:"queue_name" dc:"Queue name"`+ ForcedExpire bool `json:"forced_expire" dc:"Forced expire flag"`+ Recipient string `json:"recipient" dc:"Recipient"`+}++type Recipient struct {+ Address string `json:"address" dc:"Recipient address"`+ DelayReason string `json:"delay_reason,omitempty" dc:"Delay reason"`+}++type GetPostfixQueueListReq struct {+ g.Meta `path:"/postfix_queue/list" method:"get" summary:"Get postfix queue list"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ Domain string `json:"domain" desc:"Domain filter"`+}++type GetPostfixQueueListRes struct {+ api_v1.StandardRes+ Data struct {+ List []QueueMailItem `json:"list" dc:"Postfix queue list"`+ Total int `json:"total" dc:"Total count"`+ } `json:"data"`+}++type GetPostfixQueueInfoReq struct {+ g.Meta `path:"/postfix_queue/queue_info" method:"get" summary:"View mail content of specified queue"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ QueueID string `json:"queue_id" v:"required" dc:"Queue ID"`+}++type GetPostfixQueueInfoRes struct {+ api_v1.StandardRes+}++type DeletePostfixQueueByIdReq struct {+ g.Meta `path:"/postfix_queue/delete_by_id" method:"post" summary:"Delete specified queue mail"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ QueueID string `json:"queue_id" v:"required" dc:"Queue ID"`+}++type DeletePostfixQueueByIdRes struct {+ api_v1.StandardRes+}++type DeleteAllDeferredQueueReq struct {+ g.Meta `path:"/postfix_queue/delete" method:"post" summary:"Clear all deferred queue"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+}++type DeleteAllDeferredQueueRes struct {+ api_v1.StandardRes+}++type FlushPostfixQueueReq struct {+ g.Meta `path:"/postfix_queue/flush" method:"post" summary:"Force send all mail queue"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ Domain string `json:"domain" dc:"Optional, specify domain to force send"`+}++type FlushPostfixQueueRes struct {+ api_v1.StandardRes+}++type FlushPostfixQueueByIdReq struct {+ g.Meta `path:"/postfix_queue/flush_by_id" method:"post" summary:"Resend specified queue mail"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ QueueID string `json:"queue_id" v:"required" dc:"Queue ID"`+}++type FlushPostfixQueueByIdRes struct {+ api_v1.StandardRes+}++type SetPostfixConfigReq struct {+ g.Meta `path:"/postfix_queue/set_config" method:"post" summary:"Set Postfix queue-related configuration items"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ Key string `json:"key" dc:"Configuration key"`+ Value string `json:"value" dc:"Configuration value"`+}++type SetPostfixConfigRes struct {+ api_v1.StandardRes+}++type GetPostfixConfigReq struct {+ g.Meta `path:"/postfix_queue/get_config" method:"get" summary:"Get Postfix queue-related configuration items"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+}++type GetPostfixConfigRes struct {+ api_v1.StandardRes+}diff --git a/core/internal/consts/log_type.go b/core/internal/consts/log_type.goindex b2e60c75..1d7af557 100644--- a/core/internal/consts/log_type.go+++ b/core/internal/consts/log_type.go@@ -23,6 +23,7 @@ var (DockerApi stringLanguage stringLogin string+ PostfixQueue string}{Task: "Email Marketing Task",Template: "Email Template",@@ -40,6 +41,7 @@ var (DockerApi: "Docker Api",Language: "Language",Login: "Login",+ PostfixQueue: "Postfix Queue",})var (diff --git a/core/internal/controller/mail_services/mail_services_v1_delete_all_deferred_queue.go b/core/internal/controller/mail_services/mail_services_v1_delete_all_deferred_queue.gonew file mode 100644index 00000000..bf5d7228--- /dev/null+++ b/core/internal/controller/mail_services/mail_services_v1_delete_all_deferred_queue.go@@ -0,0 +1,50 @@+package mail_services++import (+ "billionmail-core/internal/consts"+ docker "billionmail-core/internal/service/dockerapi"+ "billionmail-core/internal/service/public"+ "context"+ "strings"++ "github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g"++ "billionmail-core/api/mail_services/v1"+)++func (c *ControllerV1) DeleteAllDeferredQueue(ctx context.Context, req *v1.DeleteAllDeferredQueueReq) (res *v1.DeleteAllDeferredQueueRes, err error) {+ res = &v1.DeleteAllDeferredQueueRes{}+ dk, dockerErr := docker.NewDockerAPI()+ if dockerErr != nil {+ g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)+ res.SetError(gerror.New(public.LangCtx(ctx, "docker api unavailable: {}", dockerErr.Error())))+ return res, nil+ }+ defer dk.Close()+ cmd := []string{"postsuper", "-d", "ALL", "deferred"}+ result, err := dk.ExecCommandByName(ctx, consts.SERVICES.Postfix, cmd, "root")+ if err != nil {+ g.Log().Error(ctx, "Failed to execute command in container :", err, "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to execute command in container: {}", err.Error())))+ return res, nil+ }+ if result == nil {+ g.Log().Error(ctx, "The result of the command is empty:", "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "The result of the command is empty: {}", strings.Join(cmd, " "))))+ return res, nil+ }+ if result.ExitCode != 0 {+ g.Log().Error(ctx, "The command execution returns a nonzero status:", result.ExitCode, "output:", result.Output, "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "Command execution failed, exit code: {}, output: {}", result.ExitCode, result.Output)))+ return res, nil+ }++ // Operation Log+ _ = public.WriteLog(ctx, public.LogParams{+ Type: consts.LOGTYPE.PostfixQueue,+ Log: "Delete all deferred queue mail successfully",+ })+ res.SetSuccess(public.LangCtx(ctx, "delete all deferred queue mail success"))+ return res, nil+}diff --git a/core/internal/controller/mail_services/mail_services_v1_delete_postfix_queue_by_id.go b/core/internal/controller/mail_services/mail_services_v1_delete_postfix_queue_by_id.gonew file mode 100644index 00000000..ef072f16--- /dev/null+++ b/core/internal/controller/mail_services/mail_services_v1_delete_postfix_queue_by_id.go@@ -0,0 +1,35 @@+package mail_services++import (+ "billionmail-core/internal/consts"+ docker "billionmail-core/internal/service/dockerapi"+ "billionmail-core/internal/service/public"+ "context"+ "github.com/gogf/gf/v2/errors/gerror"++ "billionmail-core/api/mail_services/v1"+)++func (c *ControllerV1) DeletePostfixQueueById(ctx context.Context, req *v1.DeletePostfixQueueByIdReq) (res *v1.DeletePostfixQueueByIdRes, err error) {+ res = &v1.DeletePostfixQueueByIdRes{}++ dockerApi, err := docker.NewDockerAPI()++ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "docker api unavailable: {}", err.Error())))+ return res, nil+ }+ _, err = dockerApi.ExecCommandByName(ctx, "postfix", []string{"postsuper", "-d", req.QueueID}, "root")+ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "postsuper -d failed: {}", err.Error())))+ return res, nil+ }+ // Operation Log+ _ = public.WriteLog(ctx, public.LogParams{+ Type: consts.LOGTYPE.PostfixQueue,+ Log: "Delete postfix queue mail " + req.QueueID + " successfully",+ })++ res.SetSuccess(public.LangCtx(ctx, "delete postfix queue mail success"))+ return res, nil+}diff --git a/core/internal/controller/mail_services/mail_services_v1_flush_postfix_queue.go b/core/internal/controller/mail_services/mail_services_v1_flush_postfix_queue.gonew file mode 100644index 00000000..4c8de14e--- /dev/null+++ b/core/internal/controller/mail_services/mail_services_v1_flush_postfix_queue.go@@ -0,0 +1,94 @@+package mail_services++import (+ "billionmail-core/internal/consts"+ docker "billionmail-core/internal/service/dockerapi"+ "billionmail-core/internal/service/public"+ "context"+ "github.com/gogf/gf/os/gtimer"+ "strings"+ "time"++ "github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g"++ "billionmail-core/api/mail_services/v1"+)++func (c *ControllerV1) FlushPostfixQueue(ctx context.Context, req *v1.FlushPostfixQueueReq) (res *v1.FlushPostfixQueueRes, err error) {+ res = &v1.FlushPostfixQueueRes{}++ if req.Domain == "" {+ dk, dockerErr := docker.NewDockerAPI()+ if dockerErr != nil {+ g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)+ res.SetError(gerror.New(public.LangCtx(ctx, "docker api unavailable: {}", dockerErr.Error())))+ return res, nil+ }+ defer dk.Close()+ cmd := []string{"postqueue", "-f"}+ result, err := dk.ExecCommandByName(ctx, consts.SERVICES.Postfix, cmd, "root")+ if err != nil || result == nil || result.ExitCode != 0 {+ g.Log().Error(ctx, "Failed to flush all postfix queue:", err, result)+ res.SetError(gerror.New(public.LangCtx(ctx, "flush all postfix queue failed: {}", err)))+ return res, nil+ }+ _ = public.WriteLog(ctx, public.LogParams{+ Type: consts.LOGTYPE.PostfixQueue,+ Log: "Flush all postfix queue mail successfully",+ })+ res.SetSuccess(public.LangCtx(ctx, "flush all postfix queue success"))+ return res, nil+ }++ getReq := &v1.GetPostfixQueueListReq{+ Authorization: req.Authorization,+ }+ queueRes, err := c.GetPostfixQueueList(ctx, getReq)+ if err != nil || queueRes == nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "get postfix queue list failed: {}", err)))+ return res, nil+ }++ targetDomain := strings.ToLower(req.Domain)+ queueIDs := make(map[string]struct{})+ for _, item := range queueRes.Data.List {+ parts := strings.Split(item.Sender, "@")+ if len(parts) == 2 && strings.ToLower(parts[1]) == targetDomain {+ queueIDs[item.QueueID] = struct{}{}+ }+ }++ if len(queueIDs) == 0 {+ res.SetSuccess(public.LangCtx(ctx, "no deferred mail found for sender domain"))+ return res, nil+ }++ gtimer.AddOnce(100*time.Millisecond, func() {+ ctx1 := context.Background()+ dk, dockerErr := docker.NewDockerAPI()+ if dockerErr != nil {+ g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)+ return+ }+ defer dk.Close()++ for qid := range queueIDs {+ cmd := []string{"postqueue", "-i", qid}+ result, err := dk.ExecCommandByName(ctx1, consts.SERVICES.Postfix, cmd, "root")+ if err != nil || result == nil || result.ExitCode != 0 {+ g.Log().Error(ctx1, "Failed to flush queue id:", qid, err, result)+ } else {+ g.Log().Info(ctx1, "Flushed queue id:", qid)+ }+ }+ })++ // Operation Log+ _ = public.WriteLog(ctx, public.LogParams{+ Type: consts.LOGTYPE.PostfixQueue,+ Log: "Flush postfix queue mail [" + req.Domain + "] successfully",+ })+ res.SetSuccess(public.LangCtx(ctx, "flush postfix queue success"))+ return res, nil+}diff --git a/core/internal/controller/mail_services/mail_services_v1_flush_postfix_queue_by_id.go b/core/internal/controller/mail_services/mail_services_v1_flush_postfix_queue_by_id.gonew file mode 100644index 00000000..7abc584d--- /dev/null+++ b/core/internal/controller/mail_services/mail_services_v1_flush_postfix_queue_by_id.go@@ -0,0 +1,53 @@+package mail_services++import (+ "billionmail-core/internal/consts"+ docker "billionmail-core/internal/service/dockerapi"+ "billionmail-core/internal/service/public"+ "context"+ "strings"++ "github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g"++ "billionmail-core/api/mail_services/v1"+)++func (c *ControllerV1) FlushPostfixQueueById(ctx context.Context, req *v1.FlushPostfixQueueByIdReq) (res *v1.FlushPostfixQueueByIdRes, err error) {+ res = &v1.FlushPostfixQueueByIdRes{}+ if req.QueueID == "" {+ res.SetError(gerror.New(public.LangCtx(ctx, "queue_id required")))+ return res, nil+ }+ dk, dockerErr := docker.NewDockerAPI()+ if dockerErr != nil {+ g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)+ res.SetError(gerror.New(public.LangCtx(ctx, "docker api unavailable: {}", dockerErr.Error())))+ return res, nil+ }+ defer dk.Close()+ cmd := []string{"postqueue", "-i", req.QueueID}+ result, err := dk.ExecCommandByName(ctx, consts.SERVICES.Postfix, cmd, "root")+ if err != nil {+ g.Log().Error(ctx, "Failed to execute command in container :", err, "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to execute command in container: {}", err.Error())))+ return res, nil+ }+ if result == nil {+ g.Log().Error(ctx, "The result of the command is empty:", "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "The result of the command is empty: {}", strings.Join(cmd, " "))))+ return res, nil+ }+ if result.ExitCode != 0 {+ g.Log().Error(ctx, "The command execution returns a nonzero status:", result.ExitCode, "output:", result.Output, "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "Command execution failed, exit code: {}, output: {}", result.ExitCode, result.Output)))+ return res, nil+ }+ // Operation Log+ _ = public.WriteLog(ctx, public.LogParams{+ Type: consts.LOGTYPE.PostfixQueue,+ Log: "Flush postfix queue mail [" + req.QueueID + "] successfully",+ })+ res.SetSuccess(public.LangCtx(ctx, "flush postfix queue mail by id success"))+ return res, nil+}diff --git a/core/internal/controller/mail_services/mail_services_v1_get_postfix_config.go b/core/internal/controller/mail_services/mail_services_v1_get_postfix_config.gonew file mode 100644index 00000000..a3081e8e--- /dev/null+++ b/core/internal/controller/mail_services/mail_services_v1_get_postfix_config.go@@ -0,0 +1,63 @@+package mail_services++import (+ "billionmail-core/internal/service/public"+ "bufio"+ "context"+ "os"+ "strings"++ "github.com/gogf/gf/v2/frame/g"++ "billionmail-core/api/mail_services/v1"+)++func (c *ControllerV1) GetPostfixConfig(ctx context.Context, req *v1.GetPostfixConfigReq) (res *v1.GetPostfixConfigRes, err error) {+ res = &v1.GetPostfixConfigRes{}+ params := []string{"bounce_queue_lifetime", "maximal_queue_lifetime", "minimal_backoff_time", "maximal_backoff_time", "queue_run_delay", "trigger_timeout"}+ defaultConfig := map[string]string{+ "bounce_queue_lifetime": "5d",+ "maximal_backoff_time": "4000s",+ "maximal_queue_lifetime": "5d",+ "minimal_backoff_time": "300s",+ "queue_run_delay": "300s",+ "trigger_timeout": "10s",+ }+ config := make(map[string]string)+ mainCfPath := v1.ServiceType_Postfix+ file, err := os.Open(mainCfPath)+ if err != nil {+ g.Log().Warning(ctx, "Failed to open main.cf, use default values:", err)+ for _, key := range params {+ config[key] = defaultConfig[key]+ }+ res.Data = config+ res.SetSuccess(public.LangCtx(ctx, "Success (default values used)"))+ return res, nil+ }+ defer file.Close()+ kv := make(map[string]string)+ scanner := bufio.NewScanner(file)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" || strings.HasPrefix(line, "#") {+ continue+ }+ parts := strings.SplitN(line, "=", 2)+ if len(parts) == 2 {+ k := strings.TrimSpace(parts[0])+ v := strings.TrimSpace(parts[1])+ kv[k] = v+ }+ }+ for _, key := range params {+ if val, ok := kv[key]; ok {+ config[key] = val+ } else {+ config[key] = defaultConfig[key]+ }+ }+ res.Data = config+ res.SetSuccess(public.LangCtx(ctx, "Success"))+ return res, nil+}diff --git a/core/internal/controller/mail_services/mail_services_v1_get_postfix_queue_info.go b/core/internal/controller/mail_services/mail_services_v1_get_postfix_queue_info.gonew file mode 100644index 00000000..380ae4e6--- /dev/null+++ b/core/internal/controller/mail_services/mail_services_v1_get_postfix_queue_info.go@@ -0,0 +1,49 @@+package mail_services++import (+ "billionmail-core/internal/consts"+ docker "billionmail-core/internal/service/dockerapi"+ "billionmail-core/internal/service/public"+ "context"+ "strings"++ "github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g"++ "billionmail-core/api/mail_services/v1"+)++func (c *ControllerV1) GetPostfixQueueInfo(ctx context.Context, req *v1.GetPostfixQueueInfoReq) (res *v1.GetPostfixQueueInfoRes, err error) {+ res = &v1.GetPostfixQueueInfoRes{}+ if req.QueueID == "" {+ res.SetError(gerror.New(public.LangCtx(ctx, "queue_id required")))+ return res, nil+ }+ dk, dockerErr := docker.NewDockerAPI()+ if dockerErr != nil {+ g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)+ res.SetError(gerror.New(public.LangCtx(ctx, "docker api unavailable: {}", dockerErr.Error())))+ return res, nil+ }+ defer dk.Close()+ cmd := []string{"postcat", "-q", req.QueueID}+ result, err := dk.ExecCommandByName(ctx, consts.SERVICES.Postfix, cmd, "root")+ if err != nil {+ g.Log().Error(ctx, "Failed to execute command in container :", err, "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to execute command in container: {}", err.Error())))+ return res, nil+ }+ if result == nil {+ g.Log().Error(ctx, "The result of the command is empty:", "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "The result of the command is empty: {}", strings.Join(cmd, " "))))+ return res, nil+ }+ if result.ExitCode != 0 {+ g.Log().Error(ctx, "The command execution returns a nonzero status:", result.ExitCode, "output:", result.Output, "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "Command execution failed, exit code: {}, output: {}", result.ExitCode, result.Output)))+ return res, nil+ }+ res.Data = result.Output+ res.SetSuccess(public.LangCtx(ctx, "Success"))+ return res, nil+}diff --git a/core/internal/controller/mail_services/mail_services_v1_get_postfix_queue_list.go b/core/internal/controller/mail_services/mail_services_v1_get_postfix_queue_list.gonew file mode 100644index 00000000..cf69d312--- /dev/null+++ b/core/internal/controller/mail_services/mail_services_v1_get_postfix_queue_list.go@@ -0,0 +1,92 @@+package mail_services++import (+ docker "billionmail-core/internal/service/dockerapi"+ "billionmail-core/internal/service/public"+ "context"+ "strings"++ "github.com/gogf/gf/v2/encoding/gjson"+ "github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g"++ "billionmail-core/api/mail_services/v1"+ "billionmail-core/internal/consts"+)++func (c *ControllerV1) GetPostfixQueueList(ctx context.Context, req *v1.GetPostfixQueueListReq) (res *v1.GetPostfixQueueListRes, err error) {+ res = &v1.GetPostfixQueueListRes{}+ dk, dockerErr := docker.NewDockerAPI()+ if dockerErr != nil {+ g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)+ res.SetError(gerror.New(public.LangCtx(ctx, "docker api unavailable: {}", dockerErr.Error())))+ return res, nil+ }+ defer dk.Close()+ var cmd []string+ if req.Domain != "" {+ cmd = []string{"sh", "-c", "postqueue -j | grep -i '" + req.Domain + "'"}+ } else {+ cmd = []string{"postqueue", "-j"}+ }+ result, err := dk.ExecCommandByName(ctx, consts.SERVICES.Postfix, cmd, "root")+ if err != nil {+ g.Log().Error(ctx, "Failed to execute command in container :", err, "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to execute command in container: {}", err.Error())))+ return res, nil+ }++ if result == nil {+ g.Log().Error(ctx, "The result of the command is empty:", "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "The result of the command is empty: {}", strings.Join(cmd, " "))))+ return res, nil+ }+ if result.ExitCode != 0 {+ g.Log().Error(ctx, "The command execution returns a nonzero status:", result.ExitCode, "output:", result.Output, "command:", strings.Join(cmd, " "))+ res.SetError(gerror.New(public.LangCtx(ctx, "Command execution failed, exit code: {}, output: {}", result.ExitCode, result.Output)))+ return res, nil+ }++ lines := strings.Split(result.Output, "\n")+ list := make([]v1.QueueMailItem, 0)+ for _, line := range lines {+ if strings.TrimSpace(line) == "" {+ continue+ }+ var item struct {+ QueueName string `json:"queue_name"`+ QueueID string `json:"queue_id"`+ ArrivalTime int64 `json:"arrival_time"`+ MessageSize int `json:"message_size"`+ ForcedExpire bool `json:"forced_expire"`+ Sender string `json:"sender"`+ Recipients []struct {+ Address string `json:"address"`+ DelayReason string `json:"delay_reason,omitempty"`+ } `json:"recipients"`+ }+ if err := gjson.Unmarshal([]byte(line), &item); err != nil {+ continue+ }+ if item.QueueName != "deferred" {+ continue+ }+ for _, r := range item.Recipients {+ list = append(list, v1.QueueMailItem{+ QueueID: item.QueueID,+ Sender: item.Sender,+ Recipients: nil,+ ArrivalTime: item.ArrivalTime,+ DelayReason: r.DelayReason,+ MessageSize: item.MessageSize,+ QueueName: item.QueueName,+ ForcedExpire: item.ForcedExpire,+ Recipient: r.Address,+ })+ }+ }+ res.Data.List = list+ res.Data.Total = len(list)+ res.SetSuccess(public.LangCtx(ctx, "get postfix queue list success"))+ return res, nil+}diff --git a/core/internal/controller/mail_services/mail_services_v1_set_postfix_config.go b/core/internal/controller/mail_services/mail_services_v1_set_postfix_config.gonew file mode 100644index 00000000..22205100--- /dev/null+++ b/core/internal/controller/mail_services/mail_services_v1_set_postfix_config.go@@ -0,0 +1,116 @@+package mail_services++import (+ "billionmail-core/api/mail_services/v1"+ "billionmail-core/internal/consts"+ docker "billionmail-core/internal/service/dockerapi"+ "billionmail-core/internal/service/public"+ "context"+ "github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g"+ "github.com/gogf/gf/v2/os/gmutex"+ "io/ioutil"+ "strings"+)++var setPostfixConfigLocker = gmutex.New()++func (c *ControllerV1) SetPostfixConfig(ctx context.Context, req *v1.SetPostfixConfigReq) (res *v1.SetPostfixConfigRes, err error) {+ res = &v1.SetPostfixConfigRes{}++ if req.Key == "" || req.Value == "" {+ res.SetError(gerror.New(public.LangCtx(ctx, "key and value required")))+ return res, nil+ }++ // Allowable configuration for modification+ allowedKeys := map[string]struct{}{+ "bounce_queue_lifetime": {},+ "maximal_backoff_time": {},+ "maximal_queue_lifetime": {},+ "minimal_backoff_time": {},+ "queue_run_delay": {},+ "trigger_timeout": {},+ }++ if _, ok := allowedKeys[req.Key]; !ok {+ res.SetError(gerror.Newf(public.LangCtx(ctx, "config key not allowed to modify: {}", req.Key)))+ return res, nil+ }+ setPostfixConfigLocker.Lock()+ defer setPostfixConfigLocker.Unlock()++ postfixCfgPath := v1.ServiceType_Postfix++ data, err := ioutil.ReadFile(postfixCfgPath)+ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "open main.cf failed: %v", err.Error())))+ return res, nil+ }++ //// Backup+ //backupPath := fmt.Sprintf("%s.bak.%s", postfixCfgPath, time.Now().Format("20060102150405"))+ //if err := ioutil.WriteFile(backupPath, data, 0644); err != nil {+ // res.SetError(gerror.New(public.LangCtx(ctx, "backup main.cf failed: %v", err.Error())))+ // return res, nil+ //}++ // Process line by line+ lines := strings.Split(string(data), "\n")+ found := false+ for i, line := range lines {+ trim := strings.TrimSpace(line)+ if trim == "" || strings.HasPrefix(trim, "#") {+ continue+ }+ parts := strings.SplitN(trim, "=", 2)+ if len(parts) < 2 {+ continue+ }+ key := strings.TrimSpace(parts[0])+ if key == req.Key {+ lines[i] = req.Key + " = " + req.Value+ found = true+ break // Found and replaced, no need to continue loop+ }+ }+ if !found {++ if len(lines) > 0 && lines[len(lines)-1] != "" {+ lines = append(lines, "")+ }+ lines = append(lines, req.Key+" = "+req.Value)+ }++ err = ioutil.WriteFile(postfixCfgPath, []byte(strings.Join(lines, "\n")), 0644)+ if err != nil {+ // Attempt to restore from backup+ _ = ioutil.WriteFile(postfixCfgPath, data, 0644)+ res.SetError(gerror.New(public.LangCtx(ctx, "write main.cf failed: %v", err.Error())))+ return res, nil+ }++ // reload postfix+ dk, err := docker.NewDockerAPI()+ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "failed to create Docker API instance: %v", err.Error())))+ return res, nil+ }+ defer dk.Close()++ // Restart the Postfix container to apply the changes+ result, err := dk.ExecCommandByName(ctx, consts.SERVICES.Postfix, []string{"postfix", "reload"}, "root")+ if err != nil || result == nil || result.ExitCode != 0 {+ g.Log().Error(ctx, "Failed to reload postfix:", err, result)+ res.SetError(gerror.New(public.LangCtx(ctx, "set config success but reload failed, please check service status")))+ return res, nil+ }+ // Operation Log+ _ = public.WriteLog(ctx, public.LogParams{+ Type: consts.LOGTYPE.Settings,+ Log: "Set postfix config [" + req.Key + "] = [" + req.Value + "] successfully",+ })++ res.SetSuccess(public.LangCtx(ctx, "set postfix config success"))+ return res, nil+}