feat(postcard): inline mail CSS at render with a per-layout opt-out

- github.com/vanng822/go-premailer v1.38.0 (default options) inlines the
  rendered HTML after the safety checks; the result is checked again,
  HTML without a style element is left as it is, an inliner error sends
  the style block only and warns (key inline:<layout>)
- opt-out: layout header key disable_auto_inline_css, the layouts column
  of the same name (migration 202611130003), LayoutFile/LayoutOverride/
  Draft.DisableAutoInlineCSS; SyncIndex mirrors and ResetOverride restores
  the file's value
- cabana layout form switch on the CSS tab, mapped into the layout draft
  and the save validation; en/pl copy
- tests: TestMailPartialsSmoke/inline, TestMailEditorSmoke/inline_flag,
  the layouts switch in TestMailScreensSmoke; CSS-slot tests read the
  style block through a no-op inliner
- 35-06 Task 2 (G-35-8)
This commit is contained in:
Jakub Zych
2026-11-13 21:12:01 +01:00
parent dcd0ae5338
commit d320733510
22 changed files with 551 additions and 85 deletions

View File

@@ -26,7 +26,7 @@ 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. The brand CSS (`mail.brandCss`, or the saved Branding) and `mail.css` go 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, 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 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.
@@ -181,6 +181,18 @@ Markdown drops raw HTML, so a call in a body does not insert the partial's HTML
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 inlined HTML is checked again, so a `javascript:`, `vbscript:` or `data:` address that reaches a `style` attribute fails the render as before. 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. When the inliner fails on a message, 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 layout calls 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. Its text wrapper is the message, a blank line and the footer's text section.
| Partial | Arguments | Renders |
@@ -394,7 +406,7 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
| `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. 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.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. |
@@ -412,9 +424,9 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t
| `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. |
| `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.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. |
@@ -454,7 +466,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), 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).
- 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`), `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`.

View File

