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
Template, Contacts
lotk179aa7a5fdb7
diff --git a/core/api/settings/v1/settings.go b/core/api/settings/v1/settings.goindex 6c1c6da8..2c83b992 100644--- a/core/api/settings/v1/settings.go+++ b/core/api/settings/v1/settings.go@@ -5,6 +5,77 @@ import ("github.com/gogf/gf/v2/frame/g")+// SSLConfig+type SSLConfig struct {+ CertPath string `json:"cert_path" dc:"cert path"`+ KeyPath string `json:"key_path" dc:"key path"`+ CertData string `json:"certPem" dc:"cert data"`+ KeyData string `json:"privateKey" dc:"key data"`+ ValidUntil string `json:"notAfter" dc:"cert not after"`+ ValidFrom string `json:"notBefore" dc:"cert not before"`+ Issuer string `json:"issuer" dc:"cert issuer"`+ Subject string `json:"subject" dc:"cert subject"`+ DNSNames []string `json:"dns_names" dc:"dns names"`+ SerialNumber string `json:"serial_number" dc:"serial number"`+ IsCA bool `json:"is_ca" dc:"is ca certificate"`+ IssuerCommonName string `json:"issuer_common_name" dc:"issuer common name"`+ SubjectCommonName string `json:"subject_common_name" dc:"subject common name"`+ Version int `json:"version" dc:"version"`+}++// SystemConfig+type SystemConfig struct {+ // Basic configuration+ AdminUsername string `json:"admin_username" dc:"admin username"`+ AdminPassword string `json:"admin_password" dc:"admin password"`+ SafePath string `json:"safe_path" dc:"safe path"`++ // Domain name configuration+ Hostname string `json:"billionmail_hostname" dc:"billionmail hostname"`++ // Database configuration+ DBName string `json:"db_name" dc:"db name"`+ DBUser string `json:"db_user" dc:"db user"`+ DBPass string `json:"db_pass" dc:"db password"`++ // Redis configuration+ RedisPass string `json:"redis_pass" dc:"redis password"`+ RedisPort string `json:"redis_port" dc:"redis port"`++ // Port configuration+ MailPorts struct {+ SMTP int `json:"smtp" dc:"smtp port"`+ SMTPS int `json:"smtps" dc:"smtps port"`+ Submission int `json:"submission" dc:"submission port"`+ IMAP int `json:"imap" dc:"imap port"`+ IMAPS int `json:"imaps" dc:"imaps port"`+ POP int `json:"pop" dc:"pop port"`+ POPS int `json:"pops" dc:"pops port"`+ } `json:"mail_ports" dc:"mail ports configuration"`++ // Management port configuration+ ManagePorts struct {+ HTTP int `json:"http" dc:"http port"`+ HTTPS int `json:"https" dc:"https port"`+ Command1 string `json:"command_https" dc:"command https"`+ Command2 string `json:"command_http" dc:"command http"`+ } `json:"manage_ports" dc:"management ports configuration"`++ // Time zone configuration+ ManageTimeZone struct {+ TimeZone string `json:"timezone" dc:"time zone"`+ Command string `json:"command" dc:"command"`+ } `json:"manage_timezone" dc:"time zone configuration"`++ // IPv4 network configuration+ IPv4Network string `json:"ipv4_network" dc:"ipv4 network"`+ Fail2ban bool `json:"fail2ban" dc:"fail2ban"`+ WhitelistIP []string `json:"whitelist_ip" dc:"whitelist ip"`++ // SSL certificate configuration+ SSL SSLConfig `json:"ssl" dc:"ssl certificate configuration"`+}+type GetVersionReq struct {g.Meta `path:"/settings/get_version" tags:"Version" method:"get" summary:"Get current version information" in:"query"`}@@ -18,3 +89,47 @@ type GetVersionRes struct {CanUpdate bool `json:"can_update" dc:"CanUpdate"`} `json:"data" dc:"Data"`}++// Get system configuration request+type GetSystemConfigReq struct {+ g.Meta `path:"/settings/get_system_config" tags:"Settings" method:"get" summary:"Get system configuration"`+}++// Get system configuration response+type GetSystemConfigRes struct {+ api_v1.StandardRes+ Data *SystemConfig `json:"data" dc:"system configuration data"`+}++// Set system configuration request+type SetSystemConfigReq struct {+ g.Meta `path:"/settings/set_system_config" tags:"Settings" method:"post" summary:"Set system configuration"`+ SystemConfig+}++// Set system configuration response+type SetSystemConfigRes struct {+ api_v1.StandardRes+}++// Set system configuration request+type SetSystemConfigKeyReq struct {+ g.Meta `path:"/settings/set_system_config_key" tags:"Settings" method:"post" summary:"Set system configuration"`+ Key string `json:"key" dc:"configuration key"`+ Value string `json:"value" dc:"configuration value"`+}++type SetSystemConfigKeyRes struct {+ api_v1.StandardRes+}++// Set SSL certificate request+type SetSSLConfigReq struct {+ g.Meta `path:"/settings/set_ssl_config" tags:"Settings" method:"post" summary:"Set SSL certificate configuration"`+ CertData string `json:"certPem" dc:"certificate data"`+ KeyData string `json:"privateKey" dc:"private key data"`+}++type SetSSLConfigRes struct {+ api_v1.StandardRes+}diff --git a/core/internal/controller/batch_mail/batch_mail_v1_send_test_email.go b/core/internal/controller/batch_mail/batch_mail_v1_send_test_email.goindex 71a728bd..923bff41 100644--- a/core/internal/controller/batch_mail/batch_mail_v1_send_test_email.go+++ b/core/internal/controller/batch_mail/batch_mail_v1_send_test_email.go@@ -79,8 +79,7 @@ func (c *ControllerV1) SendTestEmail(ctx context.Context, req *v1.SendTestEmailR// send emailerr = sender.Send(message, []string{req.Recipient})if err != nil {- g.Log().Error(ctx, "send email to %s failed: %v", req.Recipient, err)- res.SetError(gerror.New(public.LangCtx(ctx, "send email to %s failed: %v", req.Recipient, err)))+ res.SetError(gerror.New(public.LangCtx(ctx, "send email to {} failed: {}", req.Recipient, err)))return}diff --git a/core/internal/controller/contact/contact_v1_edit_contacts.go b/core/internal/controller/contact/contact_v1_edit_contacts.gonew file mode 100644index 00000000..2db5070a--- /dev/null+++ b/core/internal/controller/contact/contact_v1_edit_contacts.go@@ -0,0 +1,142 @@+package contact++import (+ "billionmail-core/internal/service/contact"+ "billionmail-core/internal/service/public"+ "context"+ "encoding/json"+ "fmt"+ "github.com/gogf/gf/v2/database/gdb"+ "github.com/gogf/gf/v2/frame/g"+ "strings"+ "time"++ "github.com/gogf/gf/v2/errors/gerror"++ "billionmail-core/api/contact/v1"+)++func (c *ControllerV1) EditContacts(ctx context.Context, req *v1.EditContactsReq) (res *v1.EditContactsRes, err error) {+ res = &v1.EditContactsRes{}++ var attribs map[string]string+ if req.Attribs != "" {++ attribsStr := strings.Trim(req.Attribs, "\"")++ attribsStr = strings.ReplaceAll(attribsStr, "\"\"", "\"")++ var rawAttribs map[string]interface{}+ if err := json.Unmarshal([]byte(attribsStr), &rawAttribs); err != nil {+ res.Code = 400+ res.SetError(gerror.New(public.LangCtx(ctx, "Invalid attributes format:{}", err.Error())))+ return res, nil+ }++ attribs = make(map[string]string)+ for k, v := range rawAttribs {+ switch val := v.(type) {+ case string:+ attribs[k] = val+ case float64: // Numbers in JSON parse to float64 by default+ if float64(int64(val)) == val {+ // Integer+ attribs[k] = fmt.Sprintf("%d", int64(val))+ } else {+ // Float+ attribs[k] = fmt.Sprintf("%g", val)+ }+ case bool:+ attribs[k] = fmt.Sprintf("%v", val)+ case nil:+ attribs[k] = ""+ default:+ // Other types try to convert to JSON string+ if bytes, err := json.Marshal(val); err == nil {+ attribs[k] = string(bytes)+ } else {+ attribs[k] = fmt.Sprintf("%v", val)+ }+ }+ }+ }++ err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {++ if len(req.GroupIds) > 0 {+ for _, groupId := range req.GroupIds {+ if _, err := contact.GetGroup(ctx, groupId); err != nil {+ return gerror.New(public.LangCtx(ctx, "Group {} not found", groupId))+ }+ }+ }++ var existingContact struct {+ Attribs map[string]string `json:"attribs"`+ Status int `json:"status"`+ }+ err := g.DB().Model("bm_contacts").+ Where("email", req.Emails).+ Order("id DESC").+ Limit(1).+ Scan(&existingContact)++ var finalAttribs map[string]string+ if attribs != nil {+ // If new attributes are provided, use them directly (without merging)+ finalAttribs = attribs+ } else if err == nil && existingContact.Attribs != nil {+ // If no new attributes are provided, use existing attributes+ finalAttribs = existingContact.Attribs+ } else {++ finalAttribs = make(map[string]string)+ }++ // 3. If group relations need to be updatedrelations need to be updated+ if len(req.GroupIds) > 0 {+ // Delete old contact recordsd contact records+ _, err := g.DB().Model("bm_contacts").+ Where("email", req.Emails).+ Delete()+ if err != nil {+ return gerror.New(public.LangCtx(ctx, "Failed to delete old contact records"))+ }++ // Create new group relations+ now := time.Now().Unix()+ var data []g.Map++ for _, groupId := range req.GroupIds {+ data = append(data, g.Map{+ "email": req.Emails,+ "group_id": groupId,+ "active": req.Active,+ "create_time": now,+ "attribs": finalAttribs,+ "status": existingContact.Status,+ })+ }++ if len(data) > 0 {+ _, err := g.DB().Model("bm_contacts").+ Data(data).+ Insert()+ if err != nil {+ return gerror.New(public.LangCtx(ctx, "Failed to create new contact records"))+ }+ }+ }++ return nil+ })++ if err != nil {+ res.Code = 500+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to edit contact: {}", err.Error())))+ return+ }++ res.SetSuccess(public.LangCtx(ctx, "Contact updated successfully"))+ return+}diff --git a/core/internal/controller/contact/contact_v1_export_contacts.go b/core/internal/controller/contact/contact_v1_export_contacts.goindex 8476908d..cd1541b0 100644--- a/core/internal/controller/contact/contact_v1_export_contacts.go+++ b/core/internal/controller/contact/contact_v1_export_contacts.go@@ -7,7 +7,10 @@ import ("billionmail-core/internal/model/entity""billionmail-core/internal/service/contact""billionmail-core/internal/service/public"+ "bytes""context"+ "encoding/csv"+ "encoding/json""fmt""github.com/gogf/gf/v2/errors/gerror""github.com/gogf/gf/v2/os/gfile"@@ -15,6 +18,8 @@ import ("io""os""path/filepath"+ "strings"+ "time")func (c *ControllerV1) ExportContacts(ctx context.Context, req *v1.ExportContactsReq) (res *v1.ExportContactsRes, err error) {@@ -75,7 +80,7 @@ func (c *ControllerV1) ExportContacts(ctx context.Context, req *v1.ExportContact// Export file based on formatvar fileContent []byte- fileContent, err = exportContactFile(allContacts, req.Format)+ fileContent, err = exportContactFile1(allContacts, req.Format)if err != nil {fmt.Println("Export file error: ", err)res.Code = 500@@ -126,7 +131,7 @@ func (c *ControllerV1) ExportContacts(ctx context.Context, req *v1.ExportContactfilePath := filepath.Join(tempDir, fileName)// Export file- fileContent, err := exportContactFile(filteredContacts, req.Format)+ fileContent, err := exportContactFile1(filteredContacts, req.Format)if err != nil {continue}@@ -218,3 +223,96 @@ func createZipFile(files []ExportFile, zipPath string) error {return nil}++// exportContactFile1+func exportContactFile1(contacts []*entity.Contact, format string) ([]byte, error) {+ var content []byte+ switch format {+ case "csv":+ // Create CSV writer+ var csvData [][]string++ // Add CSV headers+ headers := []string{+ "email", // Email address+ "attributes", // Attributes+ "active", // Active status+ "create_time", // Create time+ }+ csvData = append(csvData, headers)++ // Add data rows+ for _, c := range contacts {+ if c.Attribs == nil {+ c.Attribs = make(map[string]string)+ }+ // Convert attributes to JSON string+ attribsJSON, err := json.Marshal(c.Attribs)+ if err != nil {+ attribsJSON = []byte("{}")+ }++ // Format time+ createdAt := ""+ if c.CreateTime != 0 {+ // Convert timestamp to time string+ t := time.Unix(int64(c.CreateTime), 0)+ createdAt = t.Format("2006-01-02 15:04:05")+ }++ row := []string{+ c.Email,+ string(attribsJSON),+ fmt.Sprintf("%d", c.Active),+ createdAt,+ }+ csvData = append(csvData, row)+ }++ // Write CSV data+ buf := &bytes.Buffer{}+ writer := csv.NewWriter(buf)+ err := writer.WriteAll(csvData)+ if err != nil {+ return nil, err+ }+ content = buf.Bytes()++ case "txt":+ var lines []string+ for _, c := range contacts {+ // Convert attributes to JSON string+ attribsJSON, err := json.Marshal(c.Attribs)+ if err != nil {+ attribsJSON = []byte("{}")+ }++ // Format create time+ createdAt := ""+ if c.CreateTime != 0 {+ // Convert timestamp to time string+ t := time.Unix(int64(c.CreateTime), 0)+ createdAt = t.Format("2006-01-02 15:04:05")+ }++ // Format: email,attributes,active,created_at+ line := fmt.Sprintf("%s,%s,%d,%s",+ c.Email,+ string(attribsJSON),+ c.Active,+ createdAt,+ )+ lines = append(lines, line)+ }+ content = []byte(strings.Join(lines, "\n"))++ case "excel":++ return nil, fmt.Errorf("excel format not implemented")++ default:+ return nil, fmt.Errorf("unsupported format: %s", format)+ }++ return content, nil+}diff --git a/core/internal/controller/contact/contact_v1_import_contacts.go b/core/internal/controller/contact/contact_v1_import_contacts.goindex 74c61993..d6469110 100644--- a/core/internal/controller/contact/contact_v1_import_contacts.go+++ b/core/internal/controller/contact/contact_v1_import_contacts.go@@ -6,113 +6,301 @@ import ("billionmail-core/internal/model/entity""billionmail-core/internal/service/contact""billionmail-core/internal/service/public"+ "bytes""context"+ "encoding/csv"+ "encoding/json"+ "fmt""github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g"+ "io""strings")-// parseEmailContent parse email content-func parseEmailContent(content string) []*entity.Contact {+const (+ ImportTypeFile = 1+ ImportTypePaste = 2+ DefaultBatchSize = 1000+)++// isCSVFormat Check if the content is in CSV format+func isCSVFormat(firstLine string) bool {+ // 1. Check if the standard CSV header is included+ lowercaseLine := strings.ToLower(firstLine)+ if strings.Contains(lowercaseLine, "email") {+ return true+ }++ // 2. Try to parse the first line with CSV reader+ reader := csv.NewReader(strings.NewReader(firstLine))+ record, err := reader.Read()+ if err != nil {+ return false+ }++ // If it can be parsed into multiple columns and the first column is not a valid email address, it may be a CSV header+ if len(record) > 1 && !strings.Contains(record[0], "@") {+ return true+ }++ return false+}++// parseJSONAttributes Parse JSON attribute string+func parseJSONAttributes(ctx context.Context, attribsStr string) (map[string]string, error) {+ g.Log().Debug(ctx, "Parsing JSON attributes: %s", attribsStr)++ // Handle double quote escaping+ attribsStr = strings.ReplaceAll(attribsStr, "\"\"", "\"")+ // Remove leading and trailing quotes+ attribsStr = strings.Trim(attribsStr, "\"")++ if attribsStr == "{}" {+ return make(map[string]string), nil+ }++ var attribs map[string]interface{}+ if err := json.Unmarshal([]byte(attribsStr), &attribs); err != nil {+ g.Log().Error(ctx, "Failed to unmarshal JSON attributes: %v", err)+ return nil, err+ }++ // Convert all values to strings+ stringAttribs := make(map[string]string)+ for k, v := range attribs {+ switch val := v.(type) {+ case string:+ stringAttribs[k] = val+ g.Log().Debug(ctx, "Processed attribute %s: %s", k, val)+ case float64:+ if float64(int64(val)) == val {+ stringAttribs[k] = fmt.Sprintf("%d", int64(val))+ } else {+ stringAttribs[k] = fmt.Sprintf("%g", val)+ }+ case bool:+ stringAttribs[k] = fmt.Sprintf("%v", val)+ case nil:+ stringAttribs[k] = ""+ default:+ stringAttribs[k] = fmt.Sprintf("%v", val)+ }+ }++ g.Log().Debug(ctx, "Final parsed attributes: %v", stringAttribs)+ return stringAttribs, nil+}++// parseCSVContent Parse CSV content+func parseCSVContent(ctx context.Context, content string) ([]*entity.Contact, error) {var contacts []*entity.Contact- lines := strings.Split(strings.TrimSpace(content), "\n")+ reader := csv.NewReader(bytes.NewReader([]byte(content)))+ reader.FieldsPerRecord = -1+ reader.LazyQuotes = true+ reader.TrimLeadingSpace = true+ // Read headers+ headers, err := reader.Read()+ if err != nil {+ return nil, fmt.Errorf("failed to read CSV headers: %v", err)+ }++ // Find the index of the required columns+ columnIndexes := make(map[string]int)+ for i, header := range headers {+ header = strings.ToLower(strings.TrimSpace(header))+ columnIndexes[header] = i+ }++ // Check the required columns+ if _, ok := columnIndexes["email"]; !ok {+ return nil, fmt.Errorf("required column 'email' not found")+ }++ // Process data rows+ for {+ record, err := reader.Read()+ if err == io.EOF {+ break+ }+ if err != nil {+ g.Log().Warning(ctx, "Error reading CSV record: %v", err)+ continue+ }++ email := strings.TrimSpace(record[columnIndexes["email"]])+ if email == "" {+ continue+ }++ contact := &entity.Contact{+ Email: email,+ Active: -1,+ Attribs: make(map[string]string),+ }++ // Process active field+ if activeIdx, ok := columnIndexes["active"]; ok && len(record) > activeIdx {+ activeStr := strings.TrimSpace(record[activeIdx])+ if activeStr == "0" {+ contact.Active = 0+ } else if activeStr == "1" {+ contact.Active = 1+ }+ }++ // Process attributes+ if attribsIdx, ok := columnIndexes["attributes"]; ok && len(record) > attribsIdx {+ attribsStr := strings.TrimSpace(record[attribsIdx])+ if attribsStr != "" {+ attribs, err := parseJSONAttributes(ctx, attribsStr)+ if err != nil {+ g.Log().Warning(ctx, "Failed to parse attributes for email %s: %v", email, err)+ } else {+ contact.Attribs = attribs+ }+ }+ }++ contacts = append(contacts, contact)+ }++ return contacts, nil+}++// parseEmailContent parse email content with attributes+func parseEmailContent(ctx context.Context, content string, importType int) []*entity.Contact {+ content = strings.TrimSpace(content)+ if content == "" {+ return nil+ }++ lines := strings.Split(content, "\n")+ if len(lines) == 0 {+ return nil+ }++ // If it is a CSV format and the import type is file upload+ if isCSVFormat(lines[0]) && importType == ImportTypeFile {+ contacts, err := parseCSVContent(ctx, content)+ if err != nil {+ g.Log().Error(ctx, "Failed to parse CSV content: %v", err)+ return nil+ }+ return contacts+ }++ // Process normal text format+ var contacts []*entity.Contactfor _, line := range lines {line = strings.TrimSpace(line)if line == "" {continue}- // parse email and status- parts := strings.Split(line, ",")+ parts := strings.SplitN(line, ",", 2)email := strings.TrimSpace(parts[0])- active := 1 // default subscription status+ if email == "" {+ continue+ }++ contact := &entity.Contact{+ Email: email,+ Active: -1,+ Attribs: make(map[string]string),+ }- // if there is status informationif len(parts) > 1 {- status := strings.TrimSpace(parts[1])- if status == "0" {- active = 0+ attribsStr := strings.TrimSpace(parts[1])+ if attribsStr != "" && attribsStr != "null" {+ attribs, err := parseJSONAttributes(ctx, attribsStr)+ if err == nil {+ contact.Attribs = attribs+ }}}- if email != "" {- contacts = append(contacts, &entity.Contact{- Email: email,- Active: active,- })- }+ contacts = append(contacts, contact)}+return contacts}func (c *ControllerV1) ImportContacts(ctx context.Context, req *v1.ImportContactsReq) (res *v1.ImportContactsRes, err error) {res = &v1.ImportContactsRes{}- if len(req.GroupIds) == 0 {+ // Parameter validation+ if err := c.validateImportRequest(ctx, req); err != nil {res.Code = 400- res.SetError(gerror.New(public.LangCtx(ctx, "Group IDs cannot be empty")))- return- }-- for _, groupId := range req.GroupIds {- _, err = contact.GetGroup(ctx, groupId)- if err != nil {- res.Code = 400- res.SetError(gerror.New(public.LangCtx(ctx, "Group {} does not exist", groupId)))- return- }+ res.SetError(err)+ return res, nil}var contactList []*entity.Contact- // handle content according to import type+ // Process content based on import typeswitch req.ImportType {- case 1: // file upload+ case ImportTypeFile:if req.FileData == "" {res.Code = 400res.SetError(gerror.New(public.LangCtx(ctx, "File content cannot be empty")))- return+ return res, nil}- contactList = parseEmailContent(req.FileData)- case 2: // paste content+ g.Log().Debug(ctx, "Processing file import")+ contactList = parseEmailContent(ctx, req.FileData, req.ImportType)++ case ImportTypePaste:if req.Contacts == "" {res.Code = 400res.SetError(gerror.New(public.LangCtx(ctx, "Contacts content cannot be empty")))- return+ return res, nil}- contactList = parseEmailContent(req.Contacts)+ g.Log().Debug(ctx, "Processing paste import")+ contactList = parseEmailContent(ctx, req.Contacts, req.ImportType)default:res.Code = 400res.SetError(gerror.New(public.LangCtx(ctx, "Invalid import type")))- return+ return res, nil}if len(contactList) == 0 {res.Code = 400res.SetError(gerror.New(public.LangCtx(ctx, "No valid contacts found")))- return+ return res, nil}- // import contacts to each group+ g.Log().Debug(ctx, "Found %d valid contacts to import", len(contactList))++ // Import contacts to each groupsuccessCount := 0for _, groupId := range req.GroupIds {- // prepare contacts data for current groupvar groupContacts []*entity.Contactfor _, c := range contactList {- contactInfo := *c // create a copy+ contactInfo := *ccontactInfo.GroupId = groupId++ if contactInfo.Active == -1 {+ contactInfo.Active = req.DefaultActive+ }++ contactInfo.Status = req.StatusgroupContacts = append(groupContacts, &contactInfo)++ // Print the attributes of each contact for debugging+ g.Log().Debug(ctx, "Contact to import - Email: %s, Active: %d, Attributes: %v",+ contactInfo.Email,+ contactInfo.Active,+ contactInfo.Attribs)}- // batch create new contacts, ignore duplicate dataif len(groupContacts) > 0 {- count, err := contact.BatchCreateContactsIgnoreDuplicate(ctx, groupContacts)- if err != nil {+ count, importErr := c.importContactsToGroup(ctx, groupContacts, req.Overwrite)+ if importErr != nil {res.Code = 500- res.SetError(gerror.New(public.LangCtx(ctx, "Failed to import contacts: {}", err.Error())))- return nil, err+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to import contacts: {}", importErr.Error())))+ return res, importErr}successCount += count}@@ -120,5 +308,30 @@ func (c *ControllerV1) ImportContacts(ctx context.Context, req *v1.ImportContactres.Data.ImportedCount = successCountres.SetSuccess(public.LangCtx(ctx, "Successfully imported {} contacts", successCount))- return+ return res, nil+}++// validateImportRequest Validate import request parameters+func (c *ControllerV1) validateImportRequest(ctx context.Context, req *v1.ImportContactsReq) error {+ if len(req.GroupIds) == 0 {+ return gerror.New(public.LangCtx(ctx, "Group IDs cannot be empty"))+ }++ // Check if the group exists+ for _, groupId := range req.GroupIds {+ _, err := contact.GetGroup(ctx, groupId)+ if err != nil {+ return gerror.New(public.LangCtx(ctx, "Group {} does not exist", groupId))+ }+ }++ return nil+}++// importContactsToGroup Import contacts to the specified group+func (c *ControllerV1) importContactsToGroup(ctx context.Context, contacts []*entity.Contact, overwrite int) (int, error) {+ if overwrite == 1 {+ return contact.BatchCreateContactsWithOverwrite(ctx, contacts)+ }+ return contact.BatchCreateContactsIgnoreDuplicate(ctx, contacts)}diff --git a/core/internal/controller/settings/settings.go b/core/internal/controller/settings/settings.goindex 0ebe6674..b561da4b 100644--- a/core/internal/controller/settings/settings.go+++ b/core/internal/controller/settings/settings.go@@ -3,3 +3,176 @@// =================================================================================package settings++import (+ v1 "billionmail-core/api/settings/v1"+ "billionmail-core/internal/consts"+ "billionmail-core/internal/service/public"+ "crypto/x509"+ "encoding/pem"+ "fmt"+ "github.com/gogf/gf/v2/errors/gerror"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "time"+)++var (+ //envPath = "../.env"+ envPath = public.AbsPath("../.env")+ projectPath = public.AbsPath("../")+)++// loadEnvFile .env+func loadEnvFile() (map[string]string, error) {+ content, err := os.ReadFile(envPath)+ if err != nil {+ return nil, err+ }++ envMap := make(map[string]string)+ lines := strings.Split(string(content), "\n")++ for _, line := range lines {+ line = strings.TrimSpace(line)+ if line == "" || strings.HasPrefix(line, "#") {+ continue+ }++ parts := strings.SplitN(line, "=", 2)+ if len(parts) != 2 {+ continue+ }++ key := strings.TrimSpace(parts[0])+ value := strings.Trim(strings.TrimSpace(parts[1]), `"'`)+ envMap[key] = value+ }++ return envMap, nil+}++// loadSSLInfo+func loadSSLInfo() (*v1.SSLConfig, error) {++ certPath := public.AbsPath(filepath.Join(consts.SSL_PATH, "cert.pem"))+ keyPath := public.AbsPath(filepath.Join(consts.SSL_PATH, "key.pem"))++ if _, err := os.Stat(certPath); os.IsNotExist(err) {+ return nil, gerror.Newf("certificate file %s does not exist", certPath)+ }+ if _, err := os.Stat(keyPath); os.IsNotExist(err) {+ return nil, gerror.Newf("private key file %s does not exist", keyPath)+ }++ certData, err := os.ReadFile(certPath)+ if err != nil {+ return nil, gerror.Wrapf(err, "failed to read certificate file %s", certPath)+ }++ keyData, err := os.ReadFile(keyPath)+ if err != nil {+ return nil, gerror.Wrapf(err, "failed to read private key file %s", keyPath)+ }++ block, _ := pem.Decode(certData)+ if block == nil {+ return nil, gerror.New("failed to decode PEM block containing certificate")+ }++ cert, err := x509.ParseCertificate(block.Bytes)+ if err != nil {+ return nil, gerror.Wrap(err, "failed to parse certificate")+ }++ // 返回SSL配置+ return &v1.SSLConfig{+ CertPath: certPath,+ KeyPath: keyPath,+ CertData: string(certData),+ KeyData: string(keyData),+ ValidUntil: cert.NotAfter.Format(time.RFC3339),+ ValidFrom: cert.NotBefore.Format(time.RFC3339),+ Issuer: cert.Issuer.String(),+ Subject: cert.Subject.String(),+ DNSNames: cert.DNSNames,+ SerialNumber: cert.SerialNumber.String(),+ IsCA: cert.IsCA, // CA Certificate+ IssuerCommonName: cert.Issuer.CommonName,+ SubjectCommonName: cert.Subject.CommonName,+ Version: cert.Version,+ }, nil+}++// convertEnvToConfig Convert environment variables to configuration structure+func convertEnvToConfig(envMap map[string]string) *v1.SystemConfig {+ config := &v1.SystemConfig{}++ // Basic configuration+ config.AdminUsername = envMap["ADMIN_USERNAME"]+ config.AdminPassword = envMap["ADMIN_PASSWORD"]+ config.SafePath = envMap["SafePath"]+ config.Hostname = envMap["BILLIONMAIL_HOSTNAME"]++ // Database configuration+ config.DBName = envMap["DBNAME"]+ config.DBUser = envMap["DBUSER"]+ //config.DBPass = envMap["DBPASS"]++ // Redis configuration+ //config.RedisPass = envMap["REDISPASS"]+ config.RedisPort = envMap["REDIS_PORT"]++ // Mail port configuration+ if port := envMap["SMTP_PORT"]; port != "" {+ config.MailPorts.SMTP = parseInt(port, 25)+ }+ if port := envMap["SMTPS_PORT"]; port != "" {+ config.MailPorts.SMTPS = parseInt(port, 465)+ }+ if port := envMap["SUBMISSION_PORT"]; port != "" {+ config.MailPorts.Submission = parseInt(port, 587)+ }+ if port := envMap["IMAP_PORT"]; port != "" {+ config.MailPorts.IMAP = parseInt(port, 143)+ }+ if port := envMap["IMAPS_PORT"]; port != "" {+ config.MailPorts.IMAPS = parseInt(port, 993)+ }+ if port := envMap["POP_PORT"]; port != "" {+ config.MailPorts.POP = parseInt(port, 110)+ }+ if port := envMap["POPS_PORT"]; port != "" {+ config.MailPorts.POPS = parseInt(port, 995)+ }++ // Management port configuration+ if port := envMap["HTTP_PORT"]; port != "" {+ config.ManagePorts.HTTP = parseInt(port, 80)+ }+ if port := envMap["HTTPS_PORT"]; port != "" {+ config.ManagePorts.HTTPS = parseInt(port, 443)+ }+ config.ManagePorts.Command1 = fmt.Sprintf("cd %s && echo \"PORT\" | bash bm.sh change-port", projectPath)+ config.ManagePorts.Command2 = fmt.Sprintf("cd %s && echo \"PORT\" | bash bm.sh change-apply-ssl-port", projectPath)++ // Time zone configuration+ config.ManageTimeZone.TimeZone = envMap["TZ"]+ config.ManageTimeZone.Command = fmt.Sprintf("cd %s && echo \"TIME ZONE\" | bash bm.sh change-tz", projectPath)++ // Network configuration+ config.IPv4Network = envMap["IPV4_NETWORK"]+ config.Fail2ban = envMap["FAIL2BAN_INIT"] == "y"++ return config+}++// parseInt Safely convert string to integer+func parseInt(s string, defaultValue int) int {+ if v, err := strconv.Atoi(s); err == nil {+ return v+ }+ return defaultValue+}diff --git a/core/internal/controller/settings/settings_v1_get_system_config.go b/core/internal/controller/settings/settings_v1_get_system_config.goindex fcc88939..acbeec44 100644--- a/core/internal/controller/settings/settings_v1_get_system_config.go+++ b/core/internal/controller/settings/settings_v1_get_system_config.go@@ -2,6 +2,7 @@ package settingsimport ("billionmail-core/api/settings/v1"+ "billionmail-core/internal/service/public""context""github.com/gogf/gf/v2/errors/gerror")@@ -11,8 +12,8 @@ func (c *ControllerV1) GetSystemConfig(ctx context.Context, req *v1.GetSystemConenvMap, err := loadEnvFile()if err != nil {- res.SetError(gerror.New("failed to load environment variables"))- return res, err+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to read environment variable file: {}", err)))+ return res, nil}config := convertEnvToConfig(envMap)@@ -25,5 +26,6 @@ func (c *ControllerV1) GetSystemConfig(ctx context.Context, req *v1.GetSystemCon// TODO: Whitelist ipres.Data = config+ res.SetSuccess(public.LangCtx(ctx, "Successfully retrieved system configuration"))return res, nil}diff --git a/core/internal/controller/settings/settings_v1_set_ssl_config.go b/core/internal/controller/settings/settings_v1_set_ssl_config.gonew file mode 100644index 00000000..9afa6ea2--- /dev/null+++ b/core/internal/controller/settings/settings_v1_set_ssl_config.go@@ -0,0 +1,95 @@+package settings++import (+ "context"+ "crypto/x509"+ "encoding/pem"+ "os"+ "path/filepath"++ "billionmail-core/api/settings/v1"+ "billionmail-core/internal/consts"+ "billionmail-core/internal/service/public"+ "github.com/gogf/gf/v2/errors/gerror"+)++func (c *ControllerV1) SetSSLConfig(ctx context.Context, req *v1.SetSSLConfigReq) (res *v1.SetSSLConfigRes, err error) {+ res = &v1.SetSSLConfigRes{}++ certPath := public.AbsPath(filepath.Join(consts.SSL_PATH, "cert.pem"))+ keyPath := public.AbsPath(filepath.Join(consts.SSL_PATH, "key.pem"))++ // If the certificate data is empty, delete the certificate file+ if req.CertData == "" && req.KeyData == "" {+ // Delete the certificate file (if it exists)+ if err := os.Remove(certPath); err != nil && !os.IsNotExist(err) {+ res.Code = 500+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to delete certificate file: {}", err)))+ return res, nil+ }+ // Delete the key file (if it exists)+ if err := os.Remove(keyPath); err != nil && !os.IsNotExist(err) {+ res.Code = 500+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to delete key file: {}", err)))+ return res, nil+ }++ res.SetSuccess(public.LangCtx(ctx, "Certificate deleted successfully"))+ return res, nil+ }++ // Verify certificate data+ block, _ := pem.Decode([]byte(req.CertData))+ if block == nil {+ res.Code = 400+ res.SetError(gerror.New(public.LangCtx(ctx, "Invalid certificate data: {}", err)))+ return res, nil+ }++ // Verify certificate format+ if _, err := x509.ParseCertificate(block.Bytes); err != nil {+ res.Code = 400+ res.SetError(gerror.New(public.LangCtx(ctx, "Invalid certificate format: {}", err)))+ return res, nil+ }++ // Verify private key data+ block, _ = pem.Decode([]byte(req.KeyData))+ if block == nil {+ res.Code = 400+ res.SetError(gerror.New(public.LangCtx(ctx, "Invalid private key data: {}", err)))+ return res, nil+ }++ // Ensure the certificate directory exists+ if err := os.MkdirAll(filepath.Dir(certPath), 0755); err != nil {+ res.Code = 500+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to create certificate directory: {}", err)))+ return res, nil+ }++ // Write the new certificate file+ if err := os.WriteFile(certPath, []byte(req.CertData), 0644); err != nil {+ res.Code = 500+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to save certificate file: {}", err)))+ return res, nil+ }++ // Write the new private key file+ if err := os.WriteFile(keyPath, []byte(req.KeyData), 0600); err != nil {+ // If the private key writing fails, the already written certificate file needs to be deleted+ _ = os.Remove(certPath)+ res.Code = 500+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to save private key file: {}", err)))+ return res, nil+ }+ // Restart the container+ err = public.DockerApiFromCtx(ctx).RestartContainerByName(ctx, "billionmail-core-billionmail-1")+ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to restart container: {}", err)))+ return res, nil+ }++ res.SetSuccess(public.LangCtx(ctx, "SSL certificate updated successfully"))+ return res, nil+}diff --git a/core/internal/controller/settings/settings_v1_set_system_config.go b/core/internal/controller/settings/settings_v1_set_system_config.gonew file mode 100644index 00000000..45b60594--- /dev/null+++ b/core/internal/controller/settings/settings_v1_set_system_config.go@@ -0,0 +1,121 @@+package settings++import (+ "billionmail-core/internal/service/public"+ "context"+ "github.com/gogf/gf/v2/os/gfile"+ "os"+ "strings"++ "github.com/gogf/gf/v2/errors/gerror"++ "billionmail-core/api/settings/v1"+)++func (c *ControllerV1) SetSystemConfig(ctx context.Context, req *v1.SetSystemConfigReq) (res *v1.SetSystemConfigRes, err error) {+ res = &v1.SetSystemConfigRes{}++ envMap, err := loadEnvFile()+ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to read environment variable file: {}", err)))+ return res, nil+ }++ // 2. Update the configuration items that need to be modified+ modified := updateEnvMap(envMap, req)++ // 3. If there is a modification, write to the file+ if modified {++ if err := saveEnvFile(envMap); err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update environment variable file: {}", err)))+ return res, nil+ }++ err = public.DockerApiFromCtx(ctx).RestartContainerByName(ctx, "billionmail-core-billionmail-1")++ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to restart container: {}", err)))+ return res, nil+ }+ }++ res.SetSuccess(public.LangCtx(ctx, "Configuration updated successfully"))+ return res, nil+}++// updateEnvMap Update the environment variable map+func updateEnvMap(envMap map[string]string, req *v1.SetSystemConfigReq) bool {+ modified := false++ // Basic configuration+ if req.AdminUsername != "" && req.AdminUsername != envMap["ADMIN_USERNAME"] {+ envMap["ADMIN_USERNAME"] = req.AdminUsername+ modified = true++ }+ if req.AdminPassword != "" && req.AdminPassword != envMap["ADMIN_PASSWORD"] {+ envMap["ADMIN_PASSWORD"] = req.AdminPassword+ modified = true++ }+ if req.SafePath != "" && req.SafePath != envMap["SafePath"] {+ envMap["SafePath"] = req.SafePath+ modified = true++ }+ if req.Hostname != "" && req.Hostname != envMap["BILLIONMAIL_HOSTNAME"] {+ envMap["BILLIONMAIL_HOSTNAME"] = req.Hostname+ modified = true++ }++ return modified+}++// saveEnvFile Save the environment variable to the file+func saveEnvFile(envMap map[string]string) error {+ // 1. Read the original file content+ content, err := os.ReadFile(envPath)+ if err != nil {+ return err+ }++ // 2. Process by line+ var newLines []string+ lines := strings.Split(string(content), "\n")++ for _, line := range lines {+ line = strings.TrimSpace(line)+ // Keep comment lines and empty lines+ if line == "" || strings.HasPrefix(line, "#") {+ newLines = append(newLines, line)+ continue+ }++ // Parse key-value pairs+ parts := strings.SplitN(line, "=", 2)+ if len(parts) != 2 {+ newLines = append(newLines, line)+ continue+ }++ key := strings.TrimSpace(parts[0])+ // If envMap has this key, update the value+ if val, ok := envMap[key]; ok {++ newLines = append(newLines, key+"="+val)+ delete(envMap, key) // Mark as processed+ } else {+ newLines = append(newLines, line)+ }+ }++ // 3. Add new key-value pairs in envMap+ for k, v := range envMap {+ newLines = append(newLines, k+"="+v)+ }++ // 4. Write to file+ return gfile.PutContents(envPath, strings.Join(newLines, "\n"))+}diff --git a/core/internal/controller/settings/settings_v1_set_system_config_key.go b/core/internal/controller/settings/settings_v1_set_system_config_key.gonew file mode 100644index 00000000..27911ecf--- /dev/null+++ b/core/internal/controller/settings/settings_v1_set_system_config_key.go@@ -0,0 +1,100 @@+package settings++import (+ "context"++ "billionmail-core/api/settings/v1"+ "billionmail-core/internal/service/public"+ "github.com/gogf/gf/v2/errors/gerror"+ "github.com/gogf/gf/v2/frame/g"+ "strings"+)++func (c *ControllerV1) SetSystemConfigKey(ctx context.Context, req *v1.SetSystemConfigKeyReq) (res *v1.SetSystemConfigKeyRes, err error) {+ res = &v1.SetSystemConfigKeyRes{}++ // 1. Read the current .env file content+ envMap, err := loadEnvFile()+ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to read environment variable file: {}", err)))+ return res, nil+ }++ // 2. Find the corresponding environment variable name based on the key+ _, modified := convertJsonKeyToEnvKey(req.Key, req.Value, envMap)+ if !modified {+ res.SetError(gerror.New(public.LangCtx(ctx, "Invalid configuration item or value not changed")))+ return res, nil+ }++ // 3. If there is a modification, write to the file+ if err := saveEnvFile(envMap); err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to update environment variable file: {}", err)))+ return res, nil+ }++ // 4. Restart the container+ g.Log().Info(ctx, public.LangCtx(ctx, "Configuration updated, preparing to restart container"))+ err = public.DockerApiFromCtx(ctx).RestartContainerByName(ctx, "billionmail-core-billionmail-1")+ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to restart container: {}", err)))+ return res, nil+ }++ res.SetSuccess(public.LangCtx(ctx, "Configuration updated successfully"))+ return res, nil+}++// convertJsonKeyToEnvKey Convert JSON configuration key to environment variable key and update value+func convertJsonKeyToEnvKey(jsonKey string, value string, envMap map[string]string) (string, bool) {+ // JSON key to environment variable key mapping+ keyMapping := map[string]string{+ "admin_username": "ADMIN_USERNAME",+ "admin_password": "ADMIN_PASSWORD",+ "safe_path": "SafePath",+ "billionmail_hostname": "BILLIONMAIL_HOSTNAME",+ "db_name": "DBNAME",+ "db_user": "DBUSER",+ "db_pass": "DBPASS",+ "redis_pass": "REDISPASS",+ "redis_port": "REDIS_PORT",+ "smtp": "SMTP_PORT",+ "smtps": "SMTPS_PORT",+ "submission": "SUBMISSION_PORT",+ "imap": "IMAP_PORT",+ "imaps": "IMAPS_PORT",+ "pop": "POP_PORT",+ "pops": "POPS_PORT",+ "http": "HTTP_PORT",+ "https": "HTTPS_PORT",+ "timezone": "TZ",+ "ipv4_network": "IPV4_NETWORK",+ "fail2ban": "FAIL2BAN_INIT",+ }++ // Get the environment variable key name+ envKey, exists := keyMapping[strings.ToLower(jsonKey)]+ if !exists {+ return "", false+ }++ // Special handling for fail2ban values+ if envKey == "FAIL2BAN_INIT" {+ if value == "1" {+ value = "y"+ } else if value == "0" {+ value = "n"+ }+ }++ // Check if the value has changed+ if currentValue, exists := envMap[envKey]; exists && currentValue == value {+ return envKey, false+ }++ // Update the environment variable map+ envMap[envKey] = value+ g.Log().Debug(nil, "Update configuration item %s to: %s", envKey, value)++ return envKey, true+}diff --git a/core/internal/service/batch_mail/task_executor.go b/core/internal/service/batch_mail/task_executor.goindex 510b20ca..8f962160 100644--- a/core/internal/service/batch_mail/task_executor.go+++ b/core/internal/service/batch_mail/task_executor.go@@ -651,7 +651,7 @@ func (e *TaskExecutor) processRecipientBatch(ctx context.Context, task *entity.E// print task id//g.Log().Debug(ctx, "current task id", task.Id, "sender-", task.Addresser, "recipient-", recipientBak.Recipient)// personalize content- personalized := e.personalizeEmail(ctx, emailContent, task, recipientBak)+ personalized, _ := e.personalizeEmail(ctx, emailContent, task, recipientBak)//personalized := emailContent// send email@@ -860,47 +860,85 @@ func (e *TaskExecutor) getTemplateInfo(ctx context.Context, templateId int) (*enfunc (e *TaskExecutor) processEmailContent(ctx context.Context, content string, task *entity.EmailTask) string {// process unsubscribe linkif task.Unsubscribe == 1 {- // __UNSUBSCRIBE_URL__- if !strings.Contains(content, "__UNSUBSCRIBE_URL__") {+ // __UNSUBSCRIBE_URL__ {{ UnsubscribeURL }}+ if !strings.Contains(content, "__UNSUBSCRIBE_URL__") && !strings.Contains(content, "{{ UnsubscribeURL }}") {content = public.AddUnsubscribeButton(content)}- // get current domain- domain := domains.GetBaseURL()-- // generate unsubscribe URL placeholder- unsubscribeURL := fmt.Sprintf("%s/api/unsubscribe", domain)- groupURL := fmt.Sprintf("%s/api/unsubscribe/user_group", domain)- unsubscribeJumpURL := fmt.Sprintf("%s/unsubscribe.html?jwt=__JWT__&email=__EMAIL__&url_type=%s&url_unsubscribe=%s",- domain, groupURL, unsubscribeURL)-- content = strings.ReplaceAll(content, "__UNSUBSCRIBE_URL__", unsubscribeJumpURL)+ content = strings.ReplaceAll(content, "__UNSUBSCRIBE_URL__", "{{ UnsubscribeURL }}")}-return content}// personalizeEmail personalize email content-func (e *TaskExecutor) personalizeEmail(ctx context.Context, content string, task *entity.EmailTask, recipient *entity.RecipientInfo) string {- // process unsubscribe JWT+func (e *TaskExecutor) personalizeEmail(ctx context.Context, content string, task *entity.EmailTask, recipient *entity.RecipientInfo) (string, string) {++ var contact entity.Contact+ err := g.DB().Model("bm_contacts").Where("email", recipient.Recipient).Scan(&contact)+ if err != nil {+ g.Log().Error(ctx, "get contact info failed: %v", err)+ }++ var emailtask entity.EmailTask+ err = g.DB().Model("email_tasks").Where("id", task.Id).Scan(&emailtask)+ if err != nil {+ g.Log().Error(ctx, "get task info failed: %v", err)+ emailtask = *task+ }++ // Unsubscribe+ var renderedContent, renderedSubject string+ engine := GetTemplateEngine()+if task.Unsubscribe == 1 {- // generate JWT+ domain := domains.GetBaseURL()+ unsubscribeURL := fmt.Sprintf("%s/api/unsubscribe", domain)+ groupURL := fmt.Sprintf("%s/api/unsubscribe/user_group", domain)+jwtToken, err := GenerateUnsubscribeJWT(recipient.Recipient,task.TemplateId,task.Id,)+ if err != nil {+ g.Log().Error(ctx, "generate unsubscribe JWT failed: %v", err)+ jwtToken = ""+ }+ // generate unsubscribe URL+ unsubscribeJumpURL := fmt.Sprintf("%s/unsubscribe.html?jwt=%s&email=%s&url_type=%s&url_unsubscribe=%s",+ domain, jwtToken, recipient.Recipient, groupURL, unsubscribeURL)++ // render email content+ renderedContent, err = engine.RenderEmailTemplate(ctx, content, &contact, &emailtask, unsubscribeJumpURL)if err != nil {- g.Log().Error(ctx, "Failed to generate unsubscribe JWT: %v", err)- } else {- // replace JWT and email- content = strings.ReplaceAll(content, "__JWT__", jwtToken)- content = strings.ReplaceAll(content, "__EMAIL__", recipient.Recipient)+ g.Log().Error(ctx, "render email content failed: %v", err)+ renderedContent = content+ }++ // render email subject+ renderedSubject, err = engine.RenderEmailTemplate(ctx, emailtask.Subject, &contact, &emailtask, unsubscribeJumpURL)+ if err != nil {+ g.Log().Error(ctx, "render email subject failed: %v", err)+ renderedSubject = emailtask.Subject+ }+ } else {+ // if unsubscribe is not enabled, render email content+ renderedContent, err = engine.RenderEmailTemplate(ctx, content, &contact, &emailtask, "")+ if err != nil {+ g.Log().Error(ctx, "render email content failed: %v", err)+ renderedContent = content+ }++ // render email subject+ renderedSubject, err = engine.RenderEmailTemplate(ctx, emailtask.Subject, &contact, &emailtask, "")+ if err != nil {+ g.Log().Error(ctx, "render email subject failed: %v", err)+ renderedSubject = emailtask.Subject}}- return content+ return renderedContent, renderedSubject}// sendEmail send email@@ -917,8 +955,8 @@ func (e *TaskExecutor) sendEmail(ctx context.Context, task *entity.EmailTask, re// continue execution}- // senderder task.Addresser- // recipientipient recipient.Recipient+ // get rendered content and subject+ renderedContent, renderedSubject := e.personalizeEmail(ctx, content, task, recipient)sender, err := mail_service.NewEmailSenderWithLocal(task.Addresser)if err != nil {@@ -935,14 +973,13 @@ func (e *TaskExecutor) sendEmail(ctx context.Context, task *entity.EmailTask, re//Tracking emailsbaseURL := domains.GetBaseURL()- mail_tracker := maillog_stat.NewMailTracker(content, task.Id, messageID, recipient.Recipient, baseURL)+ mail_tracker := maillog_stat.NewMailTracker(renderedContent, task.Id, messageID, recipient.Recipient, baseURL)mail_tracker.TrackLinks()mail_tracker.AppendTrackingPixel()- content = mail_tracker.GetHTML()-- // create email message- message := mail_service.NewMessage(task.Subject, content)+ renderedContent = mail_tracker.GetHTML()+ // create email message with rendered subject+ message := mail_service.NewMessage(renderedSubject, renderedContent)message.SetMessageID(messageID)// set sender display namediff --git a/core/internal/service/batch_mail/template_render.go b/core/internal/service/batch_mail/template_render.gonew file mode 100644index 00000000..dd202982--- /dev/null+++ b/core/internal/service/batch_mail/template_render.go@@ -0,0 +1,153 @@+package batch_mail++import (+ "billionmail-core/internal/model/entity"+ "context"+ "github.com/gogf/gf/v2/frame/g"+ "github.com/gogf/gf/v2/os/gview"+ "strings"+)++// TemplateEngine+type TemplateEngine struct {+ view *gview.View+}++// NewTemplateEngine Create new template engine instance+func NewTemplateEngine() *TemplateEngine {+ view := gview.New()++ // register template functions+ view.BindFuncMap(g.Map{+ "get": func(m interface{}, key string) interface{} {+ // handle map+ if m, ok := m.(map[string]string); ok {+ return m[key]+ }+ // handle g.Map+ if m, ok := m.(g.Map); ok {+ return m[key]+ }+ return ""+ },+ })++ return &TemplateEngine{view: view}+}++// RenderTemplate Render template+func (e *TemplateEngine) RenderTemplate(ctx context.Context, content string, data g.Map) (string, error) {+ return e.view.ParseContent(ctx, content, data)+}++// RenderEmailTemplate Render email template+func (e *TemplateEngine) RenderEmailTemplate(ctx context.Context, content string, contact *entity.Contact, task *entity.EmailTask, unsubscribeURL string) (string, error) {+ // handle escape characters+ content = strings.NewReplacer(+ "\\r\\n", "\n",+ "\\n", "\n",+ "\\r", "\n",+ "\\t", "\t",+ ).Replace(content)++ // prepare subscriber data+ subscriberData := g.Map{+ "Email": "",+ "Active": 0,+ "Status": 0,+ "Attribs": g.Map{},+ }+ if contact != nil {+ subscriberData["Email"] = contact.Email+ subscriberData["Active"] = contact.Active+ subscriberData["Status"] = contact.Status+ if contact.Attribs != nil {+ subscriberData["Attribs"] = contact.Attribs+ }+ }++ // prepare task data+ taskData := g.Map{+ "Id": 0,+ "TaskName": "",+ "Addresser": "",+ "Subject": "",+ "FullName": "",+ "RecipientCount": 0,+ "TaskProcess": 0,+ "Pause": 0,+ "TemplateId": 0,+ "IsRecord": 0,+ "Unsubscribe": 0,+ "Threads": 0,+ "Etypes": "",+ "TrackOpen": 0,+ "TrackClick": 0,+ "StartTime": 0,+ "CreateTime": 0,+ "UpdateTime": 0,+ "Remark": "",+ "Active": 0,+ }+ if task != nil {+ taskData["Id"] = task.Id+ taskData["TaskName"] = task.TaskName+ taskData["Addresser"] = task.Addresser+ taskData["Subject"] = task.Subject+ taskData["FullName"] = task.FullName+ taskData["RecipientCount"] = task.RecipientCount+ taskData["TaskProcess"] = task.TaskProcess+ taskData["Pause"] = task.Pause+ taskData["TemplateId"] = task.TemplateId+ taskData["IsRecord"] = task.IsRecord+ taskData["Unsubscribe"] = task.Unsubscribe+ taskData["Threads"] = task.Threads+ taskData["Etypes"] = task.Etypes+ taskData["TrackOpen"] = task.TrackOpen+ taskData["TrackClick"] = task.TrackClick+ taskData["StartTime"] = task.StartTime+ taskData["CreateTime"] = task.CreateTime+ taskData["UpdateTime"] = task.UpdateTime+ taskData["Remark"] = task.Remark+ taskData["Active"] = task.Active+ }++ // prepare template data+ templateData := g.Map{+ "Subscriber": subscriberData,+ "Task": taskData,+ "UnsubscribeURL": unsubscribeURL,+ }++ // use template engine to render+ result, err := e.view.ParseContent(ctx, content, templateData)+ if err != nil {+ return "", err+ }++ return result, nil+}++// global template engine instance+var defaultEngine = NewTemplateEngine()++// GetTemplateEngine Get default template engine instance+func GetTemplateEngine() *TemplateEngine {+ return defaultEngine+}++// RenderGoTemplate For compatibility, package-level function+func RenderGoTemplate(tpl string, ctx interface{}, funcMap map[string]interface{}) (string, error) {+ engine := NewTemplateEngine()+ if funcMap != nil {+ engine.view.BindFuncMap(funcMap)+ }++ data := g.Map{+ "Subscriber": ctx.(entity.MailTemplateContext).Subscriber,+ "Task": ctx.(entity.MailTemplateContext).Task,+ "UnsubscribeURL": ctx.(entity.MailTemplateContext).UnsubscribeURL,+ }++ return engine.RenderTemplate(context.Background(), tpl, data)+}