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 service configuration related interfaces

lotkca8f3a64bad8
diff --git a/core/api/mail_services/mail_services.go b/core/api/mail_services/mail_services.go
new file mode 100644
index 00000000..655e06fa
--- /dev/null
+++ b/core/api/mail_services/mail_services.go
@@ -0,0 +1,24 @@
+// =================================================================================
+// Code generated and maintained by GoFrame CLI tool. DO NOT EDIT.
+// =================================================================================
+
+package mail_services
+
+import (
+ "context"
+
+ "billionmail-core/api/mail_services/v1"
+)
+
+type IMailServicesV1 interface {
+ GetConfigFile(ctx context.Context, req *v1.GetConfigFileReq) (res *v1.GetConfigFileRes, err error)
+ SaveConfigFile(ctx context.Context, req *v1.SaveConfigFileReq) (res *v1.SaveConfigFileRes, err error)
+ GetBccList(ctx context.Context, req *v1.GetBccListReq) (res *v1.GetBccListRes, err error)
+ AddBcc(ctx context.Context, req *v1.AddBccReq) (res *v1.AddBccRes, err error)
+ EditBcc(ctx context.Context, req *v1.EditBccReq) (res *v1.EditBccRes, err error)
+ DeleteBcc(ctx context.Context, req *v1.DeleteBccReq) (res *v1.DeleteBccRes, err error)
+ GetMailForwardList(ctx context.Context, req *v1.GetMailForwardListReq) (res *v1.GetMailForwardListRes, err error)
+ 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)
+}
diff --git a/core/api/mail_services/v1/common.go b/core/api/mail_services/v1/common.go
new file mode 100644
index 00000000..90e65a69
--- /dev/null
+++ b/core/api/mail_services/v1/common.go
@@ -0,0 +1,47 @@
+package v1
+
+import (
+ "billionmail-core/utility/types/api_v1"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+type ServiceType string
+
+const (
+ ServiceTypePostfix ServiceType = "postfix"
+ ServiceTypeDovecot ServiceType = "dovecot"
+ ServiceTypeRspamd ServiceType = "rspamd"
+)
+
+const (
+ ServiceType_Postfix = "/opt/Billion-Mail/conf/postfix/main.cf"
+ ServiceType_Dovecot = "/opt/Billion-Mail/conf/dovecot/dovecot.conf"
+ ServiceType_Rspamd = "/opt/Billion-Mail/conf/rspamd/rspamd.conf"
+)
+
+type GetConfigFileReq struct {
+ g.Meta `path:"/services/get_config" method:"post" summary:"get config file"`
+ ServiceType ServiceType `json:"service_type" v:"required" desc:"service type"`
+}
+
+type GetConfigFileRes struct {
+ api_v1.StandardRes
+ Data struct {
+ ConfigPath string `json:"config_path"` // config file path
+ Content string `json:"content"` // file content
+ Encoding string `json:"encoding"` // file encoding
+ LastModified int64 `json:"last_modified"` // last modified time
+ Size int64 `json:"size"` // file size
+ OnlyRead bool `json:"only_read"` // only read (file too large)
+ } `json:"data"`
+}
+
+type SaveConfigFileReq struct {
+ g.Meta `path:"/services/save_config" method:"post" summary:"save config file"`
+ ServiceType ServiceType `json:"service_type" v:"required" desc:"service type"`
+ Content string `json:"content" v:"required" desc:"file content"`
+}
+
+type SaveConfigFileRes struct {
+ api_v1.StandardRes
+}
diff --git a/core/api/mail_services/v1/mail_bcc.go b/core/api/mail_services/v1/mail_bcc.go
new file mode 100644
index 00000000..524394ea
--- /dev/null
+++ b/core/api/mail_services/v1/mail_bcc.go
@@ -0,0 +1,70 @@
+package v1
+
+import (
+ "billionmail-core/utility/types/api_v1"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+type BmBcc struct {
+ ID int `json:"id" dc:"ID"`
+ Type string `json:"type" dc:"type: sender/recipient"`
+ Address string `json:"address" dc:"address"`
+ Goto string `json:"goto" dc:"Forwarding target"`
+ Domain string `json:"domain" dc:"domain"`
+ CreateTime int64 `json:"create_time" dc:"create time"`
+ UpdateTime int64 `json:"update_time" dc:"update time"`
+ Active int `json:"active" dc:"Status: 1-enabled, 0-disabled"`
+}
+
+type GetBccListReq struct {
+ g.Meta `path:"/mail_bcc/list" method:"get" summary:"get mail bcc list"`
+ Type string `json:"type" desc:"bcc type: sender/recipient, not set means get all"`
+ Domain string `json:"domain" desc:"domain filter"`
+ SearchKey string `json:"search_key" desc:"search key"`
+ PageNum int `json:"page_num" d:"1" desc:"page num"`
+ PageSize int `json:"page_size" d:"20" desc:"page size"`
+}
+
+type GetBccListRes struct {
+ api_v1.StandardRes
+ Data struct {
+ List []BmBcc `json:"list" dc:"BCC list"`
+ Total int `json:"total" dc:"total"`
+ } `json:"data"`
+}
+
+type AddBccReq struct {
+ g.Meta `path:"/mail_bcc/add" method:"post" summary:"add mail bcc"`
+ Type string `json:"type" v:"required|in:sender,recipient" dc:"bcc type: sender or recipient"`
+ Address string `json:"address" v:"required" dc:"email address or domain"`
+ Goto string `json:"goto" v:"required" dc:"forward target address"`
+ Domain string `json:"domain" dc:"domain"`
+ Active int `json:"active" d:"1" dc:"status: 1-enabled, 0-disabled"`
+}
+
+type AddBccRes struct {
+ api_v1.StandardRes
+}
+
+type EditBccReq struct {
+ g.Meta `path:"/mail_bcc/edit" method:"post" summary:"edit mail bcc"`
+ ID int `json:"id" v:"required" dc:"record id"`
+ Type string `json:"type" v:"in:sender,recipient" dc:"bcc typeype: sen or er or recipient"`
+ Address string `json:"address" dc:"email address or domainddress or domain"`
+ Goto string `json:"goto" dc:"forward target addressd target address"`
+ Domain string `json:"domain" dc:"domain"`
+ Active int `json:"active" v:"required" d:"1" dc:"status: 1-enabled, 0-disabled"`
+}
+
+type EditBccRes struct {
+ api_v1.StandardRes
+}
+
+type DeleteBccReq struct {
+ g.Meta `path:"/mail_bcc/delete" method:"post" summary:"delete mail bcc"`
+ ID int `json:"id" v:"required" dc:"ID"`
+}
+
+type DeleteBccRes struct {
+ api_v1.StandardRes
+}
diff --git a/core/api/mail_services/v1/mail_forward.go b/core/api/mail_services/v1/mail_forward.go
new file mode 100644
index 00000000..6223883a
--- /dev/null
+++ b/core/api/mail_services/v1/mail_forward.go
@@ -0,0 +1,63 @@
+package v1
+
+import (
+ "billionmail-core/utility/types/api_v1"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+type Alias struct {
+ Address string `json:"address" dc:"Alias address"`
+ Goto string `json:"goto" dc:"Forwarding target"`
+ Domain string `json:"domain" dc:"Domain name"`
+ CreateTime int64 `json:"create_time" dc:"Creation time"`
+ UpdateTime int64 `json:"update_time" dc:"Update time"`
+ Active int `json:"active" dc:"Status: 1-enabled, 0-disabled"`
+}
+
+type GetMailForwardListReq struct {
+ g.Meta `path:"/mail_forward/list" method:"get" summary:"get mail forward list"`
+ Domain string `json:"domain" desc:"domain filter"`
+ Page int `json:"page" v:"min:1" desc:"page num" default:"1"`
+ PageSize int `json:"page_size" v:"min:1" desc:"page size" default:"20"`
+ SearchKey string `json:"search_key" desc:"search key, can search address"`
+}
+
+type GetMailForwardListRes struct {
+ api_v1.StandardRes
+ Data struct {
+ Total int `json:"total" desc:"total records"`
+ List []*Alias `json:"list" desc:"mail forward list"`
+ } `json:"data"`
+}
+
+type AddMailForwardReq struct {
+ g.Meta `path:"/mail_forward/add" method:"post" summary:"add mail forward"`
+ Address string `json:"address" v:"required|email" desc:"forwarded email address, e.g. [email protected]"`
+ Goto string `json:"goto" v:"required" desc:"forward target address, multiple addresses separated by newline"`
+ Domain string `json:"domain" v:"required" desc:"domain"`
+ Active int `json:"active" v:"in:0,1" desc:"status: 1-enabled, 0-disabled" default:"1"`
+}
+
+type AddMailForwardRes struct {
+ api_v1.StandardRes
+}
+
+type EditMailForwardReq struct {
+ g.Meta `path:"/mail_forward/edit" method:"post" summary:"edit mail forward"`
+ Address string `json:"address" v:"required" desc:"forwarded email address"`
+ Goto string `json:"goto" desc:"forward target address, multiple addresses separated by newline. not set means only modify status"`
+ Active int `json:"active" v:"in:0,1" desc:"status: 1-enabled, 0-disabled"`
+}
+
+type EditMailForwardRes struct {
+ api_v1.StandardRes
+}
+
+type DeleteMailForwardReq struct {
+ g.Meta `path:"/mail_forward/delete" method:"post" summary:"delete mail forward"`
+ Address string `json:"address" v:"required" desc:"forwarded email address"`
+}
+
+type DeleteMailForwardRes struct {
+ api_v1.StandardRes
+}
diff --git a/core/internal/cmd/cmd.go b/core/internal/cmd/cmd.go
index 8bdb8710..1d929528 100644
--- a/core/internal/cmd/cmd.go
+++ b/core/internal/cmd/cmd.go
@@ -11,6 +11,7 @@ import (
"billionmail-core/internal/controller/files"
"billionmail-core/internal/controller/languages"
"billionmail-core/internal/controller/mail_boxes"
+ "billionmail-core/internal/controller/mail_services"
"billionmail-core/internal/controller/overview"
"billionmail-core/internal/controller/rbac"
"billionmail-core/internal/service/database_initialization"
@@ -182,6 +183,7 @@ var (
files.NewV1(),
abnormal_recipient.NewV1(),
languages.NewV1(),
+ mail_services.NewV1(),
)
})
diff --git a/core/internal/controller/mail_services/mail_services.go b/core/internal/controller/mail_services/mail_services.go
new file mode 100644
index 00000000..40b15a42
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services.go
@@ -0,0 +1,187 @@
+// =================================================================================
+// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
+// =================================================================================
+
+package mail_services
+
+import (
+ "billionmail-core/internal/model/entity"
+ docker "billionmail-core/internal/service/dockerapi"
+ "context"
+ "fmt"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gfile"
+ "github.com/gogf/gf/v2/text/gstr"
+ "path"
+ "regexp"
+ "strings"
+)
+
+func processForwardUsers(forwardUsers string) []string {
+
+ tmp := strings.Split(forwardUsers, "\\n")
+ if len(tmp) == 1 && strings.Contains(tmp[0], "\n") {
+ tmp = strings.Split(tmp[0], "\n")
+ }
+
+ result := make([]string, 0, len(tmp))
+ for _, addr := range tmp {
+ addr = strings.TrimSpace(addr)
+ if addr != "" {
+ result = append(result, addr)
+ }
+ }
+
+ return result
+}
+
+// SyncBccToPostfix sync bcc to postfix
+func SyncBccToPostfix(ctx context.Context) error {
+
+ // configPath
+ postfixConfigDir := "/opt/Billion-Mail/conf/postfix/conf"
+ senderBccFile := path.Join(postfixConfigDir, "sender_bcc")
+ recipientBccFile := path.Join(postfixConfigDir, "recipient_bcc")
+ mainCfFile := path.Join(postfixConfigDir, "main.cf")
+
+ if !gfile.Exists(postfixConfigDir) {
+ return gerror.Newf("Postfix configuration directory does not exist : %s", postfixConfigDir)
+
+ }
+
+ // clear bcc file
+ for _, file := range []string{senderBccFile, recipientBccFile} {
+ if err := gfile.PutContents(file, ""); err != nil {
+ return gerror.Newf("clear bcc file err : %v", err)
+ }
+ }
+
+ // read bcc from database
+ for _, bccType := range []string{"sender", "recipient"} {
+ var rules []*entity.BmBcc
+ err := g.DB().Model("bm_bcc").
+ Where("type", bccType).
+ Where("active", 1).
+ Scan(&rules)
+ if err != nil {
+ return err
+ }
+
+ var content strings.Builder
+ for _, rule := range rules {
+ address := rule.Address
+ // check address is domain or email
+ domainRegex := regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
+ if domainRegex.MatchString(address) {
+ content.WriteString(fmt.Sprintf("@%s %s\n", address, rule.Goto))
+ } else {
+ content.WriteString(fmt.Sprintf("%s %s\n", address, rule.Goto))
+ }
+ }
+
+ // write bcc to file
+ targetFile := senderBccFile
+ if bccType == "recipient" {
+ targetFile = recipientBccFile
+ }
+
+ if content.Len() > 0 {
+ if err := gfile.PutContents(targetFile, content.String()); err != nil {
+ return gerror.Newf("write bcc to file, err: %v", err)
+ }
+ }
+ }
+
+ // check main.cf file and add bcc config
+ if err := ensurePostfixBccConfig(mainCfFile); err != nil {
+ return err
+ }
+
+ postfixContainer := "billionmail-postfix-billionmail-1"
+
+ dk, dockerErr := docker.NewDockerAPI()
+ if dockerErr != nil {
+ g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)
+ return dockerErr
+ }
+ defer dk.Close()
+
+ cmdsToRun := [][]string{
+ {"postmap", "/etc/postfix/conf/sender_bcc"},
+ {"postmap", "/etc/postfix/conf/recipient_bcc"},
+ {"postfix", "reload"},
+ }
+
+ for _, cmd := range cmdsToRun {
+ result, err := dk.ExecCommandByName(ctx, postfixContainer, cmd, "root")
+
+ if err != nil {
+ g.Log().Error(ctx, "Failed to execute command in container :", err, "command:", strings.Join(cmd, " "))
+ return gerror.Newf("Failed to execute command in container: %v, command: %s", err, strings.Join(cmd, " "))
+ }
+
+ if result == nil {
+ g.Log().Error(ctx, "The result of the command is empty:", "command:", strings.Join(cmd, " "))
+ return gerror.Newf("The result of the command is empty: %s", strings.Join(cmd, " "))
+ }
+
+ if result.ExitCode != 0 {
+ g.Log().Error(ctx, "The command execution returns a nonzero status:", result.ExitCode, "output:", result.Output, "command:", strings.Join(cmd, " "))
+ return gerror.Newf("Command execution failed, exit code: %d, output: %s, command: %s",
+ result.ExitCode, result.Output, strings.Join(cmd, " "))
+ }
+ }
+
+ return nil
+}
+
+// ensurePostfixBccConfig Make sure the Postfix configuration includes the BCC option
+func ensurePostfixBccConfig(mainCfFile string) error {
+
+ content := gfile.GetContents(mainCfFile)
+
+ needUpdate := false
+ bccConfig := ""
+
+ // check sender_bcc_maps
+ if !gstr.Contains(content, "sender_bcc_maps") {
+ bccConfig += "sender_bcc_maps = hash:/etc/postfix/conf/sender_bcc\n"
+ needUpdate = true
+ }
+
+ // check recipient_bcc_maps
+ if !gstr.Contains(content, "recipient_bcc_maps") {
+ bccConfig += "recipient_bcc_maps = hash:/etc/postfix/conf/recipient_bcc\n"
+ needUpdate = true
+ }
+
+ if needUpdate {
+ if !strings.HasSuffix(content, "\n") {
+ content += "\n"
+ }
+ content += bccConfig
+
+ if err := gfile.PutContents(mainCfFile, content); err != nil {
+ return gerror.Newf("Failed to write to the configuration file: %v", err)
+ }
+ }
+
+ return nil
+}
+
+// Checks if the string is in domain format
+func isDomain(str string) bool {
+ domainRegex := regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
+ return domainRegex.MatchString(str)
+}
+
+// Extract the domain name from the address
+func extractDomain(address string) string {
+ if strings.Contains(address, "@") {
+ return strings.Split(address, "@")[1]
+ } else if strings.HasPrefix(address, "@") {
+ return address[1:]
+ }
+ return address
+}
diff --git a/core/internal/controller/mail_services/mail_services_new.go b/core/internal/controller/mail_services/mail_services_new.go
new file mode 100644
index 00000000..905844e5
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_new.go
@@ -0,0 +1,15 @@
+// =================================================================================
+// This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish.
+// =================================================================================
+
+package mail_services
+
+import (
+ "billionmail-core/api/mail_services"
+)
+
+type ControllerV1 struct{}
+
+func NewV1() mail_services.IMailServicesV1 {
+ return &ControllerV1{}
+}
diff --git a/core/internal/controller/mail_services/mail_services_v1_add_bcc.go b/core/internal/controller/mail_services/mail_services_v1_add_bcc.go
new file mode 100644
index 00000000..a1b79243
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_v1_add_bcc.go
@@ -0,0 +1,60 @@
+package mail_services
+
+import (
+ "billionmail-core/api/mail_services/v1"
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+ "time"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+)
+
+func (c *ControllerV1) AddBcc(ctx context.Context, req *v1.AddBccReq) (res *v1.AddBccRes, err error) {
+ res = &v1.AddBccRes{}
+
+ count, err := g.DB().Model("bm_bcc").
+ Where("type", req.Type).
+ Where("address", req.Address).
+ Where("goto", req.Goto).
+ Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "check rule failed: {}", err.Error())))
+ return res, nil
+ }
+ if count > 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "rule already exists")))
+ return res, nil
+ }
+
+ if req.Domain == "" {
+ req.Domain = extractDomain(req.Address)
+ }
+
+ now := time.Now().Unix()
+ _, err = g.DB().Model("bm_bcc").Insert(g.Map{
+ "type": req.Type,
+ "address": req.Address,
+ "goto": req.Goto,
+ "domain": req.Domain,
+ "create_time": now,
+ "update_time": now,
+ "active": req.Active,
+ })
+
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "add bcc rule failed: {}", err.Error())))
+ return res, nil
+ }
+
+ // sync config immediately to take effect
+ if err := SyncBccToPostfix(ctx); err != nil {
+ g.Log().Error(ctx, "sync bcc config failed: {}", err)
+ res.SetError(gerror.New(public.LangCtx(ctx, "add success but sync config failed: {}", err.Error())))
+ return res, nil
+ }
+
+ // set return data
+ res.SetSuccess(public.LangCtx(ctx, "add bcc rule success"))
+ return res, nil
+}
diff --git a/core/internal/controller/mail_services/mail_services_v1_add_mail_forward.go b/core/internal/controller/mail_services/mail_services_v1_add_mail_forward.go
new file mode 100644
index 00000000..64b69c07
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_v1_add_mail_forward.go
@@ -0,0 +1,65 @@
+package mail_services
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+ "strings"
+ "time"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/mail_services/v1"
+)
+
+func (c *ControllerV1) AddMailForward(ctx context.Context, req *v1.AddMailForwardReq) (res *v1.AddMailForwardRes, err error) {
+ res = &v1.AddMailForwardRes{}
+
+ count, err := g.DB().Model("alias").Where("address=?", req.Address).Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "check address failed: {}", err.Error())))
+ return res, nil
+ }
+
+ if count > 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "forward address already exists")))
+ return res, nil
+ }
+
+ count, err = g.DB().Model("domain").Where("domain=?", req.Domain).Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "check domain failed: {}", err.Error())))
+ return res, nil
+ }
+
+ if count == 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "domain not found in mail server")))
+ return res, nil
+ }
+
+ // process forward target addresses
+ forwardUsers := processForwardUsers(req.Goto)
+ if len(forwardUsers) == 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "forward target address cannot be empty")))
+ return res, nil
+ }
+
+ now := time.Now().Unix()
+
+ _, err = g.DB().Model("alias").Insert(g.Map{
+ "address": req.Address,
+ "goto": strings.Join(forwardUsers, ","),
+ "domain": req.Domain,
+ "create_time": now,
+ "update_time": now,
+ "active": req.Active,
+ })
+
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "add mail forward failed: {}", err.Error())))
+ return res, nil
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "add mail forward success"))
+ return res, nil
+}
diff --git a/core/internal/controller/mail_services/mail_services_v1_delete_bcc.go b/core/internal/controller/mail_services/mail_services_v1_delete_bcc.go
new file mode 100644
index 00000000..d9d54304
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_v1_delete_bcc.go
@@ -0,0 +1,40 @@
+package mail_services
+
+import (
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+
+ "billionmail-core/api/mail_services/v1"
+ "billionmail-core/internal/service/public"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+)
+
+func (c *ControllerV1) DeleteBcc(ctx context.Context, req *v1.DeleteBccReq) (res *v1.DeleteBccRes, err error) {
+ res = &v1.DeleteBccRes{}
+
+ info, err := g.DB().Model("bm_bcc").Where("id", req.ID).One()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "check record failed: {}", err.Error())))
+ return res, nil
+ }
+ if info.IsEmpty() {
+ res.SetError(gerror.New(public.LangCtx(ctx, "record not found")))
+ return res, nil
+ }
+
+ _, err = g.DB().Model("bm_bcc").Where("id", req.ID).Delete()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "delete bcc rule failed: {}", err.Error())))
+ return res, nil
+ }
+
+ if err := SyncBccToPostfix(ctx); err != nil {
+ g.Log().Error(ctx, "sync bcc config failed: {}", err)
+ res.SetError(gerror.New(public.LangCtx(ctx, "delete success but sync config failed: {}", err.Error())))
+ return res, nil
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "delete bcc rule success"))
+ return res, nil
+}
diff --git a/core/internal/controller/mail_services/mail_services_v1_delete_mail_forward.go b/core/internal/controller/mail_services/mail_services_v1_delete_mail_forward.go
new file mode 100644
index 00000000..4f0fa7cf
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_v1_delete_mail_forward.go
@@ -0,0 +1,35 @@
+package mail_services
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/mail_services/v1"
+)
+
+func (c *ControllerV1) DeleteMailForward(ctx context.Context, req *v1.DeleteMailForwardReq) (res *v1.DeleteMailForwardRes, err error) {
+ res = &v1.DeleteMailForwardRes{}
+
+ count, err := g.DB().Model("alias").Where("address=?", req.Address).Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "check address failed: {}", err.Error())))
+ return res, nil
+ }
+
+ if count == 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "forward address not found")))
+ return res, nil
+ }
+
+ _, err = g.DB().Model("alias").Where("address=?", req.Address).Delete()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "delete mail forward failed: {}", err.Error())))
+ return res, nil
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "delete mail forward success"))
+ return res, nil
+}
diff --git a/core/internal/controller/mail_services/mail_services_v1_edit_bcc.go b/core/internal/controller/mail_services/mail_services_v1_edit_bcc.go
new file mode 100644
index 00000000..73e88c78
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_v1_edit_bcc.go
@@ -0,0 +1,84 @@
+package mail_services
+
+import (
+ "context"
+ "github.com/gogf/gf/v2/database/gdb"
+ "github.com/gogf/gf/v2/frame/g"
+ "time"
+
+ "billionmail-core/api/mail_services/v1"
+ "billionmail-core/internal/service/public"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+)
+
+func (c *ControllerV1) EditBcc(ctx context.Context, req *v1.EditBccReq) (res *v1.EditBccRes, err error) {
+ res = &v1.EditBccRes{}
+
+ err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
+
+ info, err := tx.Model("bm_bcc").Where("id", req.ID).One()
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "check record failed: {}", err.Error()))
+ }
+ if info.IsEmpty() {
+ return gerror.New(public.LangCtx(ctx, "record not found"))
+ }
+
+ // prepare update data
+ updateData := g.Map{
+ "update_time": time.Now().Unix(),
+ "active": req.Active,
+ }
+
+ // check if it is full edit mode
+ isFullEdit := req.Type != "" && req.Address != "" && req.Goto != ""
+
+ // if it is full edit mode, update all fields
+ if isFullEdit {
+
+ domainValue := req.Domain
+ if domainValue == "" {
+ domainValue = extractDomain(req.Address)
+ }
+
+ updateData["type"] = req.Type
+ updateData["address"] = req.Address
+ updateData["goto"] = req.Goto
+ updateData["domain"] = domainValue
+ }
+
+ _, err = tx.Model("bm_bcc").
+ Where("id", req.ID).
+ Update(updateData)
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "update record failed: {}", err.Error()))
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "update record failed: {}", err.Error())))
+ return res, nil
+ }
+
+ // sync config immediately to take effect
+ if err := SyncBccToPostfix(ctx); err != nil {
+ g.Log().Error(ctx, "sync bcc config failed: {}", err)
+ res.SetError(gerror.New(public.LangCtx(ctx, "modify success but sync config failed: {}", err.Error())))
+ return res, nil
+ }
+
+ if req.Type != "" && req.Address != "" && req.Goto != "" {
+ res.SetSuccess(public.LangCtx(ctx, "modify bcc rule success"))
+ } else {
+ if req.Active == 1 {
+ res.SetSuccess(public.LangCtx(ctx, "bcc rule enabled"))
+ } else {
+ res.SetSuccess(public.LangCtx(ctx, "bcc rule disabled"))
+ }
+ }
+
+ return res, nil
+}
diff --git a/core/internal/controller/mail_services/mail_services_v1_edit_mail_forward.go b/core/internal/controller/mail_services/mail_services_v1_edit_mail_forward.go
new file mode 100644
index 00000000..896f2cbc
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_v1_edit_mail_forward.go
@@ -0,0 +1,55 @@
+package mail_services
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+ "strings"
+ "time"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/mail_services/v1"
+)
+
+func (c *ControllerV1) EditMailForward(ctx context.Context, req *v1.EditMailForwardReq) (res *v1.EditMailForwardRes, err error) {
+ res = &v1.EditMailForwardRes{}
+
+ count, err := g.DB().Model("alias").Where("address=?", req.Address).Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "check address failed: {}", err.Error())))
+ return res, nil
+ }
+
+ if count == 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "forward address not found")))
+ return res, nil
+ }
+
+ update := g.Map{
+ "update_time": time.Now().Unix(),
+ "active": req.Active,
+ }
+
+ // if provided ForwardUsers, update target address
+ if req.Goto != "" {
+ // process forward target addresses
+ forwardUsers := processForwardUsers(req.Goto)
+ if len(forwardUsers) == 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "forward target address cannot be empty")))
+ return res, nil
+ }
+
+ // add forward target to update parameters
+ update["goto"] = strings.Join(forwardUsers, ",")
+ }
+
+ _, err = g.DB().Model("alias").Where("address=?", req.Address).Update(update)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "modify mail forward failed: {}", err.Error())))
+ return res, nil
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "modify mail forward success"))
+ return res, nil
+}
diff --git a/core/internal/controller/mail_services/mail_services_v1_get_bcc_list.go b/core/internal/controller/mail_services/mail_services_v1_get_bcc_list.go
new file mode 100644
index 00000000..15bec589
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_v1_get_bcc_list.go
@@ -0,0 +1,56 @@
+package mail_services
+
+import (
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/util/gconv"
+
+ "billionmail-core/api/mail_services/v1"
+ "billionmail-core/internal/model/entity"
+ "billionmail-core/internal/service/public"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+)
+
+func (c *ControllerV1) GetBccList(ctx context.Context, req *v1.GetBccListReq) (res *v1.GetBccListRes, err error) {
+ res = &v1.GetBccListRes{}
+
+ model := g.DB().Model("bm_bcc")
+
+ if req.Type != "" {
+ model = model.Where("type", req.Type)
+ }
+ if req.Domain != "" {
+ model = model.Where("domain", req.Domain)
+ }
+ if req.SearchKey != "" {
+ model = model.WhereOr("address LIKE ?", "%"+req.SearchKey+"%").
+ WhereOr("goto LIKE ?", "%"+req.SearchKey+"%")
+ }
+
+ total, err := model.Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "get bcc total failed: {}", err.Error())))
+ return res, nil
+ }
+
+ list := make([]*entity.BmBcc, 0)
+ err = model.Page(req.PageNum, req.PageSize).
+ Order("id DESC").
+ Scan(&list)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "get bcc list failed: {}", err.Error())))
+ return res, nil
+ }
+
+ res.Data.List = make([]v1.BmBcc, 0)
+ if err = gconv.Structs(list, &res.Data.List); err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "convert data failed: {}", err.Error())))
+ return res, nil
+ }
+
+ res.Data.Total = total
+
+ res.SetSuccess(public.LangCtx(ctx, "get bcc list success"))
+ return res, nil
+}
diff --git a/core/internal/controller/mail_services/mail_services_v1_get_config_file.go b/core/internal/controller/mail_services/mail_services_v1_get_config_file.go
new file mode 100644
index 00000000..7dc955f1
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_v1_get_config_file.go
@@ -0,0 +1,138 @@
+package mail_services
+
+import (
+ "context"
+ "github.com/gogf/gf/v2/errors/gcode"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/os/gfile"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "billionmail-core/api/mail_services/v1"
+)
+
+func (c *ControllerV1) GetConfigFile(ctx context.Context, req *v1.GetConfigFileReq) (res *v1.GetConfigFileRes, err error) {
+ res = &v1.GetConfigFileRes{}
+
+ // get service config file pathe config file path
+ var configPath string
+ switch req.ServiceType {
+ case v1.ServiceTypePostfix:
+ configPath = v1.ServiceType_Postfix
+ case v1.ServiceTypeDovecot:
+ configPath = v1.ServiceType_Dovecot
+ case v1.ServiceTypeRspamd:
+ configPath = v1.ServiceType_Rspamd
+ default:
+ return nil, gerror.NewCode(gcode.CodeInvalidParameter, "invalid service type")
+ }
+
+ // check if the file exists
+ if !gfile.Exists(configPath) {
+ return nil, gerror.NewCode(gcode.CodeNotFound, "config file not found: "+configPath)
+ }
+
+ // get file info
+ fileInfo, err := os.Stat(configPath)
+ if err != nil {
+ return nil, gerror.NewCode(gcode.CodeInternalError, "get file info failed: "+err.Error())
+ }
+
+ // check if the file format is supported for online editing
+ ext := filepath.Ext(configPath)
+ if ext != "" {
+ ext = ext[1:] // remove the leading dot
+ }
+
+ unsupportedExts := []string{"gz", "zip", "rar", "exe", "db", "pdf", "doc", "xls", "docx",
+ "xlsx", "ppt", "pptx", "7z", "bz2", "png", "gif", "jpg", "jpeg", "bmp",
+ "icon", "ico", "pyc", "class", "so", "pyd"}
+
+ for _, unsupportedExt := range unsupportedExts {
+ if strings.EqualFold(ext, unsupportedExt) {
+ return nil, gerror.NewCode(gcode.CodeInvalidParameter, "unsupported file format")
+ }
+ }
+
+ // file size limit (3MB)
+ maxSize := int64(3 * 1024 * 1024)
+ fileSize := fileInfo.Size()
+
+ // fill response data
+ res.Data.ConfigPath = configPath
+ res.Data.LastModified = fileInfo.ModTime().Unix()
+ res.Data.Size = fileSize
+
+ // read file content
+ if fileSize > maxSize {
+ // file too large, only read the last part
+ content, err := tailFile(configPath, 10000)
+ if err != nil {
+ return nil, gerror.NewCode(gcode.CodeInternalError, "read file failed: "+err.Error())
+ }
+
+ res.Data.Content = content
+ res.Data.OnlyRead = true
+ res.Data.Encoding = "utf-8"
+ } else {
+ // read file normally
+ content := gfile.GetContents(configPath)
+ if err != nil {
+ return nil, gerror.NewCode(gcode.CodeInternalError, "read file failed: "+err.Error())
+ }
+
+ res.Data.Content = content
+ res.Data.Encoding = "utf-8" // default assume utf-8 encoding
+ res.Data.OnlyRead = false
+ }
+
+ res.SetSuccess("config file get success")
+ return res, nil
+}
+
+// tailFile read the last few lines of a file
+func tailFile(filename string, maxLines int) (string, error) {
+ file, err := os.Open(filename)
+ if err != nil {
+ return "", err
+ }
+ defer file.Close()
+
+ // get file size
+ info, err := file.Stat()
+ if err != nil {
+ return "", err
+ }
+ fileSize := info.Size()
+
+ // decide the start position
+ var startPos int64
+ if fileSize > int64(maxLines*100) { // assume each line is 100 bytes
+ startPos = fileSize - int64(maxLines*100)
+ } else {
+ startPos = 0
+ }
+
+ // move to the start position
+ _, err = file.Seek(startPos, 0)
+ if err != nil {
+ return "", err
+ }
+
+ // read content
+ buffer := make([]byte, fileSize-startPos)
+ _, err = file.Read(buffer)
+ if err != nil {
+ return "", err
+ }
+
+ content := string(buffer)
+
+ // if not read from the beginning of the file, add a prompt message
+ if startPos > 0 {
+ return "... (file too large, only show the last part) ...\n" + content, nil
+ }
+
+ return content, nil
+}
diff --git a/core/internal/controller/mail_services/mail_services_v1_get_mail_forward_list.go b/core/internal/controller/mail_services/mail_services_v1_get_mail_forward_list.go
new file mode 100644
index 00000000..b151527b
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_v1_get_mail_forward_list.go
@@ -0,0 +1,47 @@
+package mail_services
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/mail_services/v1"
+)
+
+func (c *ControllerV1) GetMailForwardList(ctx context.Context, req *v1.GetMailForwardListReq) (res *v1.GetMailForwardListRes, err error) {
+ res = &v1.GetMailForwardListRes{}
+
+ model := g.DB().Model("alias").Where("1=1")
+
+ if req.Domain != "" {
+ model = model.Where("domain=?", req.Domain)
+ }
+
+ if req.SearchKey != "" {
+ model = model.Where("(address LIKE ? OR goto LIKE ?)", "%"+req.SearchKey+"%", "%"+req.SearchKey+"%")
+ }
+
+ count, err := model.Count()
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get email forwarding list: {}", err.Error())))
+ return res, nil
+ }
+ res.Data.Total = count
+
+ if count == 0 {
+ res.Data.List = make([]*v1.Alias, 0)
+ res.SetSuccess(public.LangCtx(ctx, "Get email forwarding list successfully"))
+ return res, nil
+ }
+
+ err = model.Page(req.Page, req.PageSize).OrderDesc("create_time").Scan(&res.Data.List)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to get email forwarding list: {}", err.Error())))
+ return res, nil
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "Get email forwarding list successfully"))
+ return res, nil
+}
diff --git a/core/internal/controller/mail_services/mail_services_v1_save_config_file.go b/core/internal/controller/mail_services/mail_services_v1_save_config_file.go
new file mode 100644
index 00000000..9fd1c0a9
--- /dev/null
+++ b/core/internal/controller/mail_services/mail_services_v1_save_config_file.go
@@ -0,0 +1,117 @@
+package mail_services
+
+import (
+ "billionmail-core/internal/service/public"
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "billionmail-core/api/mail_services/v1"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gfile"
+)
+
+func (c *ControllerV1) SaveConfigFile(ctx context.Context, req *v1.SaveConfigFileReq) (res *v1.SaveConfigFileRes, err error) {
+ res = &v1.SaveConfigFileRes{}
+
+ var configPath string
+ //var serviceNameForCheck string
+ switch req.ServiceType {
+ case v1.ServiceTypePostfix:
+ configPath = v1.ServiceType_Postfix
+ //serviceNameForCheck = "Postfix"
+ case v1.ServiceTypeDovecot:
+ configPath = v1.ServiceType_Dovecot
+ //serviceNameForCheck = "Dovecot"
+ case v1.ServiceTypeRspamd:
+ configPath = v1.ServiceType_Rspamd
+ //serviceNameForCheck = "Rspamd"
+ default:
+ res.SetError(gerror.New(public.LangCtx(ctx, "Invalid service type")))
+ return nil, err
+ }
+
+ dirPath := filepath.Dir(configPath)
+ if !gfile.Exists(dirPath) {
+ if err := os.MkdirAll(dirPath, 0755); err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create directory: {}", err.Error())))
+ return nil, err
+ }
+ }
+
+ var backupPath string
+ backupMade := false
+ if gfile.Exists(configPath) {
+ backupPath = configPath + ".bak." + time.Now().Format("20060102150405")
+ if err := gfile.Copy(configPath, backupPath); err != nil {
+ g.Log().Warningf(ctx, "Failed to back up configuration file %s: %v", configPath, err)
+ } else {
+ g.Log().Infof(ctx, "A configuration file backup has been created: %s", backupPath)
+ backupMade = true
+ }
+ }
+
+ contentBytes := []byte(req.Content)
+ if err := os.WriteFile(configPath, contentBytes, 0644); err != nil {
+ if backupMade {
+ err = gfile.Move(backupPath, configPath)
+ }
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to save file: {}", err.Error())))
+ return nil, err
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "The configuration file was saved successfully"))
+ return
+}
+
+func getDockerCheckDetails(ctx context.Context, serviceType v1.ServiceType) (containerName string, commandAndArgs []string, execUser string, serviceDisplayName string) {
+ execUser = "root"
+
+ switch serviceType {
+ case v1.ServiceTypePostfix:
+ containerName = "billionmail-postfix-billionmail-1"
+ commandAndArgs = []string{"postfix", "check"}
+ serviceDisplayName = "Postfix"
+ return
+ case v1.ServiceTypeDovecot:
+ containerName = "billionmail-dovecot-billionmail-1"
+ commandAndArgs = []string{"doveconf", "-n"}
+ serviceDisplayName = "Dovecot"
+ return
+ case v1.ServiceTypeRspamd:
+ containerName = "billionmail-rspamd-billionmail-1"
+ commandAndArgs = []string{"rspamd", "configtest", "--insecure"}
+ serviceDisplayName = "Rspamd"
+ return
+ default:
+ return "", nil, "", "Unknown service"
+ }
+}
+
+func extractCheckError(outputStr string, defaultError string) string {
+ if len(outputStr) == 0 {
+ return defaultError
+ }
+ lines := strings.Split(outputStr, "\n")
+ for _, line := range lines {
+ lowerLine := strings.ToLower(line)
+ if strings.Contains(lowerLine, "error") ||
+ strings.Contains(lowerLine, "fatal") ||
+ strings.Contains(lowerLine, "failed") {
+ if len(line) > 256 {
+ return line[:256] + "..."
+ }
+ return line
+ }
+ }
+ if len(lines) > 0 && len(lines[0]) > 0 {
+ if len(lines[0]) > 256 {
+ return lines[0][:256] + "..."
+ }
+ return lines[0]
+ }
+ return defaultError
+}
diff --git a/core/internal/model/entity/bm_bcc.go b/core/internal/model/entity/bm_bcc.go
new file mode 100644
index 00000000..ded4e7ad
--- /dev/null
+++ b/core/internal/model/entity/bm_bcc.go
@@ -0,0 +1,13 @@
+package entity
+
+// BmBcc
+type BmBcc struct {
+ Id int `json:"id" description:"ID"`
+ Type string `json:"type" description:"类型: sender或recipient"`
+ Address string `json:"address" description:"地址"`
+ Goto string `json:"goto" description:"转发目标"`
+ Domain string `json:"domain" description:"域名"`
+ CreateTime int64 `json:"create_time" description:"创建时间"`
+ UpdateTime int64 `json:"update_time" description:"更新时间"`
+ Active int `json:"active" description:"状态: 1-启用, 0-禁用"`
+}
diff --git a/core/internal/service/database_initialization/mail_serv.go b/core/internal/service/database_initialization/mail_serv.go
index b30e5134..34383bd9 100644
--- a/core/internal/service/database_initialization/mail_serv.go
+++ b/core/internal/service/database_initialization/mail_serv.go
@@ -49,6 +49,18 @@ func init() {
PRIMARY KEY (address)
)`,
+ `-- bm_bcc
+ CREATE TABLE IF NOT EXISTS bm_bcc (
+ id SERIAL PRIMARY KEY,
+ type TEXT NOT NULL, -- 'sender' or 'recipient'
+ address TEXT NOT NULL,
+ goto TEXT NOT NULL,
+ domain varchar(255) NOT NULL,
+ create_time int NOT NULL default 0,
+ update_time int NOT NULL default 0,
+ active smallint NOT NULL DEFAULT 1
+ )`,
+
`-- alias_domain
CREATE TABLE IF NOT EXISTS alias_domain (
alias_domain varchar(255) NOT NULL,