feat(postcard): mail branding and the logo URL

- Brand, DefaultBrand and CompileBrandCSS: thirteen colours, each checked
  as a six-digit hex colour, compiled into CSS for plain elements and the
  built-in layouts and partials
- once the branding row exists its compiled CSS replaces mail.brandCss;
  mail.css still follows, and the file version sent after a failing
  override keeps the Branding
- layouts get logoUrl, built per send from storage.uploads.public_url or
  app.url through attach.AbsolutePublicURL; a logo that cannot be shown is
  left out with a rate-limited warning
- Editor previews and validates a Branding draft (rule colour)

Plan 35-01, task 5.
This commit is contained in:
Jakub Zych
2026-11-13 11:06:43 +01:00
parent 935e4bf64f
commit 2bf9081c1b
10 changed files with 974 additions and 27 deletions

View File

@@ -12,7 +12,7 @@ postcard is the mail layer of SummerCMS. Plugins that implement `pact.HasMailTem
## 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`. It is separate so mail rendering and delivery can be tested and swapped (memory, log, SMTP) without touching the code that sends.
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:
@@ -26,10 +26,11 @@ Use cases:
- 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. `mail.css` and `mail.brandCss` are inlined into the layout's style block.
- 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.
- Safety checks: rendered HTML with script, iframe, object or embed tags, inline event handlers or `javascript:`/`vbscript:`/`data:` URLs is rejected; 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 }}`.
- 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.
@@ -229,6 +230,41 @@ func newTestMailer(cat *postcard.Catalog, driver postcard.Driver) postcard.Maile
}
```
### Branding
Layouts have two CSS slots, `{{ .brandCss }}` and `{{ .css }}`, and a logo slot, `{{ .logoUrl }}`. 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`, `layout-system` 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 }}
```
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:
@@ -289,8 +325,9 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
| `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. `postcard.DraftError.Rule` is one of:
`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 |
|------|---------|
@@ -301,6 +338,7 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
| `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, so text such as `metadata:` is refused at save as it would be at send, and the message shows where. A template body is also refused when its source contains one of the unsafe tags, which Markdown would otherwise drop without notice.
@@ -338,16 +376,19 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
| `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` and partial content by name in `postcard.Overrides.Partials`. |
| `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. 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. |
| `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 and `postcard.Brand.LogoURL`, the logo's absolute URL. |
| `postcard.DefaultBrand` | WinterCMS's default mail colours. |
| `postcard.CompileBrandCSS` | Checks a brand's colours and returns the brand CSS compiled from them. |
| `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` on all. |
| `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` (reserved for the branding settings; the editor does not render it yet). |
| `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. |
@@ -364,14 +405,14 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
## Configuration
`postcard.Activate` reads these keys from the app's [compass](../compass/README.md) config:
`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. |
| `mail.css` | empty | CSS inlined into the layout. |
| `mail.brandCss` | empty | Brand CSS inlined before `mail.css`. |
| `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. |
@@ -393,7 +434,7 @@ mail:
## 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).
- 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), `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/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`.