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
Creating mailboxes in bulk
lotka4aa2f6ed0d8
diff --git a/core/api/mail_boxes/mail_boxes.go b/core/api/mail_boxes/mail_boxes.goindex 19c6c4cd..d0b194df 100644--- a/core/api/mail_boxes/mail_boxes.go+++ b/core/api/mail_boxes/mail_boxes.go@@ -12,6 +12,7 @@ import (type IMailBoxesV1 interface {AddMailbox(ctx context.Context, req *v1.AddMailboxReq) (res *v1.AddMailboxRes, err error)+ BatchAddMailbox(ctx context.Context, req *v1.BatchAddMailboxReq) (res *v1.BatchAddMailboxRes, err error)UpdateMailbox(ctx context.Context, req *v1.UpdateMailboxReq) (res *v1.UpdateMailboxRes, err error)DeleteMailbox(ctx context.Context, req *v1.DeleteMailboxReq) (res *v1.DeleteMailboxRes, err error)GetMailbox(ctx context.Context, req *v1.GetMailboxReq) (res *v1.GetMailboxRes, err error)diff --git a/core/api/mail_boxes/v1/mailboxes.go b/core/api/mail_boxes/v1/mailboxes.goindex 17722309..7639081d 100644--- a/core/api/mail_boxes/v1/mailboxes.go+++ b/core/api/mail_boxes/v1/mailboxes.go@@ -36,6 +36,20 @@ type AddMailboxRes struct {api_v1.StandardRes}+type BatchAddMailboxReq struct {+ g.Meta `path:"/mailbox/batch_create" tags:"MailBox" method:"post" summary:"Batch create mailbox" in:"body"`+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`+ Domain string `json:"domain" v:"required|domain" dc:"Domain"`+ Password string `json:"password" v:"required|min-length:8" dc:"Password"`+ Quota int `json:"quota" v:"required|min:1" dc:"Quota" d:"5242880"`+ Count int `json:"count" v:"required|min:2" dc:"Count" d:"10"`+ Prefix string `json:"prefix" v:"regex:[\\w-]{0,}" dc:"Email name prefix, optional" d:"user"`+}++type BatchAddMailboxRes struct {+ api_v1.StandardRes+}+type UpdateMailboxReq struct {g.Meta `path:"/mailbox/update" tags:"MailBox" method:"post" summary:"Update mailbox" in:"body"`Authorization string `json:"authorization" dc:"Authorization" in:"header"`diff --git a/core/internal/controller/mail_boxes/mail_boxes_v1_batch_add_mailbox.go b/core/internal/controller/mail_boxes/mail_boxes_v1_batch_add_mailbox.gonew file mode 100644index 00000000..c73ee6d9--- /dev/null+++ b/core/internal/controller/mail_boxes/mail_boxes_v1_batch_add_mailbox.go@@ -0,0 +1,29 @@+package mail_boxes++import (+ "context"+ "fmt"++ "billionmail-core/api/mail_boxes/v1"+ "billionmail-core/internal/service/mail_boxes"+)++func (c *ControllerV1) BatchAddMailbox(ctx context.Context, req *v1.BatchAddMailboxReq) (res *v1.BatchAddMailboxRes, err error) {++ res = &v1.BatchAddMailboxRes{}++ if req.Count > 5000 {+ return nil, fmt.Errorf("You cannot create more than 5000 batches")+ }++ createdEmails, err := mail_boxes.BatchAdd(ctx, req.Domain, req.Password, req.Quota, req.Count, req.Prefix)+ if err != nil {+ return nil, err+ }++ successMsg := fmt.Sprintf("%d email accounts were successfully created", len(createdEmails))+ res.SetSuccess(successMsg)+ res.Data = createdEmails++ return res, nil+}diff --git a/core/internal/service/mail_boxes/mail_boxes.go b/core/internal/service/mail_boxes/mail_boxes.goindex d93dc861..b327f1d7 100644--- a/core/internal/service/mail_boxes/mail_boxes.go+++ b/core/internal/service/mail_boxes/mail_boxes.go@@ -6,10 +6,13 @@ import ("encoding/base64""encoding/hex""fmt"- "time"-"github.com/GehirnInc/crypt/md5_crypt"+ "github.com/gogf/gf/v2/database/gdb""github.com/gogf/gf/v2/frame/g"+ "math/rand"+ "regexp"+ "strconv"+ "time")func Add(ctx context.Context, mailbox *v1.Mailbox) (err error) {@@ -160,3 +163,111 @@ func PasswdMD5Crypt(ctx context.Context, password string) (string, error) {return result, nil}++func BatchAdd(ctx context.Context, domain, password string, quota int, count int, prefix string) ([]string, error) {++ if prefix == "" {+ randomPre := make([]byte, 4)+ for j := 0; j < 4; j++ {+ randomPre[j] = byte(rand.Intn(26) + 97) // a-z的ASCII码+ }++ prefix = string(randomPre)+ }++ matched, err := regexp.MatchString(`^[\w-]+$`, prefix)+ if err != nil {+ return nil, fmt.Errorf("Prefix validation error: %w", err)+ }+ if !matched {+ return nil, fmt.Errorf("Prefixes can contain only letters, numbers, underscores, and hyphens")+ }++ rand.Seed(time.Now().UnixNano())++ createdEmails := make([]string, 0, count)++ timestamp := time.Now().Unix()++ passwordEncoded := PasswdEncode(ctx, password)+ passwordCrypted, err := PasswdMD5Crypt(ctx, password)+ if err != nil {+ return nil, fmt.Errorf("Generate password md5-crypt failed: %w", err)+ }++ mailboxes := make([]v1.Mailbox, 0, count)+ emailList := make([]string, 0, count)++ for i := 0; i < count; i++ {+ // 生成本地部分(用户名): prefix + 自增数字 + 随机2位字母+ randomChars := make([]byte, 2)+ for j := 0; j < 2; j++ {+ randomChars[j] = byte(rand.Intn(26) + 97) // a-z的ASCII码+ }++ localPart := fmt.Sprintf("%s%s%s%s", prefix, strconv.Itoa(i), string(randomChars))+ username := localPart + "@" + domain++ mailbox := v1.Mailbox{+ Username: username,+ Password: passwordCrypted,+ PasswordEncode: passwordEncoded,+ FullName: localPart,+ IsAdmin: 0,+ Quota: int64(quota),+ LocalPart: localPart,+ Domain: domain,+ CreateTime: timestamp,+ UpdateTime: timestamp,+ Active: 1,+ Maildir: fmt.Sprintf("%s@%s/", localPart, domain),+ }++ mailboxes = append(mailboxes, mailbox)+ emailList = append(emailList, username)+ }++ err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {++ //domainExists, err := tx.Model("domain").Where("domain", domain).WhereNot("active", 0).One()+ //if err != nil {+ // return fmt.Errorf("Check the domain for a failure: %w", err)+ //}+ //if domainExists.IsEmpty() {+ // return fmt.Errorf(" %s Not present or activated", domain)+ //}++ const batchSize = 100+ for i := 0; i < len(mailboxes); i += batchSize {+ end := i + batchSize+ if end > len(mailboxes) {+ end = len(mailboxes)+ }++ batch := mailboxes[i:end]++ _, err := tx.Model("mailbox").Ctx(ctx).InsertIgnore(batch)+ if err != nil {+ return fmt.Errorf("Batch insert mailbox failed (batch %d-%d): %w", i, end-1, err)+ }++ for j := i; j < end; j++ {+ createdEmails = append(createdEmails, emailList[j])+ }++ }++ return nil+ })++ if err != nil {++ return nil, fmt.Errorf("Failed to create email: %w", err)+ }++ if len(createdEmails) == 0 {+ return nil, fmt.Errorf("Failed to create any mailbox")+ }++ return createdEmails, nil+}