Add optional subject param to tx API. Closes #2333.

This commit is contained in:
Kailash Nadh 2025-09-08 18:21:12 +05:30
parent ad66878ea0
commit 301c13a60d
2 changed files with 25 additions and 4 deletions

View file

@ -20,6 +20,7 @@ Allows sending transactional messages to one or more subscribers via a preconfig
| subscriber_ids | number\[\] | | Multiple subscriber IDs as an alternative to `subscriber_id`. |
| template_id | number | Yes | ID of the transactional template to be used for the message. |
| from_email | string | | Optional sender email. |
| subject | string | | Optional subject. If empty, the subject defined on the template is used |
| data | JSON | | Optional nested JSON map. Available in the template as `{{ .Tx.Data.* }}`. |
| headers | JSON\[\] | | Optional array of email headers. |
| messenger | string | | Messenger to send the message. Default is `email`. |

View file

@ -387,11 +387,11 @@ type TxMessage struct {
Headers Headers `json:"headers"`
ContentType string `json:"content_type"`
Messenger string `json:"messenger"`
Subject string `json:"subject"`
// File attachments added from multi-part form data.
Attachments []Attachment `json:"-"`
Subject string `json:"-"`
Body []byte `json:"-"`
Tpl *template.Template `json:"-"`
SubjectTpl *txttpl.Template `json:"-"`
@ -654,15 +654,35 @@ func (m *TxMessage) Render(sub Subscriber, tpl *Template) error {
copy(m.Body, b.Bytes())
b.Reset()
// Was a subject provided in the message?
var (
subjTpl *txttpl.Template
subject = m.Subject
)
if subject != "" {
if strings.Contains(m.Subject, "{{") {
// If the subject has a template string, render that.
s, err := txttpl.New(BaseTpl).Funcs(txttpl.FuncMap(nil)).Parse(m.Subject)
if err != nil {
return fmt.Errorf("error compiling subject: %v", err)
}
subjTpl = s
}
} else {
// Use the subject from the template.
subject = tpl.Subject
subjTpl = tpl.SubjectTpl
}
// If the subject is also a template, render that.
if tpl.SubjectTpl != nil {
if err := tpl.SubjectTpl.ExecuteTemplate(&b, BaseTpl, data); err != nil {
if subjTpl != nil {
if err := subjTpl.ExecuteTemplate(&b, BaseTpl, data); err != nil {
return err
}
m.Subject = b.String()
b.Reset()
} else {
m.Subject = tpl.Subject
m.Subject = subject
}
return nil