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

Batch deletion of mailbox, batch addition, import/export

lotkc220d0df7fad
diff --git a/core/api/mail_boxes/mail_boxes.go b/core/api/mail_boxes/mail_boxes.go
index d0b194df..5dfda86b 100644
--- a/core/api/mail_boxes/mail_boxes.go
+++ b/core/api/mail_boxes/mail_boxes.go
@@ -18,4 +18,6 @@ type IMailBoxesV1 interface {
GetMailbox(ctx context.Context, req *v1.GetMailboxReq) (res *v1.GetMailboxRes, err error)
GetAllMailbox(ctx context.Context, req *v1.GetAllMailboxReq) (res *v1.GetAllMailboxRes, err error)
GetAllEmail(ctx context.Context, req *v1.GetAllEmailReq) (res *v1.GetAllEmailRes, err error)
+ ExportMailbox(ctx context.Context, req *v1.ExportMailboxReq) (res *v1.ExportMailboxRes, err error)
+ ImportMailbox(ctx context.Context, req *v1.ImportMailboxReq) (res *v1.ImportMailboxRes, err error)
}
diff --git a/core/api/mail_boxes/v1/mailboxes.go b/core/api/mail_boxes/v1/mailboxes.go
index 23d61085..796b4693 100644
--- a/core/api/mail_boxes/v1/mailboxes.go
+++ b/core/api/mail_boxes/v1/mailboxes.go
@@ -68,9 +68,9 @@ type UpdateMailboxRes struct {
}
type DeleteMailboxReq struct {
- g.Meta `path:"/mailbox/delete" tags:"MailBox" method:"post" summary:"Delete mailbox" in:"body"`
- Authorization string `json:"authorization" dc:"Authorization" in:"header"`
- Email string `json:"email" v:"required|email" dc:"Email"`
+ g.Meta `path:"/mailbox/delete" tags:"MailBox" method:"post" summary:"Delete mailbox (batch supported)" in:"body"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ Emails []string `json:"emails" v:"required" dc:"Email address list for delete"`
}
type DeleteMailboxRes struct {
@@ -118,3 +118,27 @@ type GetAllEmailRes struct {
api_v1.StandardRes
Data []string `json:"data"` // List of email addresses
}
+
+// 导出邮箱
+type ExportMailboxReq struct {
+ g.Meta `path:"/mailbox/export" tags:"MailBox" method:"post" summary:"Export mailbox" in:"query"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ Domain string `json:"domain" v:"domain" dc:"Domain"`
+ FileType string `json:"file_type" v:"in:csv,txt,json" dc:"File type to export, csv or txt or json (default: csv)"`
+}
+
+type ExportMailboxRes struct {
+ api_v1.StandardRes
+}
+
+// 导入邮箱
+type ImportMailboxReq struct {
+ g.Meta `path:"/mailbox/import" tags:"MailBox" method:"post" summary:"Import mailbox" in:"body"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ FileData string `json:"file_data" v:"required" dc:"File data in base64 format"`
+ FileType string `json:"file_type" v:"in:csv,txt,json" dc:"File type to import, csv or txt or json (default: csv)"`
+}
+
+type ImportMailboxRes struct {
+ api_v1.StandardRes
+}
diff --git a/core/internal/controller/mail_boxes/mail_boxes_v1_delete_mailbox.go b/core/internal/controller/mail_boxes/mail_boxes_v1_delete_mailbox.go
index 65a9e38a..f7fcc4ab 100644
--- a/core/internal/controller/mail_boxes/mail_boxes_v1_delete_mailbox.go
+++ b/core/internal/controller/mail_boxes/mail_boxes_v1_delete_mailbox.go
@@ -4,6 +4,7 @@ import (
"billionmail-core/internal/consts"
"billionmail-core/internal/service/public"
"context"
+ "fmt"
"github.com/gogf/gf/v2/errors/gerror"
@@ -14,17 +15,38 @@ import (
func (c *ControllerV1) DeleteMailbox(ctx context.Context, req *v1.DeleteMailboxReq) (res *v1.DeleteMailboxRes, err error) {
res = &v1.DeleteMailboxRes{}
- if req.Email == "" {
- return nil, gerror.New("Email address cannot be empty")
+ if len(req.Emails) == 0 {
+ return nil, gerror.New("Email addresses cannot be empty")
}
- if err = mail_boxes.Delete(ctx, req.Email); err != nil {
+ var validEmails []string
+ for _, email := range req.Emails {
+ if email != "" {
+ validEmails = append(validEmails, email)
+ }
+ }
+
+ if len(validEmails) == 0 {
+ return nil, gerror.New("No valid email addresses provided")
+ }
+
+ affected, err := mail_boxes.DeleteBatch(ctx, validEmails)
+ if err != nil {
return nil, err
}
- _ = public.WriteLog(ctx, public.LogParams{
- Type: consts.LOGTYPE.Mailboxes,
- Log: "Deleted mailbox:" + req.Email + " successfully",
- })
- res.SetSuccess("Mailbox deleted successfully")
+
+ for _, email := range validEmails {
+ _ = public.WriteLog(ctx, public.LogParams{
+ Type: consts.LOGTYPE.Mailboxes,
+ Log: "Deleted mailbox:" + email + " successfully",
+ })
+ }
+
+ if affected == 0 {
+ res.SetSuccess("No mailboxes were deleted (they may not exist)")
+ } else {
+ res.SetSuccess(fmt.Sprintf("Successfully deleted %d mailbox(es)", affected))
+ }
+
return
}
diff --git a/core/internal/controller/mail_boxes/mail_boxes_v1_export_mailbox.go b/core/internal/controller/mail_boxes/mail_boxes_v1_export_mailbox.go
new file mode 100644
index 00000000..7212f86b
--- /dev/null
+++ b/core/internal/controller/mail_boxes/mail_boxes_v1_export_mailbox.go
@@ -0,0 +1,87 @@
+package mail_boxes
+
+import (
+ "billionmail-core/api/mail_boxes/v1"
+ "billionmail-core/internal/consts"
+ "billionmail-core/internal/service/mail_boxes"
+ "billionmail-core/internal/service/public"
+ "context"
+ "encoding/csv"
+ "encoding/json"
+ "fmt"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "strings"
+)
+
+func (c *ControllerV1) ExportMailbox(ctx context.Context, req *v1.ExportMailboxReq) (res *v1.ExportMailboxRes, err error) {
+ res = &v1.ExportMailboxRes{}
+
+ if req.FileType == "" {
+ req.FileType = "csv"
+ }
+
+ var mailboxes []v1.Mailbox
+
+ mailboxes, err = mail_boxes.All(ctx, req.Domain)
+ if err != nil {
+ return nil, err
+ }
+
+ var content, contentType, fileName string
+ switch req.FileType {
+ case "txt":
+ lines := make([]string, 0, len(mailboxes))
+ for _, m := range mailboxes {
+ lines = append(lines, m.Username)
+ }
+ content = strings.Join(lines, "\n")
+ contentType = "text/plain"
+ fileName = "mailboxes.txt"
+ case "json":
+ data, _ := json.MarshalIndent(mailboxes, "", " ")
+ content = string(data)
+ contentType = "application/json"
+ fileName = "mailboxes.json"
+ case "csv":
+ var b strings.Builder
+ w := csv.NewWriter(&b)
+
+ _ = w.Write([]string{"username", "full_name", "is_admin", "quota", "local_part", "domain", "active", "password", "password_encode"})
+ for _, m := range mailboxes {
+ _ = w.Write([]string{
+ m.Username,
+ m.FullName,
+ fmt.Sprintf("%d", m.IsAdmin),
+ fmt.Sprintf("%d", m.Quota),
+ m.LocalPart,
+ m.Domain,
+ fmt.Sprintf("%d", m.Active),
+ m.Password,
+ m.PasswordEncode,
+ })
+ }
+ w.Flush()
+ content = b.String()
+ contentType = "text/csv"
+ fileName = "mailboxes.csv"
+ default:
+ return nil, gerror.New("Unsupported export type")
+ }
+
+ r := g.RequestFromCtx(ctx)
+ if r == nil {
+ return nil, gerror.New("Unable to obtain the request context")
+ }
+ r.Response.Header().Set("Content-Type", contentType)
+ r.Response.Header().Set("Content-Disposition", "attachment; filename="+fileName)
+ r.Response.Write([]byte(content))
+
+ _ = public.WriteLog(ctx, public.LogParams{
+ Type: consts.LOGTYPE.Mailboxes,
+ Log: "Exporting the email box was successful.",
+ Data: mailboxes,
+ })
+
+ return
+}
diff --git a/core/internal/controller/mail_boxes/mail_boxes_v1_import_mailbox.go b/core/internal/controller/mail_boxes/mail_boxes_v1_import_mailbox.go
new file mode 100644
index 00000000..af4a3ff7
--- /dev/null
+++ b/core/internal/controller/mail_boxes/mail_boxes_v1_import_mailbox.go
@@ -0,0 +1,170 @@
+package mail_boxes
+
+import (
+ "billionmail-core/api/mail_boxes/v1"
+ "billionmail-core/internal/consts"
+ "billionmail-core/internal/service/mail_boxes"
+ "billionmail-core/internal/service/public"
+ "context"
+ "encoding/csv"
+ "encoding/json"
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+)
+
+func (c *ControllerV1) ImportMailbox(ctx context.Context, req *v1.ImportMailboxReq) (res *v1.ImportMailboxRes, err error) {
+ res = &v1.ImportMailboxRes{}
+
+ // default CSV
+ if req.FileType == "" {
+ req.FileType = "csv"
+ }
+
+ //// 1. base64
+ //raw, err := base64.StdEncoding.DecodeString(req.FileData)
+ //if err != nil {
+ // res.SetError(gerror.New(public.LangCtx(ctx, "文件内容解码失败")))
+ // return res, nil
+ //}
+ //content := string(raw)
+
+ content := req.FileData
+
+ var mailboxes []v1.Mailbox
+ switch req.FileType {
+ case "json":
+ if err := json.Unmarshal([]byte(content), &mailboxes); err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "JSON parsing failed")))
+ return res, nil
+ }
+ case "csv":
+ r := csv.NewReader(strings.NewReader(content))
+ records, err := r.ReadAll()
+ if err != nil || len(records) < 2 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "CSV parsing failed")))
+ return res, nil
+ }
+ header := records[0]
+ for _, row := range records[1:] {
+ m := v1.Mailbox{}
+ for i, col := range header {
+ if i >= len(row) {
+ continue
+ }
+ switch col {
+ case "username":
+ m.Username = row[i]
+ case "full_name":
+ m.FullName = row[i]
+ case "is_admin":
+ m.IsAdmin = parseInt(row[i])
+ case "quota":
+ m.Quota = int64(parseInt(row[i]))
+ case "local_part":
+ m.LocalPart = row[i]
+ case "domain":
+ m.Domain = row[i]
+ case "active":
+ m.Active = parseInt(row[i])
+ case "password":
+ m.Password = row[i]
+ case "password_encode":
+ m.PasswordEncode = row[i]
+ }
+ }
+ mailboxes = append(mailboxes, m)
+ }
+ case "txt":
+ lines := strings.Split(content, "\n")
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ continue
+ }
+ mailboxes = append(mailboxes, v1.Mailbox{Username: line})
+ }
+ default:
+ res.SetError(gerror.New(public.LangCtx(ctx, "Unsupported file type")))
+ return res, nil
+ }
+
+ if len(mailboxes) == 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to parse valid email data")))
+ return res, nil
+ }
+
+ for i := range mailboxes {
+ // If FullName is empty, use LocalPart instead
+ if mailboxes[i].FullName == "" && mailboxes[i].LocalPart != "" {
+ mailboxes[i].FullName = mailboxes[i].LocalPart
+ }
+
+ if mailboxes[i].LocalPart == "" && mailboxes[i].Username != "" {
+ if parts := strings.Split(mailboxes[i].Username, "@"); len(parts) == 2 {
+ mailboxes[i].LocalPart = parts[0]
+ mailboxes[i].Domain = parts[1]
+ }
+ }
+
+ if mailboxes[i].Domain == "" && mailboxes[i].Username != "" {
+ if parts := strings.Split(mailboxes[i].Username, "@"); len(parts) == 2 {
+ mailboxes[i].Domain = parts[1]
+ }
+ }
+
+ if mailboxes[i].Password == "" {
+ mailboxes[i].Password = "123456"
+ }
+
+ if mailboxes[i].IsAdmin == 0 {
+ mailboxes[i].IsAdmin = 0
+ }
+ if mailboxes[i].Quota == 0 {
+ mailboxes[i].Quota = 1000
+ }
+ if mailboxes[i].Active == 0 {
+ mailboxes[i].Active = 1
+ }
+ }
+
+ var failed []string
+ var successCount int
+ for _, m := range mailboxes {
+
+ if err := mail_boxes.AddImport(ctx, &m); err != nil {
+ failed = append(failed, m.Username)
+ continue
+ }
+ successCount++
+ }
+
+ importResult := map[string]interface{}{
+ "total": len(mailboxes),
+ "success": successCount,
+ "failed": len(failed),
+ "failed_list": failed,
+ }
+
+ _ = public.WriteLog(ctx, public.LogParams{
+ Type: consts.LOGTYPE.Mailboxes,
+ Log: fmt.Sprintf("Import of email account was successful. Total: %d, Success: %d, Failed: %d", len(mailboxes), successCount, len(failed)),
+ Data: importResult,
+ })
+
+ if len(failed) > 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "The import is complete, but {} email addresses failed to be imported", len(failed))))
+ } else {
+ res.SetSuccess(public.LangCtx(ctx, "Import completed. A total of {} email addresses were imported.", successCount))
+ }
+
+ return res, nil
+}
+
+// String to int conversion
+func parseInt(s string) int {
+ n, _ := strconv.Atoi(strings.TrimSpace(s))
+ return n
+}
diff --git a/core/internal/service/mail_boxes/mail_boxes.go b/core/internal/service/mail_boxes/mail_boxes.go
index 59725fdb..66c4c3db 100644
--- a/core/internal/service/mail_boxes/mail_boxes.go
+++ b/core/internal/service/mail_boxes/mail_boxes.go
@@ -38,7 +38,7 @@ func Add(ctx context.Context, mailbox *v1.Mailbox) (err error) {
mailbox.Active = 1
mailbox.Maildir = fmt.Sprintf("%s@%s/", mailbox.LocalPart, mailbox.Domain)
- _, err = g.DB().Model("mailbox").Ctx(ctx).Insert(mailbox)
+ _, err = g.DB().Model("mailbox").Ctx(ctx).InsertIgnore(mailbox)
return err
}
@@ -77,6 +77,28 @@ func Delete(ctx context.Context, email string) error {
return err
}
+func DeleteBatch(ctx context.Context, emails []string) (int64, error) {
+ if len(emails) == 0 {
+ return 0, nil
+ }
+
+ result, err := g.DB().Model("mailbox").
+ Ctx(ctx).
+ WhereIn("username", emails).
+ Delete()
+
+ if err != nil {
+ return 0, err
+ }
+
+ affected, err := result.RowsAffected()
+ if err != nil {
+ return 0, err
+ }
+
+ return affected, nil
+}
+
func Get(ctx context.Context, domain, keyword string, page, pageSize int) ([]v1.Mailbox, int, error) {
m := g.DB().Model("mailbox").Order("create_time", "desc")
@@ -284,6 +306,48 @@ func BatchAdd(ctx context.Context, domain, password string, quota int, count int
return createdEmails, nil
}
+// AddImport
+func AddImport(ctx context.Context, mailbox *v1.Mailbox) (err error) {
+
+ if mailbox.PasswordEncode != "" {
+
+ if mailbox.Password == "" {
+ mailbox.Password, err = PasswdDecode(ctx, mailbox.PasswordEncode)
+ if err != nil {
+ err = fmt.Errorf("Decode password failed: %w", err)
+ return
+ }
+ }
+
+ mailbox.Password, err = PasswdMD5Crypt(ctx, mailbox.Password)
+ if err != nil {
+ err = fmt.Errorf("Generate password md5-crypt failed: %w", err)
+ return
+ }
+ } else {
+
+ mailbox.PasswordEncode = PasswdEncode(ctx, mailbox.Password)
+ mailbox.Password, err = PasswdMD5Crypt(ctx, mailbox.Password)
+ if err != nil {
+ err = fmt.Errorf("Generate password md5-crypt failed: %w", err)
+ return
+ }
+ }
+
+ mailbox.Username = strings.ToLower(mailbox.Username)
+ mailbox.LocalPart = strings.ToLower(mailbox.LocalPart)
+ mailbox.Domain = strings.ToLower(mailbox.Domain)
+
+ now := time.Now().Unix()
+ mailbox.CreateTime = now
+ mailbox.UpdateTime = now
+ mailbox.Active = 1
+ mailbox.Maildir = fmt.Sprintf("%s@%s/", mailbox.LocalPart, mailbox.Domain)
+
+ _, err = g.DB().Model("mailbox").Ctx(ctx).InsertIgnore(mailbox)
+ return err
+}
+
// NormalizeMailboxes normalizes mailbox usernames, local parts, domains, and maildirs to lowercase.
func NormalizeMailboxes() (err error) {
// Attempt update mailboxes with uppercase letters in username