@@ -5,6 +5,7 @@ import (
"errors"
"path/filepath"
"reflect"
"regexp"
"strings"
"testing"
@@ -36,6 +37,17 @@ func styleBlock(t *testing.T, html string) string {
return css
}
// styleAttr matches a style attribute, which inlining adds to elements.
var styleAttr = regexp.MustCompile(` style="[^"]*"`)
// unstyled returns html without its style attributes, for assertions on
// the markup of inlined mail.
func unstyled(html string) string { return styleAttr.ReplaceAllString(html, "") }
// noInline is an inliner that leaves the HTML as it is, for tests of what
// fills the CSS slots rather than of inlining (TestMailPartialsSmoke/inline).
func noInline(html string) (string, error) { return html, nil }
// TestMailBrandSmoke covers Branding: the compiled brand CSS and its colour
// checks, the precedence over mail.brandCss once the settings row exists,
// the logo URL built at send time from configuration, and the editor's
@@ -173,8 +185,11 @@ func TestMailBrandSmoke(t *testing.T) {
}
})
// The preview checks read the style block: what fills the CSS slots, not
// how it is inlined.
t.Run("preview", func(t *testing.T) {
ed, drv := newEditor(t, nil)
ed.m.inline = noInline
ed.m.opts.CSS, ed.m.opts.BrandCSS = "p{margin:1px}", ".cfg{color:blue}"
draft := Draft{Kind: KindBrand, Brand: &Brand{LinkColor: "#112233", ButtonPrimaryBg: "#445566"}}
if problem := ed.Validate(ctx, draft); problem != nil {
@@ -219,6 +234,7 @@ func TestMailBrandSmoke(t *testing.T) {
Brand: &Brand{LinkColor: "#999999", LogoURL: "https://cdn.example.com/saved.png"},
Layouts: map[string]LayoutOverride{defaultLayoutName: {HTML: `<img src="{{ .logoUrl }}" alt=""><style>{{ .brandCss }}</style>{{ .Content }}`, Text: "{{ .logoUrl }}\n{{ .Content }}"}},
})
ed.m.inline = noInline
got, err = ed.Preview(ctx, Draft{Kind: KindBrand, Brand: &Brand{LinkColor: "#112233", LogoURL: "https://cdn.example.com/u/logo.png"}})
if err != nil {
t.Fatal(err)
@@ -263,9 +279,13 @@ func TestMailBrandSmoke(t *testing.T) {
// A logo and a site name: the logo in the header, the name as its
// alternative text, the card, the styled button and the footer.
got := send("blog@example.com", &Brand{LogoURL: logo, SiteName: " Acme Mail "})
if style := buttonStyle(t, got.HTML); !strings.Contains(style, "background-color:#d66829") {
t.Errorf("logo and name: the button is not styled: %q", style)
}
got.HTML = unstyled(got.HTML)
for _, want := range []string{
`class="wrapper layout-default"`,
"<td class=\"header\">\n<img src=\"" + logo + "\" class=\"logo\" alt=\"Acme Mail\" />",
"<td class=\"header\">\n<img src=\"" + logo + "\" class=\"logo\" alt=\"Acme Mail\"/>",
`class="inner-body"`,
"<td class=\"content-cell\">\n<p>Hi Ada</p>",
`class="button button-primary"`,
@@ -285,29 +305,34 @@ func TestMailBrandSmoke(t *testing.T) {
// A site name without a logo: the name in the header.
got = send("blog@example.com", &Brand{SiteName: "Acme Mail"})
got.HTML = unstyled(got.HTML)
if !strings.Contains(got.HTML, "<td class=\"header\">\n<span>Acme Mail</span>") || strings.Contains(got.HTML, "<img") {
t.Errorf("name only: HTML = %s", got.HTML)
}
// The name reaches the HTML escaped, also in the alt attribute.
got = send("blog@example.com", &Brand{LogoURL: logo, SiteName: `Bob "&" <b>Co</b>`})
got.HTML = unstyled(got.HTML)
if !strings.Contains(got.HTML, `alt="Bob &#34;&amp;&#34; &lt;b&gt;Co&lt;/b&gt;"`) || strings.Contains(got.HTML, "<b>Co</b>") {
t.Errorf("the site name is not escaped:\n%s", got.HTML)
}
// No Branding row: the display name of mail.from.
got = send("Acme <no-reply@acme.test>", nil)
got.HTML = unstyled(got.HTML)
if !strings.Contains(got.HTML, "<td class=\"header\">\n<span>Acme</span>") || !strings.Contains(got.HTML, "<p>"+copyright()+" Acme</p>") {
t.Errorf("mail.from name: HTML = %s", got.HTML)
}
// A Branding row with an empty name falls back to mail.from too.
got = send("Acme <no-reply@acme.test>", &Brand{SiteName: " "})
got.HTML = unstyled(got.HTML)
if !strings.Contains(got.HTML, "<span>Acme</span>") {
t.Errorf("empty site name: HTML = %s", got.HTML)
}
// Neither a name nor a logo: no header row, the year alone.
got = send("no-reply@acme.test", nil)
got.HTML = unstyled(got.HTML)
if strings.Contains(got.HTML, `class="header"`) || !strings.Contains(got.HTML, "<p>"+copyright()+"</p>") {
t.Errorf("no name, no logo: HTML = %s", got.HTML)
}
@@ -330,6 +355,9 @@ func TestMailBrandSmoke(t *testing.T) {
gdb := mailPostgres(t)
cfg := brandCfg(t, map[string]string{"mail.yaml": "driver: memory\ncss: \"p{margin:1px}\"\nbrandCss: \".cfg{color:blue}\"\n"})
m, drv, logs := bootMailAppCfg(t, gdb, cfg)
// The style block shows which CSS fills the slots; inlining would
// move it onto the elements.
m.inline = noInline
// No Branding row: the configured brand CSS, as before.
sendFixture(t, m, acmeNotice, "")

View File

@@ -71,6 +71,8 @@ func TestBrand(t *testing.T) {
CSS: ".mail-css{margin:0}",
Overrides: fakeOverrides{ov: ov},
})
// Which CSS fills the slots, not how it is inlined.
m.(*mailer).inline = noInline
sendFixture(t, m, acmeNotice, "")
got := lastMessage(t, drv)
if !strings.Contains(got.HTML, "#112233") {
@@ -92,6 +94,7 @@ func TestBrand(t *testing.T) {
}
drv := NewMemoryDriver()
m := NewMailer(cat, drv, Options{BrandCSS: ".from-config{color:red}", CSS: ".mail-css{margin:0}"})
m.(*mailer).inline = noInline
sendFixture(t, m, acmeNotice, "")
got := lastMessage(t, drv)
if !strings.Contains(got.HTML, ".from-config") || !strings.Contains(got.HTML, ".mail-css") {

View File

@@ -44,6 +44,8 @@ type Draft struct {
HTML string
Text string
CSS string
// DisableAutoInlineCSS is a layout draft's opt-out of CSS inlining.
DisableAutoInlineCSS bool
// Brand is a branding draft. Nil is the default brand.
Brand *Brand
@@ -261,7 +263,7 @@ func (e *Editor) renderLayout(d Draft, ov Overrides, opts renderOptions) (Render
for k, v := range ov.Layouts {
layouts[k] = v
}
layouts[code] = LayoutOverride{Name: code, HTML: d.HTML, Text: d.Text, CSS: d.CSS}
layouts[code] = LayoutOverride{Name: code, HTML: d.HTML, Text: d.Text, CSS: d.CSS, DisableAutoInlineCSS: d.DisableAutoInlineCSS}
ov.Layouts = layouts
opts.overrides = ov
sample := sampleMessage()

View File

@@ -301,8 +301,9 @@ func TestMailEditorSmoke(t *testing.T) {
t.Errorf("draft layout not applied: %q / %q", got.Subject, got.HTML)
}
// A layout draft wraps the sample message.
got, err = ed.Preview(ctx, Draft{Kind: KindLayout, Name: "promo", HTML: `<div class="promo">{{ .Content }}</div><style>{{ .css }}</style>`, Text: "PROMO\n{{ .Content }}", CSS: ".promo{margin:0}"})
// A layout draft wraps the sample message; this one keeps its style
// block.
got, err = ed.Preview(ctx, Draft{Kind: KindLayout, Name: "promo", HTML: `<div class="promo">{{ .Content }}</div><style>{{ .css }}</style>`, Text: "PROMO\n{{ .Content }}", CSS: ".promo{margin:0}", DisableAutoInlineCSS: true})
if err != nil {
t.Fatalf("layout preview: %v", err)
}
@@ -756,6 +757,73 @@ FROM `+TemplatesTable+` t LEFT JOIN `+LayoutsTable+` l ON l.id = t.layout_id WHE
}
}
})
t.Run("inline_flag", func(t *testing.T) {
gdb := mailPostgres(t)
const plain = "acme.shop::mail.layouts.plain"
cat := NewCatalog()
fsys := fstest.MapFS{
"views/mail/x.htm": {Data: []byte("subject = \"X\"\nlayout = \"plain\"\n==\nx\n")},
"views/mail/layouts/plain.htm": {Data: []byte("name = \"Plain\"\ndisable_auto_inline_css = true\n==\n{{ .Content }}\n==\n<div>{{ .Content }}</div>\n")},
}
if err := cat.Register("acme.shop", fsys, []string{"acme.shop::mail.x"}, map[string]string{"plain": plain}); err != nil {
t.Fatal(err)
}
flag := func(code string) bool {
t.Helper()
var v []bool
if err := gdb.Raw(`SELECT disable_auto_inline_css FROM `+LayoutsTable+` WHERE code = ?`, code).Scan(&v).Error; err != nil || len(v) != 1 {
t.Fatalf("flag of %s: %v %v", code, v, err)
}
return v[0]
}
sync := func() {
t.Helper()
if err := SyncIndex(ctx, gdb, cat, nil); err != nil {
t.Fatal(err)
}
}
// The index row mirrors the file's header key while not customized.
sync()
if !flag(plain) || flag(defaultLayoutName) {
t.Fatalf("after sync: plain %v, default %v", flag(plain), flag(defaultLayoutName))
}
if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = FALSE WHERE code = '` + plain + `'`).Error; err != nil {
t.Fatal(err)
}
sync()
if !flag(plain) {
t.Error("sync did not restore the file's value on a row that is not customized")
}
// A customized row keeps its own value, and the source reports it.
if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = FALSE, is_custom = TRUE, base_hash = file_hash WHERE code = '` + plain + `'`).Error; err != nil {
t.Fatal(err)
}
sync()
if flag(plain) {
t.Error("sync overwrote the value of a customized row")
}
ov, err := NewDBSource(appWith(t, gdb)).MailOverrides(ctx, "")
if err != nil || ov.Layouts[plain].DisableAutoInlineCSS {
t.Errorf("overrides = %+v, %v", ov.Layouts, err)
}
if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = TRUE WHERE code = '` + plain + `'`).Error; err != nil {
t.Fatal(err)
}
if ov, err = NewDBSource(appWith(t, gdb)).MailOverrides(ctx, ""); err != nil || !ov.Layouts[plain].DisableAutoInlineCSS {
t.Errorf("overrides = %+v, %v", ov.Layouts, err)
}
// Reset writes the file's value back.
if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = FALSE WHERE code = '` + plain + `'`).Error; err != nil {
t.Fatal(err)
}
if err := ResetOverride(ctx, gdb, cat, KindLayout, plain); err != nil {
t.Fatal(err)
}
if !flag(plain) {
t.Error("reset did not write the file's value back")
}
})
}
func with(d Draft, edit func(*Draft)) Draft { edit(&d); return d }

View File

@@ -0,0 +1,31 @@
package postcard
import (
"fmt"
"github.com/vanng822/go-premailer/premailer"
)
// inlineCSS copies the rules of html's style elements onto the elements they
// match, as WinterCMS does with CssToInlineStyles, so that mail clients that
// drop the style block still show the design. Rules that cannot be inlined,
// such as media queries and pseudo-classes, are kept in a style element.
// Classes are kept, and CSS widths and heights are mirrored to the width
// and height attributes (go-premailer's default options). A panic in the
// inliner is returned as an error.
func inlineCSS(html string) (out string, err error) {
defer func() {
if r := recover(); r != nil {
out, err = "", fmt.Errorf("postcard: inline CSS: %v", r)
}
}()
p, err := premailer.NewPremailerFromString(html, premailer.NewOptions())
if err != nil {
return "", fmt.Errorf("postcard: inline CSS: %w", err)
}
out, err = p.Transform()
if err != nil {
return "", fmt.Errorf("postcard: inline CSS: %w", err)
}
return out, nil
}

View File

@@ -54,6 +54,9 @@ type mailer struct {
// log receives override warnings and failures; nil means moduleLog.
log *slog.Logger
warned warnGate
// inline inlines a message's CSS; nil means inlineCSS. Tests set it to
// force an inliner error.
inline func(html string) (string, error)
}
// NewMailer returns a mailer that renders from cat and delivers through
@@ -149,7 +152,10 @@ func (m *mailer) render(ctx context.Context, msg Message) (RenderedMessage, erro
// keeps mail.brandCss. The site name is the Branding's, else the display
// name of mail.from.
func (m *mailer) options(brand *Brand) renderOptions {
opts := renderOptions{css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: siteName(brand, m.opts.From), year: time.Now().Year()}
opts := renderOptions{
css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: siteName(brand, m.opts.From), year: time.Now().Year(),
inline: m.inline, warn: m.warn,
}
if brand == nil {
return opts
}

View File

@@ -136,7 +136,7 @@ Body **{{ .Name }}**.
t.Fatalf("Register: %v", err)
}
drv := NewMemoryDriver()
mail := NewMailer(cat, drv, Options{CSS: "p{color:red}", BrandCSS: ".brand{color:blue}"})
mail := NewMailer(cat, drv, Options{CSS: "p{color:red}", BrandCSS: ".layout-hello{color:blue}"})
if err := mail.Send(context.Background(), Message{
Template: "golem15.hello::mail.note",
To: []string{"ada@example.test"},
@@ -154,7 +154,8 @@ Body **{{ .Name }}**.
if !strings.Contains(got[0].HTML, `class="layout-hello"`) || !strings.Contains(got[0].HTML, "<strong>Ada</strong>") {
t.Fatalf("HTML wrapper = %q", got[0].HTML)
}
if !strings.Contains(got[0].HTML, "p{color:red}") || !strings.Contains(got[0].HTML, ".brand{color:blue}") {
// mail.css and the brand CSS are inlined onto the elements they match.
if !strings.Contains(got[0].HTML, `<p style="color:red">`) || !strings.Contains(got[0].HTML, `<div class="layout-hello" style="color:blue">`) {
t.Fatalf("shared css missing: %q", got[0].HTML)
}

View File

@@ -343,12 +343,13 @@ func TestMailOverrideSmoke(t *testing.T) {
gdb := mailPostgres(t)
m, drv, logs := bootMailApp(t, gdb)
stmts := []string{
// A customized file layout, a database-only layout and an index
// row that is not customized.
`INSERT INTO ` + LayoutsTable + ` (code, source, name, content_html, content_text, content_css, is_custom) VALUES
('acme.blog::mail.layouts.blog', 'acme.blog', 'Blog', '<div class="custom-blog">{{ .Content }}</div><style>{{ .css }}</style>', '[custom] {{ .Content }}', '.custom{margin:0}', TRUE),
('promo', NULL, 'Promo', '<div class="promo">{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Shop" }}</div>', 'PROMO {{ .Content }}', '', TRUE),
('` + defaultLayoutName + `', 'postcard', 'Default', '<div class="mirror">{{ .Content }}</div>', 'MIRROR {{ .Content }}', '', FALSE)`,
// A customized file layout that keeps its style block (no
// inlining), a database-only layout and an index row that is not
// customized.
`INSERT INTO ` + LayoutsTable + ` (code, source, name, content_html, content_text, content_css, is_custom, disable_auto_inline_css) VALUES
('acme.blog::mail.layouts.blog', 'acme.blog', 'Blog', '<div class="custom-blog">{{ .Content }}</div><style>{{ .css }}</style>', '[custom] {{ .Content }}', '.custom{margin:0}', TRUE, TRUE),
('promo', NULL, 'Promo', '<div class="promo">{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Shop" }}</div>', 'PROMO {{ .Content }}', '', TRUE, FALSE),
('` + defaultLayoutName + `', 'postcard', 'Default', '<div class="mirror">{{ .Content }}</div>', 'MIRROR {{ .Content }}', '', FALSE, FALSE)`,
// A customized built-in partial.
`INSERT INTO ` + PartialsTable + ` (code, source, name, content_html, content_text, is_custom) VALUES
('postcard::mail.partials.button', 'postcard', 'Button', '<a class="btn" href="{{ .url }}">{{ .body }}</a>', '{{ .body }}: {{ .url }}', TRUE),
@@ -387,9 +388,12 @@ func TestMailOverrideSmoke(t *testing.T) {
if all.Template != nil || len(all.Layouts) != 2 || len(all.Partials) != 1 {
t.Errorf("overrides without a template name = %+v", all)
}
if l := all.Layouts["promo"]; l.Name != "Promo" || !strings.HasPrefix(l.Text, "PROMO") {
if l := all.Layouts["promo"]; l.Name != "Promo" || !strings.HasPrefix(l.Text, "PROMO") || l.DisableAutoInlineCSS {
t.Errorf("promo layout = %+v", l)
}
if l := all.Layouts["acme.blog::mail.layouts.blog"]; !l.DisableAutoInlineCSS {
t.Errorf("blog layout = %+v, want the inlining opt-out", l)
}
if logs.Len() != 0 {
t.Errorf("unexpected log output:\n%s", logs)
}

View File

@@ -1,8 +1,12 @@
package postcard
import (
"bytes"
"context"
"errors"
"io/fs"
"log/slog"
"regexp"
"strconv"
"strings"
"testing"
@@ -51,6 +55,25 @@ var (
_ pact.HasMailTemplates = templatesOnly{}
)
// buttonTag finds the opening tag of the button partial's link.
var buttonTag = regexp.MustCompile(`<a [^>]*button-primary[^>]*>`)
// buttonStyle returns the style attribute of the button partial's link, or
// empty when it has none.
func buttonStyle(t *testing.T, html string) string {
t.Helper()
tag := buttonTag.FindString(html)
if tag == "" {
t.Fatalf("no button in %s", html)
}
_, style, ok := strings.Cut(tag, ` style="`)
if !ok {
return ""
}
style, _, _ = strings.Cut(style, `"`)
return style
}
// copyright is the footer line of the built-in layouts without a site name.
func copyright() string { return "© " + strconv.Itoa(time.Now().Year()) }
@@ -219,7 +242,7 @@ func TestMailPartialsSmoke(t *testing.T) {
}
for _, want := range []string{
"<p>Hi Ada</p>\n<table class=\"action\"",
`<a href="https://example.com/go?a=1&amp;b=2" class="button button-primary" target="_blank">Go</a>`,
`<a class="button button-primary" href="https://example.com/go?a=1&amp;b=2" target="_blank">Go</a>`,
"</table>\n<p>Bye</p>",
} {
if !strings.Contains(msg.HTML, want) {
@@ -340,9 +363,9 @@ func TestMailPartialsSmoke(t *testing.T) {
m, drv := partialsMailer(t, Options{CSS: "p{color:red}", BrandCSS: ".brand{color:blue}"}, nil)
msg := sendTemplate(t, m, drv, "acme.blog::mail.auto", nil)
for _, want := range []string{
`class="wrapper layout-system"`, "<p>Done.</p>",
// mail.css is inlined onto the paragraph.
`class="wrapper layout-system"`, `<p style="color:red">Done.</p>`,
`<table class="subcopy"`, "<strong>This is an automatic message. Please do not reply to it.</strong>",
".brand{color:blue}", "p{color:red}",
} {
if !strings.Contains(msg.HTML, want) {
t.Errorf("system layout: HTML lacks %q:\n%s", want, msg.HTML)
@@ -353,11 +376,12 @@ func TestMailPartialsSmoke(t *testing.T) {
}
msg = sendTemplate(t, m, drv, "acme.blog::mail.bare", nil)
if !strings.Contains(msg.HTML, "<body>\n<p>Done.</p>\n\n</body>") || strings.Contains(msg.HTML, "content-body") || strings.Contains(msg.HTML, "layout-system") {
if !strings.Contains(msg.HTML, "<body>\n<p style=\"color:red\">Done.</p>\n\n\n</body>") || strings.Contains(msg.HTML, "content-body") || strings.Contains(msg.HTML, "layout-system") {
t.Errorf("minimal layout: HTML = %q", msg.HTML)
}
if !strings.Contains(msg.HTML, "<style type=\"text/css\">.brand{color:blue}p{color:red}</style>") {
t.Errorf("minimal layout: style block = %q", msg.HTML)
// Every rule was inlined or matched nothing: no style block is left.
if strings.Contains(msg.HTML, "<style") {
t.Errorf("minimal layout: style block left = %q", msg.HTML)
}
if msg.Text != "Done." {
t.Errorf("minimal layout: text = %q", msg.Text)
@@ -385,6 +409,111 @@ func TestMailPartialsSmoke(t *testing.T) {
}
})
t.Run("inline", func(t *testing.T) {
brand := &Brand{ButtonPrimaryBg: "#445566"}
welcome := map[string]any{"Name": "Ada", "Link": "https://example.com/go"}
const media = "@media only screen and (max-width: 600px) { .inner-body { width: 100% !important; } }"
// The default layout: the brand CSS is on the elements, the DOCTYPE
// and the classes are kept, and the safety checks still pass.
m, drv := partialsMailer(t, Options{CSS: media}, &Overrides{Brand: brand})
inlined := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
if !strings.HasPrefix(inlined.HTML, `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"`) {
t.Errorf("the DOCTYPE line was lost:\n%s", inlined.HTML)
}
if style := buttonStyle(t, inlined.HTML); !strings.Contains(style, "background-color:#445566") {
t.Errorf("the button carries no inlined brand colour: style=%q\n%s", style, inlined.HTML)
}
if !strings.Contains(inlined.HTML, `class="inner-body"`) || validateHTML(inlined.HTML) != nil {
t.Errorf("classes lost or the inlined HTML fails the safety checks:\n%s", inlined.HTML)
}
// A media query cannot be inlined: it stays in a style element.
if css := styleBlock(t, inlined.HTML); !strings.Contains(css, "@media only screen and (max-width: 600px)") || !strings.Contains(css, ".inner-body") {
t.Errorf("the media query is not in a style element:\n%s", css)
}
if strings.Contains(inlined.HTML, "width:100% !important") {
t.Errorf("a media-query rule reached an element:\n%s", inlined.HTML)
}
// optedOut checks a message whose layout kept its style block only.
optedOut := func(name string, msg RenderedMessage) {
t.Helper()
if style := buttonStyle(t, msg.HTML); style != "" {
t.Errorf("%s: the button has an inlined style %q", name, style)
}
if css := styleBlock(t, msg.HTML); !strings.Contains(css, "#445566") {
t.Errorf("%s: the style block lost the brand CSS:\n%s", name, css)
}
}
// A file layout with the header key opts out.
for _, value := range []string{"true", "1", "Yes"} {
fsys := fstest.MapFS{
"views/mail/plain.htm": {Data: []byte("subject = \"Plain\"\nlayout = \"plain\"\n==\n{{ partial \"button\" \"url\" \"https://example.com\" \"body\" \"Go\" }}\n")},
"views/mail/layouts/plain.htm": {Data: []byte("name = \"Plain\"\ndisable_auto_inline_css = " + value + "\n==\n{{ .Content }}\n==\n<html><head><style>{{ .brandCss }}</style></head><body>{{ .Content }}</body></html>\n")},
}
cat := NewCatalog()
if err := cat.Register("acme.shop", fsys, []string{"acme.shop::mail.plain"}, map[string]string{"plain": "acme.shop::mail.layouts.plain"}); err != nil {
t.Fatal(err)
}
if f, ok := cat.Layout("acme.shop::mail.layouts.plain"); !ok || !f.DisableAutoInlineCSS {
t.Errorf("header value %q: LayoutFile = %+v", value, f)
}
drv := NewMemoryDriver()
optedOut("file layout "+value, sendTemplate(t, NewMailer(cat, drv, Options{Overrides: fakeOverrides{ov: Overrides{Brand: brand}}}), drv, "acme.shop::mail.plain", nil))
}
if f, _ := NewCatalog().Layout(defaultLayoutName); f.DisableAutoInlineCSS {
t.Error("the built-in default layout opts out")
}
// A database layout with the column set opts out; without it, it inlines.
def, _ := NewCatalog().Layout(defaultLayoutName)
ov := &Overrides{Brand: brand, Layouts: map[string]LayoutOverride{defaultLayoutName: {HTML: def.HTML, Text: def.Text, DisableAutoInlineCSS: true}}}
m, drv = partialsMailer(t, Options{}, ov)
dbOptedOut := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
optedOut("database layout", dbOptedOut)
if dbOptedOut.Text != inlined.Text {
t.Errorf("the text part changed with the opt-out: %q, want %q", dbOptedOut.Text, inlined.Text)
}
ov.Layouts[defaultLayoutName] = LayoutOverride{HTML: def.HTML, Text: def.Text}
m, drv = partialsMailer(t, Options{}, ov)
if style := buttonStyle(t, sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome).HTML); !strings.Contains(style, "#445566") {
t.Errorf("a database layout without the column did not inline: %q", style)
}
// A layout draft with the flag previews the same way.
ed, _ := newEditor(t, &Overrides{Brand: brand})
draft := Draft{Kind: KindLayout, HTML: `<html><head><style>{{ .brandCss }}</style></head><body>{{ .Content }}</body></html>`, Text: "{{ .Content }}"}
prev, err := ed.Preview(context.Background(), draft)
if err != nil {
t.Fatal(err)
}
if style := buttonStyle(t, prev.HTML); !strings.Contains(style, "#445566") {
t.Errorf("a layout draft without the flag did not inline: %q", style)
}
draft.DisableAutoInlineCSS = true
if prev, err = ed.Preview(context.Background(), draft); err != nil {
t.Fatal(err)
}
optedOut("layout draft", RenderedMessage{HTML: prev.HTML})
// An inliner error sends the un-inlined HTML and warns once.
m, drv = partialsMailer(t, Options{CSS: media}, &Overrides{Brand: brand})
mm := m.(*mailer)
var logs bytes.Buffer
mm.log = slog.New(slog.NewTextHandler(&logs, nil))
mm.inline = func(string) (string, error) { return "", errors.New("inliner broke") }
failed := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome)
optedOut("inliner error", failed)
if n := strings.Count(logs.String(), "level=WARN"); n != 1 || !strings.Contains(logs.String(), "inliner broke") {
t.Errorf("log = %q, want one warning naming the error", logs.String())
}
if failed.Text != inlined.Text {
t.Errorf("the text part changed with inlining: %q, want %q", failed.Text, inlined.Text)
}
})
t.Run("layout_partials", func(t *testing.T) {
m, drv := partialsMailer(t, Options{}, nil)
msg := sendTemplate(t, m, drv, "acme.blog::mail.note", map[string]any{"Text": "<b>hi</b>"})
@@ -399,11 +528,13 @@ func TestMailPartialsSmoke(t *testing.T) {
t.Run("overrides", func(t *testing.T) {
ov := Overrides{
// A customized file layout, by its full name.
// A customized file layout, by its full name. Both layouts keep
// their style block (no inlining), so the order of the CSS slots
// shows in it.
Layouts: map[string]LayoutOverride{
"acme.blog::mail.layouts.blog": {Name: "Blog", HTML: `<div class="custom-blog">{{ .Content }}</div><style>{{ .brandCss }}{{ .css }}</style>`, Text: "[custom] {{ .Content }}", CSS: ".custom{margin:0}"},
"acme.blog::mail.layouts.blog": {Name: "Blog", HTML: `<div class="custom-blog">{{ .Content }}</div><style>{{ .brandCss }}{{ .css }}</style>`, Text: "[custom] {{ .Content }}", CSS: ".custom{margin:0}", DisableAutoInlineCSS: true},
// A database-only layout, by its code.
"promo": {Name: "Promo", HTML: `<div class="promo">{{ .Content }}{{ partial "acme.blog::mail.partials.note" "text" "promo" }}</div><style>{{ .css }}</style>`, Text: "PROMO {{ .Content }}", CSS: ".promo{margin:0}"},
"promo": {Name: "Promo", HTML: `<div class="promo">{{ .Content }}{{ partial "acme.blog::mail.partials.note" "text" "promo" }}</div><style>{{ .css }}</style>`, Text: "PROMO {{ .Content }}", CSS: ".promo{margin:0}", DisableAutoInlineCSS: true},
},
Partials: map[string]PartialOverride{
"acme.blog::mail.partials.note": {HTML: `<aside>{{ .text }}</aside>`, Text: "* {{ .text }}"},

View File

@@ -166,6 +166,18 @@ var Migrations = []*gormigrate.Migration{
return tx.Exec(`ALTER TABLE ` + BrandTable + ` DROP COLUMN IF EXISTS site_name`).Error
},
},
{
// disable_auto_inline_css keeps a layout's CSS in its style block
// only (LayoutOverride.DisableAutoInlineCSS); file-backed rows that
// are not customized mirror the file's header key.
ID: "202611130003_mail_layout_disable_auto_inline_css",
Migrate: func(tx *gorm.DB) error {
return tx.Exec(`ALTER TABLE ` + LayoutsTable + ` ADD COLUMN disable_auto_inline_css BOOLEAN NOT NULL DEFAULT FALSE`).Error
},
Rollback: func(tx *gorm.DB) error {
return tx.Exec(`ALTER TABLE ` + LayoutsTable + ` DROP COLUMN IF EXISTS disable_auto_inline_css`).Error
},
},
}
// OverrideSource supplies the database overrides one render needs.
@@ -218,6 +230,9 @@ type LayoutOverride struct {
HTML string
Text string
CSS string
// DisableAutoInlineCSS keeps the CSS in the style block only: it is not
// copied onto the elements (the disable_auto_inline_css column).
DisableAutoInlineCSS bool
}
// PartialOverride replaces a partial's HTML and text sections.
@@ -283,15 +298,16 @@ WHERE t.code = ? AND t.is_custom`, name).Scan(&rows).Error
ContentHTML string `gorm:"column:content_html"`
ContentText string `gorm:"column:content_text"`
ContentCSS string `gorm:"column:content_css"`
NoInline bool `gorm:"column:disable_auto_inline_css"`
}
if err := tx.Raw(`SELECT code, name, content_html, content_text, content_css FROM ` + LayoutsTable + ` WHERE is_custom`).Scan(&layouts).Error; err != nil {
if err := tx.Raw(`SELECT code, name, content_html, content_text, content_css, disable_auto_inline_css FROM ` + LayoutsTable + ` WHERE is_custom`).Scan(&layouts).Error; err != nil {
return err
}
for _, l := range layouts {
if out.Layouts == nil {
out.Layouts = make(map[string]LayoutOverride, len(layouts))
}
out.Layouts[l.Code] = LayoutOverride{Name: l.Name, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS}
out.Layouts[l.Code] = LayoutOverride{Name: l.Name, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS, DisableAutoInlineCSS: l.NoInline}
}
var partials []struct {
Code string
@@ -386,11 +402,11 @@ const syncLockKey = "summercms.postcard.sync"
// It runs layouts first, then templates (whose layout_id points at the
// layout row of the file's layout), then partials.
//
// For a row that is not customized the content columns mirror the file. For
// a customized row they are left alone: only source, description, locale,
// base_code, name and file_hash follow the file, which is what makes a
// changed file show as a difference between base_hash and file_hash. No row
// is deleted, database-only layouts are not touched, and a row that already
// For a row that is not customized the content columns (and a layout's
// disable_auto_inline_css) mirror the file. For a customized row they are
// left alone: only source, description, locale, base_code, name and
// file_hash follow the file, which is what makes a changed file show as a
// difference between base_hash and file_hash. No row is deleted, database-only layouts are not touched, and a row that already
// matches is not written. locales are the application's locales, for
// TemplateLocale and TemplateBase.
//
@@ -409,8 +425,8 @@ func SyncIndex(ctx context.Context, db *gorm.DB, cat *Catalog, locales []string)
return err
}
for _, l := range layouts {
if err := tx.Exec(`INSERT INTO `+LayoutsTable+` AS t (code, source, name, content_html, content_text, content_css, file_hash)
VALUES (?, ?, ?, ?, ?, '', ?)
if err := tx.Exec(`INSERT INTO `+LayoutsTable+` AS t (code, source, name, content_html, content_text, content_css, disable_auto_inline_css, file_hash)
VALUES (?, ?, ?, ?, ?, '', ?, ?)
ON CONFLICT (code) DO UPDATE SET
source = EXCLUDED.source,
name = EXCLUDED.name,
@@ -418,13 +434,14 @@ ON CONFLICT (code) DO UPDATE SET
content_html = CASE WHEN t.is_custom THEN t.content_html ELSE EXCLUDED.content_html END,
content_text = CASE WHEN t.is_custom THEN t.content_text ELSE EXCLUDED.content_text END,
content_css = CASE WHEN t.is_custom THEN t.content_css ELSE EXCLUDED.content_css END,
disable_auto_inline_css = CASE WHEN t.is_custom THEN t.disable_auto_inline_css ELSE EXCLUDED.disable_auto_inline_css END,
updated_at = NOW()
WHERE t.source IS DISTINCT FROM EXCLUDED.source
OR t.name IS DISTINCT FROM EXCLUDED.name
OR t.file_hash IS DISTINCT FROM EXCLUDED.file_hash
OR (NOT t.is_custom AND (t.content_html, t.content_text, t.content_css)
IS DISTINCT FROM (EXCLUDED.content_html, EXCLUDED.content_text, EXCLUDED.content_css))`,
l.Name, l.PluginID, rowName(l.Title, l.Name), l.HTML, l.Text, l.Hash).Error; err != nil {
OR (NOT t.is_custom AND (t.content_html, t.content_text, t.content_css, t.disable_auto_inline_css)
IS DISTINCT FROM (EXCLUDED.content_html, EXCLUDED.content_text, EXCLUDED.content_css, EXCLUDED.disable_auto_inline_css))`,
l.Name, l.PluginID, rowName(l.Title, l.Name), l.HTML, l.Text, l.DisableAutoInlineCSS, l.Hash).Error; err != nil {
return err
}
}
@@ -607,8 +624,8 @@ WHERE code = ? AND source IS NOT NULL`, f.Subject, f.Body, f.Layout, f.Hash, cod
return fmt.Errorf("postcard: reset %s: no file version", code)
}
res = db.Exec(`UPDATE `+LayoutsTable+` SET name = ?, content_html = ?, content_text = ?, content_css = '',
file_hash = ?, is_custom = FALSE, base_hash = NULL, customized_at = NULL, updated_at = NOW()
WHERE code = ? AND source IS NOT NULL`, rowName(f.Title, f.Name), f.HTML, f.Text, f.Hash, code)
disable_auto_inline_css = ?, file_hash = ?, is_custom = FALSE, base_hash = NULL, customized_at = NULL, updated_at = NOW()
WHERE code = ? AND source IS NOT NULL`, rowName(f.Title, f.Name), f.HTML, f.Text, f.DisableAutoInlineCSS, f.Hash, code)
case KindPartial:
f, ok := cat.Partial(code)
if !ok {

View File

@@ -86,6 +86,8 @@ type parsedLayout struct {
htmlWrap string
source string
hash string
// disableInline is the disable_auto_inline_css header key.
disableInline bool
}
// parsedPartial is a partial file: the layout file format, a header, a text
@@ -387,16 +389,31 @@ func parseLayout(name, pluginID, src string) (*parsedLayout, error) {
return nil, fmt.Errorf("postcard: parse %s: %w", name, err)
}
return &parsedLayout{
name: name,
pluginID: pluginID,
headerName: fields["name"],
textWrap: strings.TrimSuffix(textWrap, "\n"),
htmlWrap: strings.TrimSuffix(htmlWrap, "\n"),
source: src,
hash: fileHash(src),
name: name,
pluginID: pluginID,
headerName: fields["name"],
textWrap: strings.TrimSuffix(textWrap, "\n"),
htmlWrap: strings.TrimSuffix(htmlWrap, "\n"),
source: src,
hash: fileHash(src),
disableInline: headerBool(fields[disableInlineKey]),
}, nil
}
// disableInlineKey is the layout header key (and the layouts table column)
// that keeps a layout's CSS in its style block only, WinterCMS's option of
// the same name.
const disableInlineKey = "disable_auto_inline_css"
// headerBool reads a header value as a switch: true, 1 or yes, in any case.
func headerBool(v string) bool {
switch strings.ToLower(strings.TrimSpace(v)) {
case "true", "1", "yes":
return true
}
return false
}
func normalizeNewlines(src string) string {
return strings.ReplaceAll(src, "\r\n", "\n")
}
@@ -506,6 +523,8 @@ type renderOptions struct {
siteName string
// year is the year of the copyright line; zero is the current year.
year int
// inline copies the CSS onto the elements; nil is inlineCSS.
inline func(html string) (string, error)
// overrides are the database overrides to apply; the zero value renders
// the file version.
overrides Overrides
@@ -682,6 +701,12 @@ func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions)
if err := validateHTML(html); err != nil {
return out, partLayoutHTML, err
}
if !layout.disableInline {
html, err = inlineHTML(html, layout.name, opts)
if err != nil {
return out, partLayoutHTML, err
}
}
out = RenderedMessage{
To: append([]string(nil), msg.To...),
Cc: append([]string(nil), msg.Cc...),
@@ -694,6 +719,37 @@ func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions)
return out, "", nil
}
// styleElement finds a style element, the only place inlining reads CSS from.
var styleElement = regexp.MustCompile(`(?i)<style[\s>]`)
// inlineHTML copies the CSS of a rendered message onto its elements. HTML
// without a style element has nothing to inline and is returned as it is.
// An inliner error keeps html as it is, with its style block, and is
// reported through opts.warn; mail is never stopped by it. The inlined HTML
// passes the safety checks again, since CSS values now sit in style
// attributes.
func inlineHTML(html, layout string, opts renderOptions) (string, error) {
if !styleElement.MatchString(html) {
return html, nil
}
inline := opts.inline
if inline == nil {
inline = inlineCSS
}
inlined, err := inline(html)
if err != nil {
if opts.warn != nil {
opts.warn("inline:"+layout, "postcard: CSS could not be inlined, sending the style block only",
"layout", layout, "error", err.Error())
}
return html, nil
}
if err := validateHTML(inlined); err != nil {
return "", err
}
return inlined, nil
}
// renderLayout is the layout one render uses: a file layout, a file layout
// with its override applied, or a database-only layout.
type renderLayout struct {
@@ -701,6 +757,8 @@ type renderLayout struct {
textWrap string
htmlWrap string
css string
// disableInline keeps the CSS in the style block only.
disableInline bool
}
// layoutFor returns the layout src renders in. An override of that layout,
@@ -733,7 +791,7 @@ func (c *Catalog) layoutFor(src renderSource, opts renderOptions) (renderLayout,
func (c *Catalog) layoutByCode(code string, overrides map[string]LayoutOverride) (renderLayout, bool, error) {
if ov, ok := overrides[code]; ok {
return renderLayout{name: code, textWrap: ov.Text, htmlWrap: ov.HTML, css: ov.CSS}, true, nil
return renderLayout{name: code, textWrap: ov.Text, htmlWrap: ov.HTML, css: ov.CSS, disableInline: ov.DisableAutoInlineCSS}, true, nil
}
c.mu.RLock()
l, ok := c.layouts[code]
@@ -741,7 +799,7 @@ func (c *Catalog) layoutByCode(code string, overrides map[string]LayoutOverride)
if !ok {
return renderLayout{}, false, nil
}
return renderLayout{name: l.name, textWrap: l.textWrap, htmlWrap: l.htmlWrap}, true, nil
return renderLayout{name: l.name, textWrap: l.textWrap, htmlWrap: l.htmlWrap, disableInline: l.disableInline}, true, nil
}
func markdownHTML(src string) (string, error) {
@@ -830,6 +888,9 @@ type LayoutFile struct {
HTML string
Source string
Hash string
// DisableAutoInlineCSS is the file's disable_auto_inline_css header
// key: the layout keeps its CSS in the style block only.
DisableAutoInlineCSS bool
}
// PartialFile is a registered partial as its plugin (or postcard) ships it.
@@ -860,7 +921,7 @@ func (t *parsedTemplate) file() TemplateFile {
}
func (l *parsedLayout) file() LayoutFile {
return LayoutFile{Name: l.name, PluginID: l.pluginID, Title: l.headerName, Text: l.textWrap, HTML: l.htmlWrap, Source: l.source, Hash: l.hash}
return LayoutFile{Name: l.name, PluginID: l.pluginID, Title: l.headerName, Text: l.textWrap, HTML: l.htmlWrap, Source: l.source, Hash: l.hash, DisableAutoInlineCSS: l.disableInline}
}
func (p *parsedPartial) file() PartialFile {