High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
JavaScript campaigncampaign-managementemail-marketingemail-subscriptionlistmonkmailing-listnewsletternewsletter-managementnewsletter-softwareself-hostedsms-gatewaysmtptransactional-emails
Add template expression support to campaign custom headers like subjects.
Kailash Nadhee099f6a5600
diff --git a/docs/docs/content/apis/campaigns.md b/docs/docs/content/apis/campaigns.mdindex e1034971..58faaa6f 100644--- a/docs/docs/content/apis/campaigns.md+++ b/docs/docs/content/apis/campaigns.md@@ -304,7 +304,7 @@ Create a new campaign.| messenger | string | | 'email' or a custom messenger defined in settings. Defaults to 'email' if not provided. || template_id | number | | Template ID to use. Defaults to default template if not provided. || tags | string\[\] | | Tags to mark campaign. |-| headers | JSON | | Key-value pairs to send as SMTP headers. Example: \[{"x-custom-header": "value"}\]. |+| headers | JSON | | Key-value pairs to send as SMTP headers. Supports template expressions (e.g., `{{ .Subscriber.UUID }}`). Example: \[{"x-custom-header": "value"}, {"x-subscriber": "{{ .Subscriber.UUID }}"}\]. || attribs | JSON | | Optional JSON object attributes that can be used in the campaign message template. Example `{"location": "Somewhere"}` |##### Example requestdiff --git a/docs/docs/content/templating.md b/docs/docs/content/templating.mdindex 1dd56132..5d229c9a 100644--- a/docs/docs/content/templating.md+++ b/docs/docs/content/templating.md@@ -15,7 +15,13 @@ Transactional templates are used for sending arbitrary transactional messages us## Template expressions-There are several template functions and expressions that can be used in campaign and template bodies. They are written in the form `{{ .Subscriber.Email }}`, that is, an expression between double curly braces `{{` and `}}`.+There are several template functions and expressions that can be used in campaign and template bodies. They are written in the form `{{ .Subscriber.Email }}`, that is, an expression between double curly braces `{{` and `}}`. Template expressions are supported in:++- Campaign body and alt body+- Campaign subject+- Campaign headers+- Transactional message body and alt body+- Transactional message subject### Subscriber fields@@ -53,6 +59,7 @@ There are several template functions and expressions that can be used in campaig| `{{ OptinURL }}` | URL to the double opt-in confirmation page. || `{{ Safe "<!-- comment -->" }}` | Add any HTML code as it is. |+### Sprig functionslistmonk integrates the Sprig library that offers 100+ utility functions for working with strings, numbers, dates etc. that can be used in templating. Refer to the [Sprig documentation](https://masterminds.github.io/sprig/) for the full list of functions.diff --git a/i18n/en.json b/i18n/en.jsonindex 349d4aa9..40e0146a 100644--- a/i18n/en.json+++ b/i18n/en.json@@ -38,7 +38,7 @@"campaigns.contentHelp": "Content here","campaigns.continue": "Continue","campaigns.copyOf": "Copy of {name}",- "campaigns.customHeadersHelp": "Array of custom headers to attach to outgoing messages. eg: [{\"X-Custom\": \"value\"}, {\"X-Custom2\": \"value\"}]",+ "campaigns.customHeadersHelp": "Array of custom headers to attach to outgoing messages. Supports template expressions (e.g., {{ .Subscriber.Attribs.city }}). eg: [{\"X-Custom\": \"value\"}, {\"X-Custom2\": \"{{ .Subscriber.UUID }}\"}]","campaigns.dateAndTime": "Date and time","campaigns.ended": "Ended","campaigns.errorSendTest": "Error sending test: {error}",diff --git a/internal/manager/manager.go b/internal/manager/manager.goindex 3ff32fa4..dc8a65d2 100644--- a/internal/manager/manager.go+++ b/internal/manager/manager.go@@ -106,6 +106,7 @@ type CampaignMessage struct {body []bytealtBody []byteunsubURL string+ headers models.Headerspipe *pipe}@@ -508,11 +509,9 @@ func (m *Manager) worker() {}// Attach any custom headers.- if len(msg.Campaign.Headers) > 0 {- for _, set := range msg.Campaign.Headers {- for hdr, val := range set {- h.Add(hdr, val)- }+ for _, set := range msg.headers {+ for hdr, val := range set {+ h.Add(hdr, val)}}diff --git a/internal/manager/message.go b/internal/manager/message.goindex 3a9d64c2..e6cd7b5b 100644--- a/internal/manager/message.go+++ b/internal/manager/message.go@@ -61,6 +61,29 @@ func (m *CampaignMessage) render() error {}}+ // If there are templated headers, compile them.+ if m.Campaign.HeaderTpls == nil {+ m.headers = m.Campaign.Headers+ } else {+ hdrOut := bytes.Buffer{}+ m.headers = make(models.Headers, len(m.Campaign.Headers))+ for i, set := range m.Campaign.Headers {+ m.headers[i] = make(map[string]string, len(set))+ for hdr, val := range set {+ tpl := m.Campaign.HeaderTpls[i][hdr]+ if tpl == nil {+ m.headers[i][hdr] = val+ continue+ }+ hdrOut.Reset()+ if err := tpl.ExecuteTemplate(&hdrOut, models.ContentTpl, m); err != nil {+ return fmt.Errorf("error rendering header %q: %v", hdr, err)+ }+ m.headers[i][hdr] = hdrOut.String()+ }+ }+ }+return nil}diff --git a/models/campaigns.go b/models/campaigns.goindex b7f38f65..43e9b6a8 100644--- a/models/campaigns.go+++ b/models/campaigns.go@@ -67,6 +67,9 @@ type Campaign struct {SubjectTpl *txttpl.Template `json:"-"`AltBodyTpl *template.Template `json:"-"`+ // HeaderTpls is holds optionally {{ templated }} campaign headers.+ HeaderTpls []map[string]*txttpl.Template `json:"-"`+// List of media (attachment) IDs obtained from the next-campaign query// while sending a campaign.MediaIDs pq.Int64Array `json:"-" db:"media_id"`@@ -137,7 +140,7 @@ func (camps Campaigns) LoadStats(stmt *sqlx.Stmt) error {// template and sets the resultant template to Campaign.Tpl.func (c *Campaign) CompileTemplate(f template.FuncMap) error {// If the subject line has a template string, compile it.- if strings.Contains(c.Subject, "{{") {+ if hasTplExpr(c.Subject) {subj := c.Subjectfor _, r := range regTplFuncs {subj = r.regExp.ReplaceAllString(subj, r.replace)@@ -194,7 +197,7 @@ func (c *Campaign) CompileTemplate(f template.FuncMap) error {}c.Tpl = out- if strings.Contains(c.AltBody.String, "{{") {+ if hasTplExpr(c.AltBody.String) {b := c.AltBody.Stringfor _, r := range regTplFuncs {b = r.regExp.ReplaceAllString(b, r.replace)@@ -206,9 +209,44 @@ func (c *Campaign) CompileTemplate(f template.FuncMap) error {c.AltBodyTpl = bTpl}+ // Compile any header values that contain template expressions.+ for _, set := range c.Headers {+ for _, val := range set {+ if hasTplExpr(val) {+ c.HeaderTpls = make([]map[string]*txttpl.Template, len(c.Headers))+ break+ }+ }+ if c.HeaderTpls != nil {+ break+ }+ }+ if c.HeaderTpls != nil {+ var txtFuncs map[string]any = f+ for i, set := range c.Headers {+ c.HeaderTpls[i] = make(map[string]*txttpl.Template, len(set))+ for hdr, val := range set {+ if !hasTplExpr(val) {+ continue+ }+ tpl, err := txttpl.New(ContentTpl).Funcs(txtFuncs).Parse(val)+ if err != nil {+ return fmt.Errorf("error compiling header %q: %v", hdr, err)+ }+ c.HeaderTpls[i][hdr] = tpl+ }+ }+ }+return nil}+// hasTplExpr checks whether a given string has a Go template expression with {{ and }}.+func hasTplExpr(s string) bool {+ _, after, ok := strings.Cut(s, "{{")+ return ok && strings.Contains(after, "}}")+}+// ConvertContent converts a campaign's body from one format to another,// for example, Markdown to HTML.func (c *Campaign) ConvertContent(from, to string) (string, error) {diff --git a/models/messages.go b/models/messages.goindex fe80c688..7914dde5 100644--- a/models/messages.go+++ b/models/messages.go@@ -5,7 +5,6 @@ import ("fmt""html/template""net/textproto"- "strings"txttpl "text/template")@@ -87,7 +86,7 @@ func (m *TxMessage) Render(sub Subscriber, tpl *Template, funcs txttpl.FuncMap)b.Reset()// Render alt body if it has any templating strings.- if m.AltBody != "" && strings.Contains(m.AltBody, "{{") {+ if m.AltBody != "" && hasTplExpr(m.AltBody) {t, err := txttpl.New(BaseTpl).Funcs(funcs).Parse(m.AltBody)if err != nil {return fmt.Errorf("error compiling alt body: %v", err)@@ -105,7 +104,7 @@ func (m *TxMessage) Render(sub Subscriber, tpl *Template, funcs txttpl.FuncMap)subject = m.Subject)if subject != "" {- if strings.Contains(m.Subject, "{{") {+ if hasTplExpr(m.Subject) {// If the subject has a template string, render that.s, err := txttpl.New(BaseTpl).Funcs(funcs).Parse(m.Subject)if err != nil {diff --git a/models/templates.go b/models/templates.goindex b203ec32..7d45f21e 100644--- a/models/templates.go+++ b/models/templates.go@@ -3,7 +3,6 @@ package modelsimport ("fmt""html/template"- "strings"txttpl "text/template""time"@@ -45,7 +44,7 @@ func (t *Template) Compile(f template.FuncMap) error {t.Tpl = tpl// If the subject line has a template string, compile it.- if strings.Contains(t.Subject, "{{") {+ if hasTplExpr(t.Subject) {subj := t.SubjectsubjTpl, err := txttpl.New(BaseTpl).Funcs(txttpl.FuncMap(f)).Parse(subj)