Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

Allow Go templates in campaign From header (#3056)

nemunaire033cc433b8c5
diff --git a/cmd/campaigns.go b/cmd/campaigns.go
index 423d82bb..e1202bd1 100644
--- a/cmd/campaigns.go
+++ b/cmd/campaigns.go
@@ -827,7 +827,7 @@ func (a *App) sendTestMessage(sub models.Subscriber, camp *models.Campaign) erro
func (a *App) validateCampaignFields(c campReq) (campReq, error) {
if c.FromEmail == "" {
c.FromEmail = a.cfg.FromEmail
- } else if !reFromAddress.Match([]byte(c.FromEmail)) {
+ } else if !models.HasTplExpr(c.FromEmail) && !reFromAddress.Match([]byte(c.FromEmail)) {
if _, err := a.importer.SanitizeEmail(c.FromEmail); err != nil {
return c, errors.New(a.i18n.T("campaigns.fieldInvalidFromEmail"))
}
diff --git a/docs/docs/content/templating.md b/docs/docs/content/templating.md
index 97b8fedc..58d9737e 100644
--- a/docs/docs/content/templating.md
+++ b/docs/docs/content/templating.md
@@ -19,6 +19,7 @@ There are several template functions and expressions that can be used in campaig
- Campaign body and alt body
- Campaign subject
+- Campaign From address (for example, `{{ .Subscriber.Attribs.sender_name }} <[email protected]>`)
- Campaign headers
- Transactional message body and alt body
- Transactional message subject
diff --git a/internal/manager/message.go b/internal/manager/message.go
index e6cd7b5b..d4c9788c 100644
--- a/internal/manager/message.go
+++ b/internal/manager/message.go
@@ -42,6 +42,15 @@ func (m *CampaignMessage) render() error {
out.Reset()
}
+ // Render the From header if it's a template.
+ if m.Campaign.FromEmailTpl != nil {
+ if err := m.Campaign.FromEmailTpl.ExecuteTemplate(&out, models.ContentTpl, m); err != nil {
+ return fmt.Errorf("error rendering from: %w", err)
+ }
+ m.from = out.String()
+ out.Reset()
+ }
+
// Compile the main template.
if err := m.Campaign.Tpl.ExecuteTemplate(&out, models.BaseTpl, m); err != nil {
return err
diff --git a/models/campaigns.go b/models/campaigns.go
index 4bdde58f..74fa2a5d 100644
--- a/models/campaigns.go
+++ b/models/campaigns.go
@@ -82,9 +82,10 @@ type Campaign struct {
ArchiveTemplateBody string `db:"archive_template_body" json:"-"`
Tpl *template.Template `json:"-"`
SubjectTpl *txttpl.Template `json:"-"`
+ FromEmailTpl *txttpl.Template `json:"-"`
AltBodyTpl *template.Template `json:"-"`
- // HeaderTpls is holds optionally {{ templated }} campaign headers.
+ // HeaderTpls holds optionally {{ templated }} campaign headers.
HeaderTpls []map[string]*txttpl.Template `json:"-"`
// List of media (attachment) IDs obtained from the next-campaign query
@@ -186,19 +187,15 @@ func (camps Campaigns) LoadStats(stmt *sqlx.Stmt) error {
// CompileTemplate compiles a campaign body template into its base
// 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 hasTplExpr(c.Subject) {
- subj := c.Subject
- for _, r := range regTplFuncs {
- subj = r.regExp.ReplaceAllString(subj, r.replace)
- }
+ var err error
+ c.SubjectTpl, err = compileTxtTpl("subject", c.Subject, f)
+ if err != nil {
+ return err
+ }
- var txtFuncs map[string]any = f
- subjTpl, err := txttpl.New(ContentTpl).Funcs(txtFuncs).Parse(subj)
- if err != nil {
- return fmt.Errorf("error compiling subject: %v", err)
- }
- c.SubjectTpl = subjTpl
+ c.FromEmailTpl, err = compileTxtTpl("from", c.FromEmail, f)
+ if err != nil {
+ return err
}
// Compile the base template.
@@ -244,7 +241,7 @@ func (c *Campaign) CompileTemplate(f template.FuncMap) error {
}
c.Tpl = out
- if hasTplExpr(c.AltBody.String) {
+ if HasTplExpr(c.AltBody.String) {
b := c.AltBody.String
for _, r := range regTplFuncs {
b = r.regExp.ReplaceAllString(b, r.replace)
@@ -256,42 +253,46 @@ 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) {
+ // Rebuild header templates in case the campaign is being recompiled.
+ c.HeaderTpls = nil
+ for i, set := range c.Headers {
+ for hdr, val := range set {
+ tpl, err := compileTxtTpl(fmt.Sprintf("header %q", hdr), val, f)
+ if err != nil {
+ return err
+ }
+ if tpl == nil {
+ continue
+ }
+
+ if c.HeaderTpls == nil {
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
+ if c.HeaderTpls[i] == nil {
+ c.HeaderTpls[i] = make(map[string]*txttpl.Template)
}
+ 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, "}}")
+func compileTxtTpl(label, val string, f template.FuncMap) (*txttpl.Template, error) {
+ if !HasTplExpr(val) {
+ return nil, nil
+ }
+
+ for _, r := range regTplFuncs {
+ val = r.regExp.ReplaceAllString(val, r.replace)
+ }
+
+ tpl, err := txttpl.New(ContentTpl).Funcs(f).Parse(val)
+ if err != nil {
+ return nil, fmt.Errorf("error compiling %s: %v", label, err)
+ }
+
+ return tpl, nil
}
// ConvertContent converts a campaign's body from one format to another,
@@ -317,3 +318,9 @@ func (c *Campaign) ConvertContent(from, to string) (string, error) {
return out, 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, "}}")
+}
diff --git a/models/messages.go b/models/messages.go
index 5dad966e..f502dabe 100644
--- a/models/messages.go
+++ b/models/messages.go
@@ -90,7 +90,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 != "" && hasTplExpr(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)
@@ -108,7 +108,7 @@ func (m *TxMessage) Render(sub Subscriber, tpl *Template, funcs txttpl.FuncMap)
subject = m.Subject
)
if subject != "" {
- if hasTplExpr(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.go
index b48009cf..0e7fa7f7 100644
--- a/models/templates.go
+++ b/models/templates.go
@@ -45,10 +45,10 @@ func (t *Template) Compile(f template.FuncMap) error {
t.Tpl = tpl
// If the subject line has a template string, compile it.
- if hasTplExpr(t.Subject) {
+ if HasTplExpr(t.Subject) {
subj := t.Subject
- subjTpl, err := txttpl.New(BaseTpl).Funcs(txttpl.FuncMap(f)).Parse(subj)
+ subjTpl, err := txttpl.New(BaseTpl).Funcs(f).Parse(subj)
if err != nil {
return fmt.Errorf("error compiling subject: %v", err)
}