validateHTML ran (?i)\son[a-z]+\s*= over the rendered document, text included, so a variable such as "buy one = get one free" stopped its own message, and it is what made Online=Shop in the footer a send failure. The tokenizer walk refuses every on* attribute, and since CR-02 it also reads raw-text element and comment content as markup, so the regex is dropped. Text shaped like a handler is now sent; such site names are shown and saved, and the Branding refusal copy no longer mentions onclick=.
235 lines
21 KiB
Markdown
235 lines
21 KiB
Markdown
---
|
||
title: Mail
|
||
description: Ship WinterCMS-style mail templates in a plugin, send them through postcard, and deliver them with the memory, log or SMTP driver.
|
||
section: services
|
||
order: 70
|
||
---
|
||
# Mail
|
||
|
||
WinterCMS plugins ship mail templates in `views/mail` and send them with `Mail::send`. SummerCMS keeps the file format and the dotted template names; [postcard](../../modules/postcard/README.md) loads them at boot and sends them through a configured driver.
|
||
|
||
## Templates and layouts
|
||
|
||
A plugin implements `pact.HasMailTemplates`: it returns its embedded `views/mail` files, the template names it ships and short aliases for its layouts. A template named `acme.blog::mail.welcome` lives in `views/mail/welcome.htm` (dots in the name become directories), and a plugin may only register names in its own namespace. A missing file, a duplicate name or an unknown layout alias fails the start-up.
|
||
|
||
The file format is WinterCMS's: an INI header with the `subject`, the `layout` alias and a `description`, a `==` line, then a Markdown body with Go template variables such as `{{ .name }}`. A layout has a header, a text wrapper and an HTML wrapper, separated by `==` lines, each with `{{ .Content }}` where the message goes. A template without a `layout` uses the built-in `default` layout; see [Built-in layouts](#built-in-layouts).
|
||
|
||
Each message gets an HTML part, rendered from the Markdown, and a plain-text part. `mail.css` and the brand CSS go into the layout's style block; see [Branding](#branding).
|
||
|
||
### CSS inlining
|
||
|
||
Many mail clients drop a style block, so postcard also copies the CSS onto the elements it styles, as WinterCMS does: after the layout has rendered, every rule of the HTML's style elements is written into the `style` attribute of the elements it matches (with go-premailer), and CSS widths and heights also become `width` and `height` attributes. Classes stay on the elements. Rules that cannot be inlined, such as media queries and `:hover`, stay in a style element in the head; the style block holds only those afterwards. The preview, the test send and real mail are inlined the same way, and the plain-text part is never touched.
|
||
|
||
A layout keeps its CSS in the style block only when it opts out: a layout file with `disable_auto_inline_css = true` in its header (`1` and `yes` also work), or a layout edited in the admin with **Do not inline CSS** switched on (its CSS tab). The built-in layouts all inline. The safety checks run on the message before inlining, whether or not the layout opts out. If the inliner fails on a message, or its result fails the safety checks, that message is sent with its style block only and a warning is logged; mail is never stopped by it.
|
||
|
||
## Partials
|
||
|
||
A partial is a block that several templates and layouts share, such as a button or a footer note. A plugin implements `pact.HasMailPartials`: it returns its embedded `views/mail` files and the partial names it ships. A partial named `acme.blog::mail.partials.note` lives in `views/mail/partials/note.htm`, and its file has the layout format, with a text section and an HTML section:
|
||
|
||
```text
|
||
name = "Note"
|
||
==
|
||
NOTE: {{ .text }}
|
||
==
|
||
<div class="note">{{ .text }}</div>
|
||
```
|
||
|
||
The name must be in the plugin's namespace and under `mail.partials.`; otherwise, or when the file is missing or the name is declared twice, the start-up fails. A plugin can ship partials without shipping templates.
|
||
|
||
A body or a layout calls a partial with its name and pairs of a key and a value:
|
||
|
||
```text
|
||
{{ partial "button" "url" .link "body" "Track the order" "type" "positive" }}
|
||
|
||
{{ partial "acme.blog::mail.partials.note" "text" .note }}
|
||
```
|
||
|
||
A bare name is one of the built-in partials; a plugin's partial is called by its full name, from any plugin's mail. The pairs become the partial's variables. The HTML section is used in the HTML part and the text section in the plain-text part.
|
||
|
||
| Built-in partial | Arguments | Renders |
|
||
|------------------|-----------|---------|
|
||
| `button` | `url`, `body`, `type` (`primary`, `positive` or `negative`) | A link styled as a button. |
|
||
| `panel` | `body` | A highlighted block; the body is Markdown. |
|
||
| `table` | `body` | A Markdown table. |
|
||
| `subcopy` | `body` | Small print under a rule; the body is Markdown. |
|
||
| `header` | `logo` (an image URL), `body` (a name), `url` (optional link) | A table row for a layout's header: the logo, with the name as its alternative text, or the name when there is no logo. |
|
||
| `footer` | `text` or `body` | A table row for a layout's footer; `text` is printed as it is (escaped), `body` is Markdown. |
|
||
|
||
In a body, write the call on a line of its own with blank lines around it. Bodies are Markdown and raw HTML in them is still dropped; postcard inserts a partial's HTML after the Markdown conversion, through a random token that a variable's value cannot contain. Inside a partial's HTML section, `{{ markdown .body }}` renders a value as Markdown.
|
||
|
||
## Built-in layouts
|
||
|
||
Three layouts are available to every plugin's templates without declaring an alias:
|
||
|
||
| `layout` | Renders |
|
||
|----------|---------|
|
||
| `default` | WinterCMS's default layout: a header with the Branding logo (or the site name when no logo is set), the message on a white card, and a footer with the copyright year and the site name. Used when the template names no layout. |
|
||
| `system` | WinterCMS's system layout: the same header and footer as `default`, the message on a padded white card, then a note that it was sent automatically. |
|
||
| `minimal` | The message directly in the page body, with the Branding logo above it when one is set. |
|
||
|
||
A plugin's own alias wins over `system` and `minimal`; `default` cannot be redefined.
|
||
|
||
Every layout gets these values besides `{{ .Content }}`: `{{ .Subject }}`, the CSS slots `{{ .brandCss }}` and `{{ .css }}`, `{{ .logoUrl }}` (see [Branding](#branding)), `{{ .siteName }}`, the site name, and `{{ .year }}`, the current year. The default and system layouts use the `header` and `footer` partials with them; the footer reads `© <year> <site name>`, or `© <year>` when there is no name, passed as the footer's `text`, so the site name is printed as typed, never as Markdown, and the header row is left out when there is neither a logo nor a name.
|
||
|
||
## Branding
|
||
|
||
A layout's style block has a brand slot, `{{ .brandCss }}`, before `{{ .css }}`. Until the branding settings are saved for the first time, the brand slot holds `mail.brandCss` from the configuration. From the first save on, it holds CSS that postcard compiles from the saved colours, and `mail.brandCss` is no longer used. `mail.css` is applied either way.
|
||
|
||
The settings are thirteen colours: the page and content backgrounds, the header, footer, heading, text and link colours, the button text and the primary, positive and negative button backgrounds, the panel background and the table border. Each is a six-digit hexadecimal colour such as `#2da7c7`, and one left empty takes WinterCMS's default. The compiled CSS styles plain elements (the page, links, headings, paragraphs, tables) as well as the built-in layouts and partials, so it shows in any layout that has the style block.
|
||
|
||
The settings also hold a logo. A layout shows it where it uses `{{ .logoUrl }}`:
|
||
|
||
```text
|
||
{{ if .logoUrl }}<img src="{{ .logoUrl }}" alt="">{{ end }}
|
||
```
|
||
|
||
The settings also hold a site name, given to layouts as `{{ .siteName }}`. The built-in layouts show it in the header (as the logo's alternative text when there is a logo) and in the footer. Left empty, the display name of `mail.from` is used (`Acme` for `Acme <no-reply@acme.test>`), so mail from an application that never saved Branding still carries a name.
|
||
|
||
A site name mail could not show safely is refused when the settings are saved: one holding a `javascript:`, `vbscript:` or `data:` address. Ordinary text with a colon, such as `Big Data: Summit`, and text such as `Online=Shop` or `onclick=` are accepted: the layouts print the name as escaped text. A name stored before this check, or a `mail.from` display name of that kind, is left out of mail at send time (the next name in line is used, or none), with a warning in the log; the message is still sent.
|
||
|
||
A mail client needs an absolute address, so the logo's URL is built at send time from the configuration: `storage.uploads.public_url` when it is set, otherwise `app.url` with `storage.uploads.public_path_prefix`; see [Absolute URLs for mail](storage.md#absolute-urls-for-mail). Set one of them, or the logo is left out and a warning is logged.
|
||
|
||
## Sample values for previews
|
||
|
||
A preview of a template has no caller to pass its variables. A template can therefore give sample values in its header, one key per variable: `sample.` followed by the variable's path, in the variable's own case.
|
||
|
||
```text
|
||
subject = "Your order {{ .order.code }}"
|
||
sample.name = "Ada"
|
||
sample.order.code = "ZAM-1"
|
||
==
|
||
Hi {{ .name }}, we received the payment for **{{ .order.code }}** from {{ .company }}.
|
||
```
|
||
|
||
The keys are optional and sending ignores them. Where a preview finds no sample, it shows the variable's path in square brackets, so the body above previews as "Hi Ada, we received the payment for **ZAM-1** from [company]." Nested fields and lists work without samples too: `{{ range .order.items }}{{ .description }}{{ end }}` previews one item, `[order.items.description]`. Saving an edited template runs the same render, so an edit that uses a variable the plugin never passes still shows up as a placeholder, not as an error.
|
||
|
||
Previews, the checks on save and test sends are `postcard.Editor`; see the [postcard README](../../modules/postcard/README.md) for its API.
|
||
|
||
## Sending
|
||
|
||
At boot, `postcard.Activate` publishes one `postcard.Mailer` on the application, and `postcard.BootPlugin` registers each plugin's templates as it boots. Look the mailer up with `app.Lookup[postcard.Mailer]()` and send a `postcard.Message` with the template name, the recipients and the variables. Tests build the catalog and a memory driver directly, and read back what was sent:
|
||
|
||
```go src=modules/postcard/example_test.go#ExampleMailer_Send
|
||
// At boot, postcard.BootPlugin registers what pact.HasMailTemplates
|
||
// declares; a test registers the same thing directly.
|
||
cat := postcard.NewCatalog()
|
||
err := cat.Register("acme.blog", mailFS,
|
||
[]string{"acme.blog::mail.welcome"},
|
||
map[string]string{"blog": "acme.blog::mail.layouts.blog"})
|
||
if err != nil {
|
||
fmt.Println(err)
|
||
return
|
||
}
|
||
driver := postcard.NewMemoryDriver() // mail.driver: memory
|
||
mailer := postcard.NewMailer(cat, driver, postcard.Options{From: "blog@example.com"})
|
||
|
||
err = mailer.Send(context.Background(), postcard.Message{
|
||
Template: "acme.blog::mail.welcome",
|
||
To: []string{"ada@example.com"},
|
||
Vars: map[string]any{"name": "Ada"},
|
||
})
|
||
if err != nil {
|
||
fmt.Println(err)
|
||
return
|
||
}
|
||
sent := driver.Messages()[0]
|
||
fmt.Println(sent.From, sent.To, sent.Subject)
|
||
fmt.Println(sent.Text)
|
||
fmt.Println(strings.Contains(sent.HTML, `<div class="blog-mail"><p>Hi <strong>Ada</strong>`))
|
||
|
||
// Header injection is refused before any driver sees the message.
|
||
err = mailer.Send(context.Background(), postcard.Message{
|
||
Template: "acme.blog::mail.welcome",
|
||
To: []string{"ada@example.com\r\nBcc: all@example.com"},
|
||
Vars: map[string]any{"name": "Ada"},
|
||
})
|
||
fmt.Println(err != nil, len(driver.Messages()))
|
||
// Output:
|
||
// blog@example.com [ada@example.com] Welcome, Ada
|
||
// Hi **Ada**, thanks for joining the blog.
|
||
//
|
||
// -- The Acme blog
|
||
// true
|
||
// true 1
|
||
```
|
||
|
||
postcard does not pick a locale: the caller passes the full name. A per-language version of a template is a file named after the template, a dash and the locale (`welcome-en.htm`, sent as `acme.blog::mail.welcome-en`). A name with its own file always renders that file. A name the catalog does not hold, of the form `<template>-<locale>` where `<template>` is registered and `<locale>` is a locale tag (two letters, optionally followed by `-` or `_` and a 2 to 8 character subtag, such as `de` or `pt-BR`), sends the default-locale version: the locale's own version when an administrator customized it, else the customized template, else the template's file. Any other unknown name fails with `postcard: unknown template <name>`. So a plugin can pass `<template>-<locale>` for every locale it serves, and a locale without a file still sends mail, in the default language until someone writes that locale's version in the admin.
|
||
|
||
Before a driver sees a message, postcard refuses a subject or address with a line break, parses every address with `net/mail`, and rejects rendered HTML that contains script, iframe, object or embed tags, inline event handlers, or `javascript:`, `vbscript:` or `data:` URLs. URLs are looked for where a mail client reads one: URL-bearing attributes such as `href` and `src`, `style` attributes, style elements, comments and `meta` content, after character references are decoded and whitespace removed, so `href="javascript:..."` and `values="java	script:..."` are refused. Markup inside `noscript`, `title`, `textarea`, `style`, `xmp` and similar elements, and inside comments, is checked as well, since a mail client may read it as markup. Text is neither markup nor a URL: a body, a variable or a site name such as `metadata:`, `Big Data: Summit` or `buy one = get one free` is sent; only attributes count as event handlers. Variables are escaped by Go's `html/template`.
|
||
|
||
`postcard.Mailer.Send` delivers before it returns. To keep a request fast, send from a queued job, and send after the write that triggered the mail has committed; see [Queued jobs](jobs.md) and [Transactions](../database/transactions.md).
|
||
|
||
## Overrides from the admin
|
||
|
||
A plugin's mail files are the default text. postcard also owns a set of mail tables, created by `migrate` with the framework's other tables, where an administrator's edit of a template is stored. A row of `system_mail_templates` with `is_custom` set overrides the template named in its `code`: its subject, body and layout replace the file's. The body keeps the file's format, Markdown with Go template variables.
|
||
|
||
`postcard.Mailer.Send` reads that row on every send and caches nothing, so an edit applies to the next message in every process that shares the database, a `queue:work` worker included. The subject is the first of these that is set:
|
||
|
||
1. `postcard.Message.Subject`, when the caller passes one;
|
||
2. the override's subject;
|
||
3. the file's subject.
|
||
|
||
Layouts and partials have rows too, in `system_mail_layouts` and `system_mail_partials`. A customized row replaces the file's wrappers or sections, and a layout row whose `code` is not a file layout's name is a layout that exists only in the database, which a template override can select. A layout row's CSS goes before `mail.css` in the layout's style block.
|
||
|
||
An override cannot stop mail from going out:
|
||
|
||
- With no database, or before `migrate` has created the tables, the file version is sent. A failed lookup is logged as a warning, at most once a minute.
|
||
- An override of the template, its layout or a partial that does not parse, fails while rendering (it uses a field of a variable the caller does not pass, for example) or fails the safety checks is logged as an error with the template name, and the message is sent from the files alone.
|
||
- An override whose layout no longer exists is rendered in the `default` layout, with a warning.
|
||
|
||
The log lines carry the component `postcard`. In a test, pass any `postcard.OverrideSource` in `postcard.Options.Overrides` to supply overrides without a database; `postcard.NewDBSource` is the one `postcard.Activate` installs.
|
||
|
||
## Editing mail in the admin
|
||
|
||
Every application with an admin gets the mail screens in Settings → Mail, with no setup in the application or its plugins. They are served by the admin itself (cabana) over postcard's tables:
|
||
|
||
- **Mail templates** lists every template the application's plugins register, one row per template however many locales the application has: `acme.blog::mail.welcome` and its `acme.blog::mail.welcome-en` variant are one row. The list shows the code, the subject, the file's description, the customized locales (Default and the locale codes whose version was customized, at most three and then +N) and the layout. The Customized and File changed badges and the status filter (customized, not customized, file changed) are about the whole template: any of its locale versions. The form edits the subject, the Markdown message and the layout, chosen from every file layout and every layout created in the admin. The description stays the file's. A **Language** select under the title switches between the template's versions: Default (the template's own file), every locale with its own file, and every other locale of the application. A locale with neither a file nor a customization shows the default version, which is what it sends; saving it creates that locale's own version, and Reset to file version returns it to the default version. The application's locales are the admin's translation locales plus the content locales of a translate plugin, when one is installed.
|
||
|
||
The screen needs `system.manage_mail_templates` (see [Users and permissions](../backend/users-and-permissions.md#permissions)). Templates come from files, so the list has no create and no delete.
|
||
|
||
The rows exist before anyone edits a template: when the admin starts, it writes an index row for every file template, layout and partial (`postcard.SyncIndex`) and for every locale a template ships no file for (`postcard.EnsureLocaleRows`), and keeps a row that is not customized equal to its file. A row whose plugin is no longer installed stays in the table but is not listed. If the tables are not there yet when the admin starts, the first open of a mail list writes the rows.
|
||
|
||
Saving a template stores your subject, message and layout in its row and marks it customized, together with the hash of the file the change was based on. From then on your version is sent instead of the file, until the template is reset to the file version. A save is checked the way a send would render it (`postcard.Editor.Validate`): a message that does not parse, does not render with the sample values or fails the safety checks is refused with a line under the field, and nothing is stored.
|
||
|
||
- **Mail layouts** lists postcard's default layout first, then every other file layout and every custom layout by name; the source column is the plugin, or Custom for a layout that exists only in the database. The form has HTML, Plain text and CSS tabs. A file layout's name stays the file's. **New layout** creates a custom layout: its code (lowercase letters, digits and dashes, and not used by another layout) is what template overrides store, so it cannot be changed later. A custom layout can be deleted, unless customized templates still use it: the refusal names the layout and how many templates use it.
|
||
- **Mail partials** lists every partial, postcard's built-in ones included. The form edits the HTML and plain-text sections and shows how to call the partial, for example `{{ partial "button" "body" .body "type" .type "url" .url }}`.
|
||
|
||
Layouts and partials need `system.manage_mail_layouts`.
|
||
|
||
On a customized template, file layout or partial, **Reset to file version** returns the row to its file: your subject, message and layout choice (or the wrappers, CSS or sections) are discarded, and the file version is sent again. Rows that come from files are never deleted, and a custom layout has no file version to reset to.
|
||
|
||
When a plugin update changes a file you customized, your version is still sent, but the list marks the row Customized and File changed, the status filter's File changed choice finds it, and the form shows a notice. The File version tab shows the lines your version changed against the current file (lines starting with + are only in your version, lines starting with − only in the file) and the file itself. Saving your version again marks the change as reviewed; resetting takes the new file.
|
||
|
||
Each mail form has a live preview (`POST /mail/preview`) that renders the unsaved draft through `postcard.Editor` with the template's sample values (or sample content for layouts, partials and branding). **Send test to me** (`POST /mail/test-send`) delivers that draft only to the signed-in administrator's own email: the body never carries a recipient, personal API tokens are refused, and each administrator may send at most five tests per ten minutes (429 with `Retry-After` when the limit is hit).
|
||
|
||
## Drivers
|
||
|
||
`mail.driver` selects the driver:
|
||
|
||
| Driver | Delivers |
|
||
|--------|----------|
|
||
| `memory` (default) | Nowhere: messages are kept in the process, for tests. |
|
||
| `log` | To the log: headers and the text part, never the HTML part or credentials. For development. |
|
||
| `smtp` | Through an SMTP server with the configured TLS policy. |
|
||
|
||
The SMTP settings go in `config/mail.yaml`, with the password in the environment (`SUMMER_MAIL__SMTP__PASSWORD`):
|
||
|
||
```yaml
|
||
driver: smtp
|
||
from: blog@example.com
|
||
smtp:
|
||
host: smtp.example.com
|
||
port: 587
|
||
username: blog
|
||
password: <secret>
|
||
tls: mandatory
|
||
```
|
||
|
||
`mail.smtp.tls` defaults to `mandatory`: the connection must upgrade with STARTTLS, and sending fails if the server does not offer it. postcard never infers a plain connection. The other two values exist for local mail catchers only:
|
||
|
||
- `starttls` (or `opportunistic`) uses TLS when the server offers it and sends in plain text when it does not, so an attacker on the network can strip the upgrade.
|
||
- `none` sends in plain text.
|
||
|
||
> [!WARNING]
|
||
> Use `starttls` or `none` only against a local development mail catcher. In production, keep the default `mandatory`.
|