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

Send email api adds custom attribute rendering

lotk9cf0b82769c6
diff --git a/core/api/batch_mail/v1/api_mail.go b/core/api/batch_mail/v1/api_mail.go
index ab61caee..3b410bae 100644
--- a/core/api/batch_mail/v1/api_mail.go
+++ b/core/api/batch_mail/v1/api_mail.go
@@ -5,32 +5,6 @@ import (
"github.com/gogf/gf/v2/frame/g"
)
-// `CREATE TABLE IF NOT EXISTS api_templates (
-// id SERIAL PRIMARY KEY,
-// api_key VARCHAR(64) NOT NULL,
-// api_name VARCHAR(255) NOT NULL,
-// template_id INTEGER NOT NULL,
-// subject TEXT NOT NULL,
-// addresser VARCHAR(320) NOT NULL,
-// full_name VARCHAR(255),
-// unsubscribe SMALLINT NOT NULL DEFAULT 0,
-// track_open SMALLINT NOT NULL DEFAULT 1,
-// track_click SMALLINT NOT NULL DEFAULT 1,
-// active SMALLINT NOT NULL DEFAULT 1,
-// create_time INTEGER NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()),
-// update_time INTEGER NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()),
-// UNIQUE(api_key)
-// )`,
-
-// `CREATE TABLE IF NOT EXISTS api_mail_logs (
-// id SERIAL PRIMARY KEY,
-// api_id INTEGER NOT NULL,
-// recipient VARCHAR(320) NOT NULL,
-// message_id TEXT NOT NULL,
-// addresser VARCHAR(320) NOT NULL,
-// send_time INTEGER NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())
-// )`,
-
type ApiTemplates struct {
Id int `json:"id" dc:"id"`
ApiKey string `json:"api_key" dc:"api key"`
@@ -167,9 +141,10 @@ type ApiTemplatesDeleteRes struct {
type ApiMailSendReq struct {
g.Meta `path:"/batch_mail/api/send" method:"post" tags:"ApiMail" summary:"call api send mail"`
- ApiKey string `json:"x-api-key" dc:"API Key" in:"header"`
- Addresser string `json:"addresser" dc:"addresser"`
- Recipient string `json:"recipient" dc:"recipient"`
+ ApiKey string `json:"x-api-key" dc:"API Key" in:"header"`
+ Addresser string `json:"addresser" dc:"addresser"`
+ Recipient string `json:"recipient" dc:"recipient"`
+ Attribs map[string]string `json:"attribs" dc:"Custom properties"`
}
type ApiMailSendRes struct {
diff --git a/core/internal/controller/batch_mail/batch_mail_v1_api_mail_send.go b/core/internal/controller/batch_mail/batch_mail_v1_api_mail_send.go
index 039f8a81..578a0149 100644
--- a/core/internal/controller/batch_mail/batch_mail_v1_api_mail_send.go
+++ b/core/internal/controller/batch_mail/batch_mail_v1_api_mail_send.go
@@ -77,7 +77,7 @@ func (c *ControllerV1) ApiMailSend(ctx context.Context, req *v1.ApiMailSendReq)
}
// 6. Join the sender queue
- err = recordApiMailLog(ctx, apiTemplate, req.Recipient, req.Addresser)
+ err = recordApiMailLog(ctx, apiTemplate, req.Recipient, req.Addresser, req.Attribs)
if err != nil {
res.Code = 1005
res.SetError(gerror.New(public.LangCtx(ctx, "Failed to record email log: {}", err.Error())))
@@ -89,7 +89,7 @@ func (c *ControllerV1) ApiMailSend(ctx context.Context, req *v1.ApiMailSendReq)
}
// 记录到日志表,状态为待发送
-func recordApiMailLog(ctx context.Context, apiTemplate *entity.ApiTemplates, recipient, addresser string) error {
+func recordApiMailLog(ctx context.Context, apiTemplate *entity.ApiTemplates, recipient, addresser string, attribs map[string]string) error {
// 生成消息ID
sender, err := mail_service.NewEmailSenderWithLocal(addresser)
@@ -112,6 +112,7 @@ func recordApiMailLog(ctx context.Context, apiTemplate *entity.ApiTemplates, rec
"error_message": "",
"send_time": 0,
"create_time": now,
+ "attribs": attribs,
})
return err
@@ -188,17 +189,36 @@ func ensureContactAndGroup(ctx context.Context, email string, apiId int) (entity
}
groupId, _ := groupResult.LastInsertId()
group.Id = int(groupId)
+ } else {
+
+ count, err := g.DB().Model("bm_contacts").
+ Where("email", email).
+ Where("group_id", group.Id).
+ Where("active", 0).
+ Count()
+ if err != nil {
+ return contact, fmt.Errorf("failed to check unsubscribe: %w", err)
+ }
+ if count > 0 {
+ return contact, fmt.Errorf("the recipient has unsubscribed from the current group and cannot send")
+ }
}
- contactResult, err := g.DB().Model("bm_contacts").Insert(g.Map{
+
+ contactData := g.Map{
"email": email,
"group_id": group.Id,
"active": 1,
"status": 1,
"create_time": now,
- })
+ }
+ contactResult, err := g.DB().Model("bm_contacts").
+ Data(contactData).
+ OnConflict("email,group_id").
+ Save()
if err != nil {
return contact, err
}
+
contactId, _ := contactResult.LastInsertId()
contact.Id = int(contactId)
contact.Email = email
diff --git a/core/internal/service/batch_mail/api_mail_send.go b/core/internal/service/batch_mail/api_mail_send.go
index 12a0fcfe..82248f52 100644
--- a/core/internal/service/batch_mail/api_mail_send.go
+++ b/core/internal/service/batch_mail/api_mail_send.go
@@ -34,6 +34,7 @@ type ApiMailLog struct {
Recipient string
Addresser string
MessageId string
+ Attribs map[string]string `json:"attribs"`
}
// Cache data structure
@@ -152,7 +153,7 @@ func ProcessApiMailQueueWithLock(ctx context.Context) {
return
}
if !locked {
- g.Log().Info(ctx, "Another instance is processing the mail queue")
+ g.Log().Warning(ctx, "Another instance is processing the mail queue")
return
}
@@ -337,6 +338,14 @@ func updateLogStatus(ctx context.Context, id int64, status int, errorMsg string)
// process mail content and subject
func processMailContentAndSubject(ctx context.Context, content, subject string, apiTemplate *entity.ApiTemplates, contact entity.Contact, log ApiMailLog) (string, string) {
// unsubscribe link processing
+
+ apiAttribs := make(map[string]interface{})
+ if log.Attribs != nil {
+ for k, v := range log.Attribs {
+ apiAttribs[k] = v
+ }
+ }
+
if apiTemplate.Unsubscribe == 1 {
if !strings.Contains(content, "__UNSUBSCRIBE_URL__") && !strings.Contains(content, "{{ UnsubscribeURL . }}") {
content = public.AddUnsubscribeButton(content)
@@ -349,11 +358,11 @@ func processMailContentAndSubject(ctx context.Context, content, subject string,
if contact.Id > 0 {
engine := GetTemplateEngine()
- renderedContent, err := engine.RenderEmailTemplate(ctx, content, &contact, nil, unsubscribeJumpURL)
+ renderedContent, err := engine.RenderEmailTemplateWithAPI(ctx, content, &contact, nil, unsubscribeJumpURL, apiAttribs)
if err == nil {
content = renderedContent
}
- renderedSubject, err := engine.RenderEmailTemplate(ctx, subject, &contact, nil, unsubscribeJumpURL)
+ renderedSubject, err := engine.RenderEmailTemplateWithAPI(ctx, subject, &contact, nil, unsubscribeJumpURL, apiAttribs)
if err == nil {
subject = renderedSubject
}
@@ -362,11 +371,11 @@ func processMailContentAndSubject(ctx context.Context, content, subject string,
}
} else if contact.Id > 0 {
engine := GetTemplateEngine()
- renderedContent, err := engine.RenderEmailTemplate(ctx, content, &contact, nil, "")
+ renderedContent, err := engine.RenderEmailTemplateWithAPI(ctx, content, &contact, nil, "", apiAttribs)
if err == nil {
content = renderedContent
}
- renderedSubject, err := engine.RenderEmailTemplate(ctx, subject, &contact, nil, "")
+ renderedSubject, err := engine.RenderEmailTemplateWithAPI(ctx, subject, &contact, nil, "", apiAttribs)
if err == nil {
subject = renderedSubject
}
diff --git a/core/internal/service/batch_mail/template_render.go b/core/internal/service/batch_mail/template_render.go
index 3ab2a507..04c5d98d 100644
--- a/core/internal/service/batch_mail/template_render.go
+++ b/core/internal/service/batch_mail/template_render.go
@@ -50,8 +50,12 @@ func (e *TemplateEngine) RenderTemplate(ctx context.Context, content string, dat
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) {
+ return e.RenderEmailTemplateWithAPI(ctx, content, contact, task, unsubscribeURL, nil)
+}
+
+// RenderEmailTemplate Render email template
+func (e *TemplateEngine) RenderEmailTemplateWithAPI(ctx context.Context, content string, contact *entity.Contact, task *entity.EmailTask, unsubscribeURL string, apiAttribs map[string]interface{}) (string, error) {
// handle escape characters
content = strings.NewReplacer(
"\\r\\n", "\n",
@@ -75,6 +79,18 @@ func (e *TemplateEngine) RenderEmailTemplate(ctx context.Context, content string
}
+ // prepare api data
+ apiData := make(map[string]interface{})
+ if contact != nil {
+ // Custom properties are added directly to subscriberData
+ if apiAttribs != nil {
+ for k, v := range apiAttribs {
+ apiData[k] = v
+ }
+ }
+
+ }
+
// prepare task data
taskData := g.Map{
"Id": 0,
@@ -126,6 +142,7 @@ func (e *TemplateEngine) RenderEmailTemplate(ctx context.Context, content string
"Subscriber": subscriberData,
"Task": taskData,
"UnsubscribeURL": unsubscribeURL,
+ "API": apiAttribs,
}
// use template engine to render
@@ -144,19 +161,3 @@ var defaultEngine = NewTemplateEngine()
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)
-}
diff --git a/core/internal/service/database_initialization/batch_mail.go b/core/internal/service/database_initialization/batch_mail.go
index 9c76ce7e..c8277f85 100644
--- a/core/internal/service/database_initialization/batch_mail.go
+++ b/core/internal/service/database_initialization/batch_mail.go
@@ -15,6 +15,16 @@ func init() {
description TEXT,
create_time INTEGER NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()),
update_time INTEGER NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()),
+ token VARCHAR(30) NOT NULL DEFAULT '',
+ double_optin SMALLINT NOT NULL DEFAULT 0, -- 0: Single Opt-in, 1: Double Opt-in
+ welcome_mail_html TEXT DEFAULT '', -- HTML content for welcome email
+ welcome_mail_drag TEXT DEFAULT '', -- Drag-and-drop content for welcome email
+ confirm_mail_html TEXT DEFAULT '', -- HTML content for confirmation email
+ confirm_mail_drag TEXT DEFAULT '', -- Drag-and-drop content for confirmation email
+ success_url TEXT DEFAULT '', -- URL to redirect after successful subscription
+ confirm_url TEXT DEFAULT '', -- URL to redirect after confirmation
+ already_url TEXT DEFAULT '', -- URL to redirect if already subscribed
+ subscribe_form TEXT DEFAULT '', -- HTML form for subscription
UNIQUE(name)
)`,
@@ -128,6 +138,7 @@ func init() {
addresser VARCHAR(320) NOT NULL,
status SMALLINT NOT NULL DEFAULT 0, -- 0:to send, 2:send, 3:send failed
error_message TEXT,
+ attribs JSONB DEFAULT '{}'::jsonb,
send_time INTEGER NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW()),
create_time INTEGER NOT NULL DEFAULT EXTRACT(EPOCH FROM NOW())
@@ -159,16 +170,27 @@ func init() {
return
}
}
- // bm_contacts attribs
+ // bm_contacts
_ = AddColumnIfNotExists("bm_contacts", "attribs", "JSONB", "'{}'::jsonb", false)
- // bm_contacts status
_ = AddColumnIfNotExists("bm_contacts", "status", "INTEGER", "0", false)
- // api_mail_logs status
+
+ // api_mail_logs
_ = AddColumnIfNotExists("api_mail_logs", "status", "SMALLINT", "0", true)
- // api_mail_logs error_message
_ = AddColumnIfNotExists("api_mail_logs", "error_message", "TEXT", "''", false)
- // api_mail_logs create_time
_ = AddColumnIfNotExists("api_mail_logs", "create_time", "INTEGER", "EXTRACT(EPOCH FROM NOW())", true)
+ _ = AddColumnIfNotExists("api_mail_logs", "attribs", "JSONB", "'{}'::jsonb", false)
+
+ //bm_contact_groups
+ _ = AddColumnIfNotExists("bm_contact_groups", "token", "VARCHAR(30)", "''", true)
+ _ = AddColumnIfNotExists("bm_contact_groups", "double_optin", "SMALLINT", "0", true)
+ _ = AddColumnIfNotExists("bm_contact_groups", "success_url", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("bm_contact_groups", "confirm_url", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("bm_contact_groups", "already_url", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("bm_contact_groups", "subscribe_form", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("bm_contact_groups", "welcome_mail_html", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("bm_contact_groups", "welcome_mail_drag", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("bm_contact_groups", "confirm_mail_html", "TEXT", "''", false)
+ _ = AddColumnIfNotExists("bm_contact_groups", "confirm_mail_drag", "TEXT", "''", false)
g.Log().Info(context.Background(), "Batch mail tables initialized successfully")
})