Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
feat(email): accept a template name or ID in template, deprecate template_id
Jonas Kaninda13d730a956f6
diff --git a/internal/handlers/email_handler.go b/internal/handlers/email_handler.goindex 6e04fde..3273f81 100644--- a/internal/handlers/email_handler.go+++ b/internal/handlers/email_handler.go@@ -86,10 +86,10 @@ func (h *EmailHandler) redactContent() bool {type PreviewEmailRequest struct {Body struct {- TemplateID *uint `json:"template_id,omitempty" doc:"Template ID (preferred)"`- Template string `json:"template" doc:"Template name (fallback when template_id is not provided)"`- Language string `json:"language" doc:"Language code for localization"`- TemplateData map[string]any `json:"template_data" doc:"Variables to inject into the template"`+ Template email.TemplateRef `json:"template" doc:"Template name or ID. A name is matched first; a value that is all digits and matches no name is looked up as an ID."`+ TemplateID *uint `json:"template_id,omitempty" deprecated:"true" doc:"Deprecated: pass the ID in template instead. Used only when template is empty."`+ Language string `json:"language" doc:"Language code for localization"`+ TemplateData map[string]any `json:"template_data" doc:"Variables to inject into the template"`} `json:"body"`}diff --git a/internal/services/email/service.go b/internal/services/email/service.goindex 6b2cb2a..60d434f 100644--- a/internal/services/email/service.go+++ b/internal/services/email/service.go@@ -389,8 +389,8 @@ func (s *Service) resolveUnsubscribe(scope repositories.ResourceScope, req *Send}type SendTemplateRequest struct {- TemplateID *uint `json:"template_id,omitempty" doc:"Template ID (preferred, uses primary key index)"`- Template string `json:"template" doc:"Template name (fallback when template_id is not provided)"`+ Template TemplateRef `json:"template" doc:"Template name or ID. A name is matched first; a value that is all digits and matches no name is looked up as an ID."`+ TemplateID *uint `json:"template_id,omitempty" deprecated:"true" doc:"Deprecated: pass the ID in template instead. Used only when template is empty."`Language string `json:"language" doc:"Language code for template localization (BCP 47 / ISO 639-1, e.g. en, fr, fr-CA). Falls back to base language, the template default, then en."`From string `json:"from" doc:"Sender address. Accepts a plain address ([email protected]) or RFC 5322 display-name format (Acme <[email protected]>)."`To []string `json:"to" required:"true" minItems:"1" doc:"Recipient addresses. Each accepts a plain address or RFC 5322 display-name format (e.g. Jonas <[email protected]>)."`@@ -405,8 +405,8 @@ type SendResponse struct {}type BatchRequest struct {- TemplateID *uint `json:"template_id,omitempty" doc:"Template ID (preferred, uses primary key index)"`- Template string `json:"template" doc:"Template name (fallback when template_id is not provided)"`+ Template TemplateRef `json:"template" doc:"Template name or ID. A name is matched first; a value that is all digits and matches no name is looked up as an ID."`+ TemplateID *uint `json:"template_id,omitempty" deprecated:"true" doc:"Deprecated: pass the ID in template instead. Used only when template is empty."`Language string `json:"language" doc:"Default language for the batch (BCP 47 / ISO 639-1, e.g. en, fr, fr-CA). Each recipient can override via recipients[].language."`From string `json:"from" doc:"Sender address. Accepts a plain address ([email protected]) or RFC 5322 display-name format (Acme <[email protected]>)."`Recipients []BatchRecipient `json:"recipients" required:"true" minItems:"1"`@@ -607,7 +607,7 @@ func (s *Service) ValidateSendBatch(ctx context.Context, userID uint, workspaceIValid: true,From: from,To: activeRecipients,- Subject: req.Template,+ Subject: req.Template.String(),Recipients: len(activeRecipients),SuppressedCount: suppressedCount,}, nil@@ -1028,7 +1028,7 @@ func (s *Service) SendBatch(ctx context.Context, userID, apiKeyID uint, workspacAPIKeyID: apiKeyPtr,Sender: from,Recipients: []string{recipient.Email},- Subject: req.Template,+ Subject: req.Template.String(),TemplateName: tmpl.Name,Status: models.EmailStatusSuppressed,ErrorMessage: errRecipientSuppressed,@@ -1201,8 +1201,8 @@ func (s *Service) RetryEmail(emailUUID string, userID uint, workspaceID *uint) (// RenderTemplate resolves a template by ID or name and renders it with the given data,// returning the rendered subject, HTML, and text without sending.-func (s *Service) RenderTemplate(userID uint, workspaceID *uint, templateID *uint, templateName, language string, data map[string]any) (*RenderedTemplate, error) {- tmpl, err := s.findTemplate(userID, workspaceID, templateID, templateName)+func (s *Service) RenderTemplate(userID uint, workspaceID *uint, templateID *uint, ref TemplateRef, language string, data map[string]any) (*RenderedTemplate, error) {+ tmpl, err := s.findTemplate(userID, workspaceID, templateID, ref)if err != nil {return nil, fmt.Errorf("template not found: %w", err)}@@ -1219,37 +1219,48 @@ func (s *Service) RenderTemplate(userID uint, workspaceID *uint, templateID *uinreturn rendered, nil}-// findTemplate looks up a template by ID or name. When templateID is provided-// it performs a fast primary-key lookup and verifies the caller owns the-// resource. Otherwise it falls back to a name-based search (workspace first,-// then personal).-func (s *Service) findTemplate(userID uint, workspaceID *uint, templateID *uint, name string) (*models.Template, error) {- if templateID != nil && *templateID != 0 {- tmpl, err := s.templateRepo.FindByID(*templateID)- if err != nil {- return nil, err+// findTemplate looks up the template ref names, or the deprecated templateID+// when ref is empty. A ref is matched by name in the workspace first; one that+// is all digits and matches no name is then looked up as an ID, so a template+// named "2024" still wins over the template whose ID is 2024.+func (s *Service) findTemplate(userID uint, workspaceID *uint, templateID *uint, ref TemplateRef) (*models.Template, error) {+ if ref == "" {+ if templateID != nil && *templateID != 0 {+ return s.findTemplateByID(userID, workspaceID, *templateID)}- // Verify ownership: must belong to the same user/workspace.- if workspaceID != nil {- if tmpl.WorkspaceID == nil || *tmpl.WorkspaceID != *workspaceID {- return nil, fmt.Errorf("template not found")- }- } else if tmpl.UserID != userID || tmpl.WorkspaceID != nil {- return nil, fmt.Errorf("template not found")- }- return tmpl, nil+ return nil, fmt.Errorf("template is required")}- if name == "" {- return nil, fmt.Errorf("template_id or template name is required")+ if workspaceID != nil {+ if tmpl, err := s.templateRepo.FindByWorkspaceName(*workspaceID, ref.String()); err == nil {+ return tmpl, nil+ }+ }+ if id, ok := ref.ID(); ok {+ if tmpl, err := s.findTemplateByID(userID, workspaceID, id); err == nil {+ return tmpl, nil+ }}-if workspaceID == nil {- return nil, fmt.Errorf("template %q not found: no active workspace", name)+ return nil, fmt.Errorf("template %q not found: no active workspace", ref)}- tmpl, err := s.templateRepo.FindByWorkspaceName(*workspaceID, name)+ return nil, fmt.Errorf("template %q not found", ref)+}++// findTemplateByID performs a primary-key lookup and verifies the caller owns+// the template: it must belong to the same workspace, or be the user's own+// personal template outside a workspace.+func (s *Service) findTemplateByID(userID uint, workspaceID *uint, id uint) (*models.Template, error) {+ tmpl, err := s.templateRepo.FindByID(id)if err != nil {- return nil, fmt.Errorf("template %q not found", name)+ return nil, err+ }+ if workspaceID != nil {+ if tmpl.WorkspaceID == nil || *tmpl.WorkspaceID != *workspaceID {+ return nil, fmt.Errorf("template not found")+ }+ } else if tmpl.UserID != userID || tmpl.WorkspaceID != nil {+ return nil, fmt.Errorf("template not found")}return tmpl, nil}diff --git a/internal/services/email/template_ref.go b/internal/services/email/template_ref.gonew file mode 100644index 0000000..f5b3e0f--- /dev/null+++ b/internal/services/email/template_ref.go@@ -0,0 +1,68 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later++package email++import (+ "bytes"+ "encoding/json"+ "fmt"+ "strconv"+ "strings"+)++// TemplateRef names a template by name or by ID. It decodes from a JSON+// string ("welcome", "42") or a JSON number (42).+type TemplateRef string++func (r *TemplateRef) UnmarshalJSON(data []byte) error {+ data = bytes.TrimSpace(data)+ if bytes.Equal(data, []byte("null")) {+ *r = ""+ return nil+ }+ if len(data) > 0 && data[0] == '"' {+ var s string+ if err := json.Unmarshal(data, &s); err != nil {+ return err+ }+ *r = TemplateRef(strings.TrimSpace(s))+ return nil+ }+ var n json.Number+ if err := json.Unmarshal(data, &n); err != nil {+ return fmt.Errorf("template must be a name or an ID")+ }+ if _, err := strconv.ParseUint(n.String(), 10, 64); err != nil {+ return fmt.Errorf("template ID must be a positive integer")+ }+ *r = TemplateRef(n.String())+ return nil+}++func (r TemplateRef) String() string { return string(r) }++// ID returns the template ID r denotes when it is all digits.+func (r TemplateRef) ID() (uint, bool) {+ id, err := strconv.ParseUint(string(r), 10, 0)+ if err != nil || id == 0 {+ return 0, false+ }+ return uint(id), true+}diff --git a/internal/services/email/template_ref_test.go b/internal/services/email/template_ref_test.gonew file mode 100644index 0000000..eb33d2f--- /dev/null+++ b/internal/services/email/template_ref_test.go@@ -0,0 +1,81 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later+++package email++import (+ "encoding/json"+ "testing"+)++func TestTemplateRefUnmarshal(t *testing.T) {+ cases := []struct {+ in string+ want TemplateRef+ wantErr bool+ }{+ {`{"template":"welcome"}`, "welcome", false},+ {`{"template":" welcome "}`, "welcome", false},+ {`{"template":"42"}`, "42", false},+ {`{"template":42}`, "42", false},+ {`{"template":null}`, "", false},+ {`{}`, "", false},+ {`{"template":-1}`, "", true},+ {`{"template":1.5}`, "", true},+ {`{"template":true}`, "", true},+ }+ for _, tc := range cases {+ var req SendTemplateRequest+ err := json.Unmarshal([]byte(tc.in), &req)+ if tc.wantErr {+ if err == nil {+ t.Errorf("%s: expected an error, got template %q", tc.in, req.Template)+ }+ continue+ }+ if err != nil {+ t.Errorf("%s: %v", tc.in, err)+ continue+ }+ if req.Template != tc.want {+ t.Errorf("%s: template = %q, want %q", tc.in, req.Template, tc.want)+ }+ }+}++func TestTemplateRefID(t *testing.T) {+ cases := []struct {+ ref TemplateRef+ wantID uint+ wantOK bool+ }{+ {"42", 42, true},+ {"0", 0, false},+ {"welcome", 0, false},+ {"2024-launch", 0, false},+ {"", 0, false},+ }+ for _, tc := range cases {+ id, ok := tc.ref.ID()+ if id != tc.wantID || ok != tc.wantOK {+ t.Errorf("%q.ID() = %d, %v; want %d, %v", tc.ref, id, ok, tc.wantID, tc.wantOK)+ }+ }+}