Files
summercms/modules/postcard/README.md
Jakub Zych 8deb56ff0b fix(35): WR-03 treat data: in a site name as a data URL only with ; or ,
scriptURLText took data: followed by any non-space character as a data
URL, so names such as Data:Lab, Big Data:Summit and data:Science were
refused on the Branding form and dropped from mail, contrary to the docs.
A data URL now needs its optional MIME type and the ; or , every data URL
has. javascript: and vbscript: keep matching with whitespace after the
colon, since such a URL still runs.
2026-11-14 17:40:13 +01:00

483 lines
41 KiB
Markdown

# postcard
Transactional mail from plugin-owned Markdown templates and layouts, delivered through a memory, log or SMTP driver.
`import "git.golem15.com/golem15/summercms/modules/postcard"`
**Name:** What you send home in summer; it delivers the application's mail.
## Overview
postcard is the mail layer of SummerCMS. Plugins that implement `pact.HasMailTemplates` ship WinterCMS-shaped mail files under `views/mail/`, and plugins that implement `pact.HasMailPartials` ship reusable blocks for them; at boot, `postcard.Activate` publishes one app-scoped `postcard.Mailer` built from the compass `mail.*` config, and `postcard.BootPlugin` registers each plugin's templates, layouts and partials as the plugin boots. Callers then send a template by its dotted name with a map of variables. postcard also owns the mail tables that hold administrators' edits: when a template, layout or partial has a customized row, the mailer uses that override, and the plugin's file otherwise. It is the counterpart of WinterCMS's `Mail::send` with `views/mail/*.htm` templates and mail layouts.
## Role in the framework
A service module on `backpack`, `compass` and `pact`; `party` registers the templates plugins contribute, and `lagoon` runs `postcard.Migrations` with the framework's other migrations. postcard does not import `lagoon`: it finds the database through `backpack`, and uses only lagoon's `attach` package, for the logo's URL. It is separate so mail rendering and delivery can be tested and swapped (memory, log, SMTP) without touching the code that sends.
Use cases:
- Send account mail (welcome, password reset) from Markdown templates owned by the plugin.
- Share one branded layout across all of an application's mail.
- Capture sent mail in memory in tests, or log it in development instead of delivering it.
## Features
- Templates named `<plugin>::mail.<name>` and loaded from `views/mail/<name>.htm` (dots become directories). A plugin may only register names in its own namespace; missing files, duplicates and unknown layout aliases fail at boot.
- WinterCMS file format: an INI header (`subject`, `layout`, `description`), a `==` separator, then a Markdown body rendered with Go `html/template` variables such as `{{ .name }}`.
- Layouts with a header, a text wrapper and an HTML wrapper, referenced from templates by a short alias (`pact.HasMailTemplates` maps aliases to full names). Three layouts are built in and usable from any plugin's templates: `default`, `system` and `minimal`.
- Partials: reusable blocks named `<plugin>::mail.partials.<name>`, loaded from `views/mail/partials/<name>.htm` and declared through `pact.HasMailPartials`. Bodies and layouts call them with `{{ partial "<name>" "key" value }}`. The partials `button`, `panel`, `table` and `subcopy` are built in.
- Every message gets an HTML part (Markdown converted with goldmark) and a plain-text part. The brand CSS (`mail.brandCss`, or the saved Branding) and `mail.css` go into the layout's style block, and the rendered HTML is then inlined: each CSS rule is copied into the `style` attribute of the elements it matches (go-premailer), so mail clients that drop style blocks still show the design. A layout opts out with `disable_auto_inline_css`.
- Safety checks: rendered HTML with script, iframe, object or embed tags, inline event handlers (any attribute whose name starts with `on`) or `javascript:`/`vbscript:`/`data:` URLs is rejected. Schemes are looked for in URL-bearing attributes, `style` attributes, style elements, comments and `meta` content, after character references are decoded and whitespace and control characters removed (`javascript&#58;` and `java&#9;script:` are `javascript:`). The content of `noscript`, `title`, `textarea`, `style`, `xmp` and the other raw-text elements, and of comments, is checked as markup too, because a mail client may read it so (scripting off, `svg` content, Outlook conditional comments); such elements nested more than eight deep are refused. Text is neither markup nor a URL: it is not checked for schemes, and text shaped like an event handler (`buy one = get one free`, `online = yes`) is sent. CR/LF in the subject or address headers is rejected; addresses are parsed with `net/mail`.
- Drivers behind the `postcard.Driver` interface: `postcard.MemoryDriver` (keeps messages for tests), `postcard.LogDriver` (logs headers and the text part through `log/slog`, never the HTML or credentials), `postcard.SMTPDriver` (go-mail with an explicit TLS policy) and `postcard.FailDriver` (a deterministic failure for tests).
- Database overrides: a customized row of `system_mail_templates` replaces a template's subject, body and layout, a customized row of `system_mail_layouts` or `system_mail_partials` replaces a layout or a partial, and `system_mail_layouts` also holds layouts that exist only in the database. The mailer reads them on every send, with no cache, in every process that publishes a `*gorm.DB`. A missing database, tables that are not migrated yet, or an override that does not render or fails the safety checks sends the file version.
- Branding: once the branding settings have been saved, the brand CSS is compiled from their colours (`postcard.CompileBrandCSS`) and replaces `mail.brandCss`, and layouts get the logo's absolute URL as `{{ .logoUrl }}` and the site name as `{{ .siteName }}` (else the display name of `mail.from`). The built-in default layout shows them in a header and a copyright footer.
- Sample values: a template's header may give its variables sample values with `sample.<path>` keys. Previews and save checks use them, and show every other variable as a visible `[path]` placeholder.
- An editor API for admin code (`postcard.Editor`): validate, preview and test-send an unsaved draft of a template, layout or partial through the same render path as a real send; one index row per file (`postcard.SyncIndex`) with a hash of the file for detecting that it changed under an override, and reset to the file version (`postcard.ResetOverride`).
- No locale selection: callers pass the full template name, including any locale suffix. A `<template>-<locale>` name whose locale ships no file sends the default-locale version (see "Locale variants").
## Usage
A plugin ships `views/mail/welcome.htm`:
```text
subject = "Welcome, {{ .name }}"
description = "Sent after registration"
==
Hi **{{ .name }}**, thanks for joining the blog.
```
and sends it through the mailer the runtime published:
```go
package blog
import (
"context"
"errors"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/postcard"
)
func SendWelcome(ctx context.Context, app *backpack.App, email, name string) error {
mailer, ok := app.Lookup[postcard.Mailer]()
if !ok {
return errors.New("mailer not published")
}
return mailer.Send(ctx, postcard.Message{
Template: "acme.blog::mail.welcome",
To: []string{email},
Vars: map[string]any{"name": name},
})
}
```
In tests, build the catalog and mailer directly and inspect what was sent:
```go
package blog
import (
"context"
"testing"
"testing/fstest"
"git.golem15.com/golem15/summercms/modules/postcard"
)
func TestWelcomeMail(t *testing.T) {
mailFS := fstest.MapFS{"views/mail/welcome.htm": {Data: []byte("subject = \"Welcome, {{ .name }}\"\n==\nHi **{{ .name }}**.\n")}}
cat := postcard.NewCatalog()
if err := cat.Register("acme.blog", mailFS, []string{"acme.blog::mail.welcome"}, nil); err != nil {
t.Fatal(err)
}
driver := postcard.NewMemoryDriver()
mailer := postcard.NewMailer(cat, driver, postcard.Options{From: "blog@example.com"})
msg := postcard.Message{Template: "acme.blog::mail.welcome", To: []string{"ada@example.com"}, Vars: map[string]any{"name": "Ada"}}
if err := mailer.Send(context.Background(), msg); err != nil {
t.Fatal(err)
}
if got := driver.Messages()[0].Subject; got != "Welcome, Ada" {
t.Fatalf("subject = %q", got)
}
}
```
### Locale variants
postcard picks no locale: the caller passes the full name, such as `acme.blog::mail.welcome-en` for English. A locale variant is a file whose name is the template's name, a dash and the locale (`welcome-en.htm`). A name with its own file always renders that file, as it always did.
A name the catalog does not hold, of the form `<template>-<tag>` where `<template>` is a registered template and `<tag>` is a locale tag (two letters, optionally followed by `-` or `_` and a 2 to 8 character alphanumeric subtag: `de`, `pt-BR`; case does not matter), renders the template's file, the default-locale version. Its subject, body and layout come from, in this order: the customized row of the name itself (an administrator wrote that locale's version), the customized row of the template, the template's file. When several registered templates match, the longest name wins. Any other unknown name fails with `postcard: unknown template <name>`. The rule needs no list of locales, so a worker that only runs postcard sends the same mail as the admin previews. `postcard.Catalog.TemplateFor` returns the file a name renders from; its `Name` is the base template's for a name without a file of its own.
`postcard.EnsureLocaleRows` gives such locales their index rows, so an administrator can open and customize them (see "Index rows, drift and reset").
### Partials
A partial is a block of mail that several templates and layouts share, such as a button. Its file has the layout format: a header with a `name`, a `==` line, the text section, a `==` line, then the HTML section. A plugin ships `views/mail/partials/note.htm`:
```text
name = "Note"
==
NOTE: {{ .text }}
==
<div class="note">{{ .text }}</div>
```
and declares it next to its templates:
```go
package blog
import (
"embed"
"io/fs"
"git.golem15.com/golem15/summercms/modules/pact"
)
//go:embed views/mail
var mailFS embed.FS
type Plugin struct{}
var _ pact.HasMailPartials = Plugin{}
func (Plugin) ID() string { return "acme.blog" }
func (Plugin) MailPartialsFS() fs.FS { return mailFS }
func (Plugin) MailPartials() []string {
return []string{"acme.blog::mail.partials.note"}
}
```
A name must be in the plugin's own namespace and under `mail.partials.`; a name outside either, a missing file or a duplicate fails `postcard.BootPlugin` with the dotted name. A plugin may implement `pact.HasMailPartials` without `pact.HasMailTemplates`, and any plugin's templates may call its partials.
A template body or a layout calls a partial with its name followed by pairs of a key and a value, which become the partial's variables:
```text
subject = "Your order {{ .code }}"
==
Thanks for your order.
{{ partial "button" "url" .link "body" "Track the order" "type" "positive" }}
{{ partial "acme.blog::mail.partials.note" "text" .note }}
```
A bare name such as `button` is one of postcard's built-in partials; a plugin's partial is called by its full name. The HTML section goes into the HTML part and the text section into the plain-text part. An unknown name, an odd number of key and value arguments or a key that is not a string fails the render with the partial's name.
Inside a partial's HTML section, `{{ markdown .body }}` renders a value as Markdown, tables included; in the text section it returns the value unchanged. A partial cannot call `partial`.
Markdown drops raw HTML, so a call in a body does not insert the partial's HTML directly. It leaves a token of letters and digits, `MAILPARTIAL` followed by a random value drawn for that one render, and postcard swaps the token for the rendered partial after the body has been converted. A variable's value cannot contain that token, so text that only looks like one stays text. Put a call on its own line, with blank lines around it, to get the partial as a block of its own. Markdown rendering of bodies is unchanged: raw HTML in a body is still dropped.
### Built-in layouts and partials
| Layout alias | Full name | Renders |
|--------------|-----------|---------|
| `default` | `postcard::mail.layouts.default` | WinterCMS's default layout (`wrapper layout-default`): the `header` partial with the logo or the site name, the message in the `inner-body` card, and the `footer` partial with `© <year> <site name>`. Used when a template names no layout. |
| `system` | `postcard::mail.layouts.system` | WinterCMS's system layout (`wrapper layout-system`): the same header and footer as `default`, the message in the padded card followed by a `subcopy` note that the message is automatic. Its text wrapper ends with that note and the footer's text section. |
| `minimal` | `postcard::mail.layouts.minimal` | The message directly in the page body, with the logo (`img.logo`, the site name as its alternative text) in a paragraph above it when `logoUrl` is set. |
A template selects one with `layout = "system"`. A plugin's own alias of the same name wins, except `default`, which plugins cannot redefine. Every built-in layout has the `{{ .brandCss }}{{ .css }}` style block.
### CSS inlining
After a layout's HTML wrapper has rendered and passed the safety checks, postcard inlines it, as WinterCMS's `MailManager` does with CssToInlineStyles: `github.com/vanng822/go-premailer` with its default options reads the rules of every style element, writes them into the `style` attributes of the matching elements by specificity, mirrors CSS `width` and `height` to the attributes of the same name, keeps `class` attributes, and puts the rules it cannot inline (media queries, pseudo-classes such as `:hover`, selectors with `*`) back in one style element, marked `!important`. The safety checks run on the decoded markup before inlining, whether or not the layout opts out, so CSS in a style element with a `javascript:`, `vbscript:` or `data:` address is refused there. The inlined HTML is checked again, and an inlined result that fails the check is sent as its style-block version, with the same warning as an inliner error. HTML with no style element is left as it is. Preview, test send and sends run the same code; the text part is never changed.
A layout opts out with WinterCMS's option name, `disable_auto_inline_css`:
- a layout file sets the header key `disable_auto_inline_css = true` (`1` or `yes`, in any case, also work); `postcard.LayoutFile.DisableAutoInlineCSS` reports it;
- a row of `system_mail_layouts` sets the column `disable_auto_inline_css` (`postcard.LayoutOverride.DisableAutoInlineCSS`); `postcard.SyncIndex` mirrors the file's value into rows that are not customized and `postcard.ResetOverride` writes it back;
- a layout draft sets `postcard.Draft.DisableAutoInlineCSS`.
An opted-out layout keeps its style block as rendered; it passed the same safety checks as an inlined one. When the inliner fails on a message, or its result fails the safety checks, the message is sent with its style block only and a warning keyed by the layout is logged at most once a minute.
Both wrappers of every layout get these keys: `Content`, `Subject`, `css`, `brandCss`, `logoUrl` (see [Branding](#branding)), `siteName` (the Branding's site name, else the display name of `mail.from`, else empty) and `year` (the current year). The default and system layouts call the header only when `logoUrl` or `siteName` is set, and builds the footer line from `year` and `siteName`, `© 2026 Acme`, or `© 2026` without a name, passed to the footer as its `text` argument, so the name is printed as typed and never read as Markdown. Its text wrapper is the message, a blank line and the footer's text section.
| Partial | Arguments | Renders |
|---------|-----------|---------|
| `button` | `url`, `body`, `type` (`primary` by default, `positive` or `negative`) | A link styled as a button (`button button-<type>`); in text, the label and the address. |
| `panel` | `body` (Markdown) | A highlighted block (`panel`). |
| `table` | `body` (a Markdown table) | A table in a `table` block. |
| `subcopy` | `body` (Markdown) | Small print under a rule (`subcopy`). |
| `header` | `logo` (an image URL), `body` (a name), `url` (optional) | A layout's header row (`td.header`): `img.logo` with `body` as its alternative text when `logo` is set, else `body` in a `span`; wrapped in a link when `url` is set. In text, the name. |
| `footer` | `text` (plain, printed escaped in a paragraph) or `body` (Markdown) | A layout's footer row (`table.footer`). In text, a rule line and the text or the body. |
### Overrides from the admin
postcard owns the tables `system_mail_templates`, `system_mail_layouts`, `system_mail_partials`, `system_mail_brand_settings` and `system_mail_image_library` (`postcard.Migrations`). A row of `system_mail_templates` with `is_custom` set is an override of the template named in its `code`: its `subject` and `body` replace the file's, and the row its `layout_id` points at names the layout. The body has the same format as in the file, Markdown with Go template variables.
`postcard.Activate` gives the mailer the source `postcard.NewDBSource` returns. On every `Send` the mailer asks it once for the template being sent; nothing is cached, so an edit applies to the next message in every process that shares the database, including a worker that never loads the admin.
The subject is taken from the first of these that is set:
1. `postcard.Message.Subject`, the caller's subject;
2. the override's subject;
3. the file's subject.
Layouts and partials are overridden the same way. A row of `system_mail_layouts` with `is_custom` set and a full layout name in `code` replaces that layout's HTML and text wrappers; a row with another `code` is a layout that exists only in the database, which a template override can select. A layout row's `content_css` is placed before `mail.css` in the layout's `{{ .css }}` slot. A row of `system_mail_partials` with `is_custom` set replaces the HTML and text sections of the partial named in its `code`.
An override never stops mail:
- With no `*gorm.DB` published, the file version is sent.
- When the lookup fails (no connection, or the tables are not migrated yet), the file version is sent and a warning is logged, at most once a minute per distinct error.
- When an override (of the template, its layout or a partial it calls) does not parse, fails while rendering (for example it uses a field of a variable the caller does not pass) or fails the safety checks, the error is logged as `postcard: override failed, sending the file version` with the template name, and the message is sent from the files alone.
- When the override's layout no longer exists, the message is rendered in the default layout and a warning is logged.
`postcard.NewMailer` takes a source through `postcard.Options.Overrides`; any `postcard.OverrideSource` works, which is how a test supplies overrides without a database:
```go
package blog
import (
"context"
"git.golem15.com/golem15/summercms/modules/postcard"
)
// fixedOverrides overrides one template with a fixed subject and body.
type fixedOverrides struct{}
func (fixedOverrides) MailOverrides(_ context.Context, template string) (postcard.Overrides, error) {
if template != "acme.blog::mail.welcome" {
return postcard.Overrides{}, nil
}
return postcard.Overrides{Template: &postcard.TemplateOverride{
Subject: "Hello, {{ .name }}",
Body: "Good to see you, **{{ .name }}**.",
}}, nil
}
func newTestMailer(cat *postcard.Catalog, driver postcard.Driver) postcard.Mailer {
return postcard.NewMailer(cat, driver, postcard.Options{Overrides: fixedOverrides{}})
}
```
### Branding
Layouts have two CSS slots, `{{ .brandCss }}` and `{{ .css }}`, a logo slot, `{{ .logoUrl }}`, and a name slot, `{{ .siteName }}`. What fills the brand slot depends on the row with `id` 1 of `system_mail_brand_settings`:
- While the row does not exist, the slot holds `mail.brandCss` from the configuration and `{{ .logoUrl }}` is empty, so an application that never saves Branding is unchanged.
- Once the row exists, the slot holds `postcard.CompileBrandCSS` of the row's colours, and `mail.brandCss` is no longer used. An empty colour column is that colour's default (`postcard.DefaultBrand`).
`mail.css` fills `{{ .css }}` in both cases, after the brand CSS, with a layout's own CSS before it.
The compiled CSS styles the page, links, headings, paragraphs and tables, and the classes of the built-in layouts and partials (`button button-primary`, `panel`, `table`, `subcopy`, `header`, `footer`, the `logo` image and others), so the colours also apply in a plugin's layout that has the style block and no brand classes of its own. A colour must be a six-digit hexadecimal colour such as `#2da7c7`; `postcard.CompileBrandCSS` refuses anything else with an error naming the column. If a stored colour is invalid at send time, a warning is logged and `mail.brandCss` is used.
| Column | `postcard.Brand` field | Default |
|--------|------------------------|---------|
| `body_bg` | `BodyBg` | `#f5f8fa` |
| `content_bg` | `ContentBg` | `#ffffff` |
| `header_color` | `HeaderColor` | `#bbbfc3` |
| `footer_color` | `FooterColor` | `#aeaeae` |
| `heading_color` | `HeadingColor` | `#2f3133` |
| `text_color` | `TextColor` | `#74787e` |
| `link_color` | `LinkColor` | `#2da7c7` |
| `button_text_color` | `ButtonTextColor` | `#ffffff` |
| `button_primary_bg` | `ButtonPrimaryBg` | `#d66829` |
| `button_positive_bg` | `ButtonPositiveBg` | `#52a838` |
| `button_negative_bg` | `ButtonNegativeBg` | `#e01346` |
| `panel_bg` | `PanelBg` | `#edeff2` |
| `table_border_color` | `TableBorderColor` | `#edeff2` |
The row's `logo_file_id` names a public `system_files` row. Its URL is not stored: on every send it is built from the configuration with `attach.AbsolutePublicURL`, from `storage.uploads.public_url`, or from `app.url` and `storage.uploads.public_path_prefix`, so a worker process and `serve` produce the same absolute URL and a changed CDN address applies at once. When the file is missing or not public, or neither base is configured, `{{ .logoUrl }}` is empty, a warning is logged at most once a minute, and the mail is sent. A layout that shows the logo guards it:
```text
{{ if .logoUrl }}<img src="{{ .logoUrl }}" alt="">{{ end }}
```
The row's `site_name` column is `postcard.Brand.SiteName`. The built-in layouts show it in their header (as the logo's alternative text when there is a logo) and footer. While it is empty, and while no Branding row exists, `{{ .siteName }}` is the display name of `mail.from` parsed with `net/mail` (`Acme` for `Acme <no-reply@acme.test>`), or empty when the address has none. The name is HTML-escaped by `html/template` wherever a layout prints it, and printed literally in the header and the footer (`*Acme*` and `Acme <Studio>` appear as typed).
A name `postcard.UnsafeText` refuses (a `javascript:` or `vbscript:` URL, or a data URL such as `data:text/html,x`; `Data:Lab` is no data URL) never reaches a layout and never stops a send: an unsafe Branding name is treated as empty, so the `mail.from` display name is used if that one is safe, and an unsafe `mail.from` display name gives no name. A warning naming the source (`branding` or `mail.from`), never the value, is logged at most once a minute per source. Prose such as `Big Data: Summit`, and text shaped like an event handler such as `Online=Shop` or `Shop onclick=x`, is a name like any other: it is printed as escaped text, which is never markup. The Branding preview of an unsaved draft leaves such a name out the same way; the admin's Branding form refuses to save it.
A mail that falls back to its file version because an override failed still gets the Branding.
### Sample values
A preview has no caller to supply variables, so a template can carry sample values in its header. A key is `sample.` followed by the variable's path, and the path keeps its case, because template variables are case-sensitive:
```text
subject = "Your order {{ .order.code }}"
description = "Sent when an order is paid"
sample.name = "Ada"
sample.order.code = "ZAM-1"
==
Hi {{ .name }}, we received the payment for **{{ .order.code }}**.
{{ range .order.items }}- {{ .description }}
{{ end }}
```
Sample values are strings and are used only by `postcard.Editor`; `Send` never reads them, and a file without them works as before. For a preview postcard walks the draft's subject and body and gives every variable they read a value: its sample, or the placeholder `[path]`, as in `[order.items.description]`. A field of a variable becomes a nested value and the target of a `range` a list of one element, so a body that reads `.order.code` or ranges over `.order.items` renders without the caller's data.
### Editing drafts
`postcard.EditorFrom` returns the `postcard.Editor` of the mailer `postcard.Activate` published. Admin code describes unsaved content as a `postcard.Draft` and asks the editor to check, render or send it:
```go
package blog
import (
"context"
"errors"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/postcard"
)
// previewWelcome renders an edited welcome mail without saving it.
func previewWelcome(ctx context.Context, app *backpack.App, subject, body string) (postcard.Preview, error) {
editor, ok := postcard.EditorFrom(app)
if !ok {
return postcard.Preview{}, errors.New("mailer not published")
}
draft := postcard.Draft{
Kind: postcard.KindTemplate,
Name: "acme.blog::mail.welcome",
Subject: subject,
Body: body,
}
if problem := editor.Validate(ctx, draft); problem != nil {
// problem.Field and problem.Rule say what to show next to which field.
return postcard.Preview{}, problem
}
return editor.Preview(ctx, draft)
}
```
A draft is rendered by the code that renders a send, with the mailer's CSS and the layouts and partials its override source returns, so a preview is what the saved content would send:
| `postcard.Draft.Kind` | `postcard.Draft.Name` | Content fields | Rendered as |
|-----------------------|-----------------------|----------------|-------------|
| `postcard.KindTemplate` | The template's full name | `Subject`, `Body`, `Layout` (a layout code; empty keeps the file's layout) | The template with its sample values and placeholders. |
| `postcard.KindLayout` | The layout's code | `HTML`, `Text`, `CSS` | The layout around postcard's sample message. |
| `postcard.KindPartial` | The partial's full name | `HTML`, `Text` | A message that is one call of the partial, with a placeholder for every argument it reads. |
| `postcard.KindBrand` | Not used | `Brand` (nil is the default brand) | The sample message in the default layout, with the draft's colours and logo in place of the saved Branding. |
`postcard.Editor.Validate` returns nil or a `postcard.DraftError`. `postcard.DraftError.Field` is the form field at fault: `subject`, `layout` or `body` for a template, `content_html`, `content_text` or `content_css` for a layout or a partial, the colour's column for Branding. `postcard.DraftError.Rule` is one of:
| Rule | Meaning |
|------|---------|
| `parse` | The content is not a valid template. |
| `render` | It does not render with the sample values and placeholders. |
| `unsafe` | It contains, or renders to, a script, iframe, object or embed tag, an inline event handler or a `javascript:`, `vbscript:` or `data:` address in an attribute, a style or a comment (encoded or not); a layout's CSS that would close the style block is refused the same way. `postcard.DraftError.Message` holds the text that matched. |
| `subject_line` | The subject renders to more than one line. |
| `layout` | The template's layout code names no layout. |
| `partial` | A call names a partial that does not exist; `postcard.DraftError.Name` holds the name. |
| `no_content` | A layout wrapper does not use `{{ .Content }}`. |
| `colour` | A Branding colour is not a six-digit hexadecimal colour; the field is its column, such as `button_primary_bg`. |
`postcard.DraftError.Message` carries the template parser's, the renderer's or the safety check's own text and nothing else. The safety checks are the ones a send runs, and the message shows where. Text is not a URL, so prose such as `metadata:` or `Big Data: Summit` passes, while an encoded `href="javascript&#58;..."` is decoded and refused. A template body is also refused when its source contains one of the unsafe tags, which Markdown would otherwise drop without notice.
`postcard.Editor.Preview` and `postcard.Editor.SendDraft` return a draft problem as a `postcard.DraftError` too (use `errors.As`). `postcard.Editor.SendDraft` delivers the rendered draft to the one address it is given, through the mailer's driver and from `mail.from`.
### Index rows, drift and reset
`postcard.Catalog.Templates`, `postcard.Catalog.Layouts` and `postcard.Catalog.Partials` list the files as `postcard.TemplateFile`, `postcard.LayoutFile` and `postcard.PartialFile` values; each carries its `Source` and a `Hash`, the SHA-256 of the file's text with CRLF line endings normalized, so the same file hashes the same on every platform.
`postcard.SyncIndex` gives every file a row in its table, keyed by `code`. A row that is not customized mirrors the file, so lists and forms show the file version. A customized row keeps its content; only `source`, `description`, `locale`, `base_code`, `name` and `file_hash` follow the file. `base_code` groups the locale variants of one template: it is the code with its locale suffix stripped (`postcard.TemplateBase`), so `acme.blog::mail.welcome` and `acme.blog::mail.welcome-en` share the base `acme.blog::mail.welcome`. An override stores the hash of the file it was written against in `base_hash`, so it is outdated when `base_hash` and `file_hash` differ. `postcard.SyncIndex` never deletes a row, leaves database-only layouts alone, writes nothing when a row already matches, and may run in several processes at once. It needs the tables: when they are not migrated yet it returns the error.
`postcard.EnsureLocaleRows` adds the rows of the locales a template ships no file for: for every base template and every given locale except the default one, the row `<template>-<locale>` with that locale, the template as `base_code`, and the template file's subject, body, layout and hash. Such a row sends the default-locale version until it is customized (see "Locale variants"); its `file_hash` follows the template's file, so a customized one shows as outdated when that file changes. The default locale gets no row: the template's own file is its version. Like `postcard.SyncIndex` it writes nothing for a matching row, deletes nothing and is safe to run in several processes at once; it can be limited to some templates.
`postcard.ResetOverride` returns one row to its file version and clears `is_custom`, `base_hash` and `customized_at`. The file version of a locale row without a file of its own is the base template's file, so its reset makes it send the default-locale version again. A database-only layout has no file version and is refused.
`postcard.FormatTemplate`, `postcard.FormatLayout` and `postcard.FormatPartial` write content in the file format, so a file version and an override can be compared line by line. `postcard.TemplateLocale` reads the locale from a name such as `acme.blog::mail.welcome-en`, given the application's locales.
## API reference
| Identifier | Description |
|------------|-------------|
| `postcard.Activate` | Builds the driver from config and publishes the app-scoped `postcard.Mailer` before plugins boot. The mailer reads overrides through `postcard.NewDBSource`. |
| `postcard.BootPlugin` | Registers a booting plugin's declared partials (`pact.HasMailPartials`) and its templates and layouts (`pact.HasMailTemplates`) with the published mailer. |
| `postcard.Mailer` | Sends a registered template through the configured driver. |
| `postcard.NewMailer` | Builds a mailer from a catalog, a driver and `postcard.Options`. |
| `postcard.Message` | What callers send: template name, recipients, reply-to, variables and an optional subject override. |
| `postcard.Options` | Mailer settings: sender address, CSS, brand CSS and, in `postcard.Options.Overrides`, the source of database overrides (nil sends the file versions). |
| `postcard.Catalog` | Registered templates, layouts and partials, including the built-in ones. |
| `postcard.NewCatalog` | Returns a catalog holding the built-in layouts and partials and no template. |
| `postcard.Catalog.Register` | Loads a plugin's templates and layout aliases from an `fs.FS`. |
| `postcard.Catalog.RegisterPartials` | Loads a plugin's partials from an `fs.FS`. |
| `postcard.Driver` | Delivers a `postcard.RenderedMessage`. |
| `postcard.RenderedMessage` | The validated payload a driver transmits: headers, HTML part and text part. |
| `postcard.NewMemoryDriver` | In-memory driver; `postcard.MemoryDriver.Messages` returns what was sent. |
| `postcard.NewLogDriver` | Driver that logs through a `*slog.Logger` (the postcard component logger when nil). |
| `postcard.NewSMTPDriver` | SMTP driver built from a `postcard.SMTPConfig`. |
| `postcard.SMTPConfig` | Host, port, credentials, TLS policy and timeout for the SMTP driver. |
| `postcard.FailDriver` | Driver whose `postcard.FailDriver.Send` always returns `postcard.FailDriver.Err`. |
| `postcard.OverrideSource` | Supplies the database overrides of one render. `postcard.OverrideSource.MailOverrides` takes the template name; an empty name asks for everything except a template override. |
| `postcard.Overrides` | What a source returns: the template override in `postcard.Overrides.Template` (nil when there is none), layout content by code in `postcard.Overrides.Layouts`, partial content by name in `postcard.Overrides.Partials` and the saved Branding in `postcard.Overrides.Brand` (nil while it has never been saved). |
| `postcard.TemplateOverride` | A template's customized subject, body and layout code. An empty `postcard.TemplateOverride.Layout` keeps the file's layout. |
| `postcard.LayoutOverride` | A layout's name, HTML wrapper, text wrapper and CSS from the database, and `postcard.LayoutOverride.DisableAutoInlineCSS`, the layout's opt-out of CSS inlining. In `postcard.Overrides.Layouts` under a file layout's full name it replaces that layout; under another code it is a database-only layout. |
| `postcard.PartialOverride` | A partial's HTML and text sections from the database, in `postcard.Overrides.Partials` under the partial's full name. |
| `postcard.NewDBSource` | The source over postcard's tables. It looks the `*gorm.DB` up on the app at every call and returns no overrides when none is published. It builds the Branding logo's URL from the app's configuration. |
| `postcard.Brand` | The Branding: thirteen colours, `postcard.Brand.LogoURL`, the logo's absolute URL, and `postcard.Brand.SiteName`, the name the built-in layouts show. |
| `postcard.DefaultBrand` | WinterCMS's default mail colours. |
| `postcard.CompileBrandCSS` | Checks a brand's colours and returns the brand CSS compiled from them. |
| `postcard.UnsafeText` | Reports whether a text a layout prints, such as the site name, must be kept out of mail: it holds a `javascript:`, `vbscript:` or `data:` URL, or fails the rendered-HTML safety checks once HTML-escaped and placed where the built-in layouts print it (after `© <year> ` in the footer, in the header). Event-handler-shaped text such as `Online=Shop` is safe. |
| `postcard.Migrations` | The gormigrate set that creates the mail tables; lagoon runs it under the `summercms.postcard` history. |
| `postcard.TemplatesTable`, `postcard.LayoutsTable`, `postcard.PartialsTable`, `postcard.BrandTable`, `postcard.ImageLibraryTable` | The names of the mail tables, for code that defines models over them. |
| `postcard.SyncIndex` | Upserts one index row per file template, layout and partial of a catalog; mirrors the file into rows that are not customized and refreshes `file_hash` and the template's `base_code` on all. |
| `postcard.EnsureLocaleRows` | Upserts the row `<template>-<locale>` of every locale (except the default) a base template ships no file for, from the template's file; optionally limited to some templates. |
| `postcard.ResetOverride` | Returns one file-backed row to its file version. Takes the row's `postcard.Kind` and code. |
| `postcard.Kind` | What a draft or a row is: `postcard.KindTemplate`, `postcard.KindLayout`, `postcard.KindPartial` or `postcard.KindBrand` (a Branding draft; it has no index row). |
| `postcard.Editor` | Validates, previews and test-sends drafts with the mailer's catalog, configuration, override source and driver. |
| `postcard.EditorFrom` | Returns the editor of the mailer published on an app. |
| `postcard.Editor.Catalog` | The mailer's catalog. |
| `postcard.Editor.Validate` | Checks a draft; returns nil or a `postcard.DraftError`. |
| `postcard.Editor.Preview` | Renders a draft to a `postcard.Preview` (subject, HTML part, text part). |
| `postcard.Editor.SendDraft` | Renders a draft and delivers it to one address. |
| `postcard.Draft` | Unsaved content of one kind. A layout draft's `postcard.Draft.DisableAutoInlineCSS` previews it without CSS inlining. |
| `postcard.DraftError` | Why a draft cannot be saved: field, rule, message and, for an unknown partial, its name. |
| `postcard.TemplateFile`, `postcard.LayoutFile`, `postcard.PartialFile` | A registered file with its parts, its normalized `Source` and its `Hash`. `postcard.TemplateFile.Samples` holds the sample values and `postcard.TemplateFile.Layout` the full name of the file's layout; `postcard.LayoutFile.DisableAutoInlineCSS` is the layout's `disable_auto_inline_css` header key. |
| `postcard.Catalog.Templates`, `postcard.Catalog.Layouts`, `postcard.Catalog.Partials` | The registered files, sorted by name. |
| `postcard.Catalog.Template`, `postcard.Catalog.Layout`, `postcard.Catalog.Partial` | One registered file by full name. |
| `postcard.Catalog.TemplateFor` | The file a template name renders from: its own file, or the base template's file for a `<template>-<locale>` name whose locale ships none. |
| `postcard.FormatTemplate`, `postcard.FormatLayout`, `postcard.FormatPartial` | Content written in the file format, for display and comparison. |
| `postcard.TemplateLocale` | The locale suffix of a template name, when it is one of the given locales. |
| `postcard.TemplateBase` | A template name without the locale suffix `postcard.TemplateLocale` finds: the `base_code` its locale variants share. |
## Configuration
`postcard.Activate` reads these keys from the app's [compass](../compass/README.md) config. The Branding logo's URL also reads `storage.uploads.public_url`, `storage.uploads.public_path_prefix` and `app.url`, which belong to [lagoon](../lagoon/README.md)'s `attach` and to the application.
| Key | Default | Controls |
|-----|---------|----------|
| `mail.driver` | `memory` | Delivery driver: `memory`, `log` or `smtp`. Any other value fails at boot. |
| `mail.from` | empty | Sender address. Required by the SMTP driver. Its display name is the layouts' `{{ .siteName }}` while the Branding has no site name. |
| `mail.css` | empty | CSS placed in the layout's style block, after the brand CSS. Always applied. |
| `mail.brandCss` | empty | Brand CSS placed before `mail.css`. Used only until the branding settings are saved; from then on the CSS compiled from their colours replaces it (see [Branding](#branding)). |
| `mail.smtp.host` | none | SMTP host. Required when `mail.driver` is `smtp`. |
| `mail.smtp.port` | `587` | SMTP port. |
| `mail.smtp.username` | empty | SMTP user. When set, PLAIN authentication is used. |
| `mail.smtp.password` | empty | SMTP password. |
| `mail.smtp.tls` | `mandatory` | TLS policy: `mandatory` (or `tls`), `starttls` (or `opportunistic`), `none` (or `notls`, `off`). Plain connections are never inferred. |
| `mail.smtp.timeout` | `10s` | Connection timeout, as a Go duration or a number of seconds. |
```yaml
mail:
driver: smtp
from: blog@example.com
smtp:
host: smtp.example.com
port: 587
username: blog
password: <secret>
tls: mandatory
```
## Dependencies
- SummerCMS modules: [backpack](../backpack/README.md), [compass](../compass/README.md), [diary](../diary/README.md) (component logger `postcard` when the app publishes no logger), [pact](../pact/README.md), and the `attach` package of [lagoon](../lagoon/README.md) (`attach.AbsolutePublicURL` and `attach.BlobKey` for the logo's URL; lagoon itself is not imported).
- Third-party: `github.com/wneessen/go-mail` (SMTP), `github.com/yuin/goldmark` (Markdown, and its table extension inside partials), `github.com/vanng822/go-premailer` (CSS inlining, pinned at v1.38.0; see `.planning/notes/2026-11-13-mail-layouts-css-inlining.md`), `golang.org/x/net/html` (tokenizing rendered HTML for the safety checks, already a framework dependency; see `.planning/notes/2026-11-14-mail-url-scheme-check.md`), `gorm.io/gorm` (reading overrides), `github.com/go-gormigrate/gormigrate/v2` (the mail tables' migrations).
- Standard library: `bytes`, `context`, `crypto/rand`, `crypto/sha256`, `database/sql`, `embed`, `encoding/hex`, `errors`, `fmt`, `html`, `html/template`, `io/fs`, `log/slog`, `net/mail`, `regexp`, `sort`, `strconv`, `strings`, `sync`, `text/template` (and `text/template/parse`), `time`.
- Tests additionally use `github.com/testcontainers/testcontainers-go` (Mailpit and Postgres containers), `gorm.io/driver/postgres` and `github.com/jackc/pgx/v5`.
## Testing
```sh
go test ./modules/postcard/...
```
The SMTP integration test starts a Mailpit container, and the override, index and reset tests a Postgres container, all through testcontainers-go, so they need Docker. Run `go test -short ./modules/postcard/...` to skip them; the remaining tests use the memory and fail drivers and need no external services.