Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

feat(dev): browser-based email template previewer (#77546)

dpsutton6b855cbe810f
diff --git a/dev/email-preview/README.md b/dev/email-preview/README.md
new file mode 100644
index 00000000000..f7ea4d258f2
--- /dev/null
+++ b/dev/email-preview/README.md
@@ -0,0 +1,52 @@
+# Email template preview
+
+A browser-based previewer for the transactional email templates in
+`src/metabase/channel/email/*.hbs`, so you can work on email copy and design
+without running Metabase or sending real emails.
+
+## Run it
+
+```
+bun run email-dev
+```
+
+That starts a tiny local server and opens the preview in your browser
+(default: http://localhost:8455 — set `PORT` to change it).
+
+## Using it
+
+- **Pick a template** in the left sidebar. The shared header/footer partials
+ are included automatically, just like in real emails.
+- **Edit the template**: open the `.hbs` file in any editor, save, and the
+ preview refreshes by itself (it polls for changes every second).
+- **Fill in values**: the *Fields* panel on the right lists every value the
+ template receives (`{{applicationName}}`, user names, links, …) as editable
+ inputs. The *JSON* tab shows the same data raw, for arrays and adding keys.
+ Edits are per-browser (localStorage); *Reset* restores the defaults.
+- **Check widths** with the Desktop / Narrow / Phone buttons — email clients
+ are usually around 600px.
+- **Copy HTML** copies the fully rendered email, e.g. to paste into an email
+ client testing tool like Litmus.
+
+## What's a "sample context"?
+
+Each email is rendered from a template plus data supplied by the backend at
+send time (the "context"). The defaults in `sample-contexts.js` mirror what
+the real send-time code passes, with demo values. If a template gains a new
+variable, add a default for it there.
+
+## Fidelity caveats
+
+- Production renders with Java Handlebars (jknack); this tool uses
+ handlebars.js. For everything these templates use (`#if`, `#each`, `#with`,
+ partials, the custom helpers) the output is the same, but it is a preview,
+ not a byte-for-byte reproduction — QA real sends for final signoff.
+- Subject lines live in Clojure code (`messages.clj` and the notification
+ handlers), not in the templates, so they don't appear here.
+- Rendered dashboard/card images in subscription emails are placeholders —
+ the real content comes from the visualization renderer at send time.
+- `cid:` images (inline attachments, e.g. some icons) show as broken images
+ in the browser; they work in real emails.
+- What you see is a browser rendering. Email clients (Outlook especially)
+ are stricter — the preview is for copy and layout iteration, not client
+ compatibility testing.
diff --git a/dev/email-preview/index.html b/dev/email-preview/index.html
new file mode 100644
index 00000000000..5ed888e955a
--- /dev/null
+++ b/dev/email-preview/index.html
@@ -0,0 +1,571 @@
+<!DOCTYPE html>
+<!--
+ Email template preview tool.
+
+ Renders the Handlebars email templates in src/metabase/channel/email/ with
+ sample data, entirely in the browser — no backend required. Run it with:
+
+ ./bin/email-preview
+
+ then edit any .hbs file in your editor; the preview reloads automatically.
+
+ Fidelity notes: production renders these templates with Java Handlebars
+ (jknack) — this tool uses handlebars.js, which is equivalent for everything
+ these templates use ({{#if}}, {{#each}}, {{#with}}, partials). The custom
+ helpers (equals, format-date, now, initials, card-url, dashboard-url,
+ trash-url) are re-implemented below; format-date approximates java-time
+ formatting with a common-token subset.
+-->
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Metabase Email Template Preview</title>
+<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/handlebars.min.js"></script>
+<script src="sample-contexts.js"></script>
+<style>
+ :root {
+ --brand: #509EE3;
+ --text-dark: #4C5773;
+ --text-medium: #949AAB;
+ --border: #EEECEC;
+ --bg: #F9FBFC;
+ }
+ * { box-sizing: border-box; }
+ body {
+ margin: 0;
+ font-family: 'Lato', 'Helvetica Neue', Helvetica, sans-serif;
+ color: var(--text-dark);
+ display: flex;
+ height: 100vh;
+ overflow: hidden;
+ }
+ #sidebar {
+ width: 260px;
+ min-width: 260px;
+ border-right: 1px solid var(--border);
+ background: var(--bg);
+ overflow-y: auto;
+ padding: 0.5em 0;
+ }
+ #sidebar h1 {
+ font-size: 0.95em;
+ padding: 0.5em 1em;
+ margin: 0;
+ color: var(--text-dark);
+ }
+ #sidebar .group-label {
+ font-size: 0.7em;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--text-medium);
+ padding: 1em 1.2em 0.3em;
+ }
+ #sidebar button {
+ display: block;
+ width: 100%;
+ text-align: left;
+ border: none;
+ background: none;
+ padding: 0.45em 1.2em;
+ font: inherit;
+ font-size: 0.85em;
+ color: var(--text-dark);
+ cursor: pointer;
+ border-left: 3px solid transparent;
+ }
+ #sidebar button:hover { background: #EDF2F5; }
+ #sidebar button.active {
+ border-left-color: var(--brand);
+ background: #EDF2F5;
+ font-weight: bold;
+ color: var(--brand);
+ }
+ #main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
+ #toolbar {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ padding: 0.5em 1em;
+ border-bottom: 1px solid var(--border);
+ font-size: 0.85em;
+ }
+ #toolbar .name { font-weight: bold; margin-right: auto; }
+ #toolbar button {
+ font: inherit;
+ padding: 0.3em 0.8em;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ background: white;
+ color: var(--text-dark);
+ cursor: pointer;
+ }
+ #toolbar button.on { border-color: var(--brand); color: var(--brand); font-weight: bold; }
+ #error {
+ display: none;
+ padding: 0.6em 1em;
+ background: #FDF3F3;
+ color: #C7484C;
+ font-size: 0.85em;
+ border-bottom: 1px solid #EFC7C7;
+ white-space: pre-wrap;
+ }
+ #content { flex: 1; display: flex; min-height: 0; }
+ #preview-pane {
+ flex: 1;
+ overflow: auto;
+ background: #E8EDF2;
+ display: flex;
+ justify-content: center;
+ padding: 1.5em;
+ }
+ #frame {
+ border: none;
+ background: white;
+ width: 100%;
+ max-width: 900px;
+ height: 100%;
+ box-shadow: 0 1px 4px rgba(0,0,0,0.15);
+ transition: max-width 0.15s ease;
+ }
+ #context-pane {
+ width: 340px;
+ min-width: 340px;
+ border-left: 1px solid var(--border);
+ display: flex;
+ flex-direction: column;
+ background: var(--bg);
+ }
+ #context-pane header {
+ display: flex;
+ align-items: center;
+ padding: 0.5em 0.8em;
+ font-size: 0.8em;
+ color: var(--text-medium);
+ }
+ #context-pane header span { margin-right: auto; text-transform: uppercase; letter-spacing: 0.06em; font-size: 0.85em; }
+ #context-pane header button {
+ font: inherit;
+ font-size: 0.95em;
+ border: none;
+ background: none;
+ color: var(--brand);
+ cursor: pointer;
+ }
+ #context {
+ flex: 1;
+ border: none;
+ border-top: 1px solid var(--border);
+ resize: none;
+ font-family: Menlo, Monaco, 'Courier New', monospace;
+ font-size: 11px;
+ line-height: 1.5;
+ padding: 0.8em;
+ color: var(--text-dark);
+ background: white;
+ outline: none;
+ }
+ #context.bad { background: #FDF3F3; }
+ #context-pane header .tab {
+ color: var(--text-medium);
+ padding: 0.1em 0.5em;
+ border-radius: 4px;
+ }
+ #context-pane header .tab.on { color: var(--brand); font-weight: bold; background: #EDF2F5; }
+ #fields {
+ flex: 1;
+ overflow-y: auto;
+ border-top: 1px solid var(--border);
+ background: white;
+ padding: 0.6em 0.8em 1.5em;
+ }
+ #fields label {
+ display: block;
+ font-size: 0.7em;
+ color: var(--text-medium);
+ margin: 0.9em 0 0.25em;
+ word-break: break-all;
+ }
+ #fields input[type=text], #fields textarea.field {
+ width: 100%;
+ font: inherit;
+ font-size: 0.8em;
+ padding: 0.35em 0.5em;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ color: var(--text-dark);
+ }
+ #fields textarea.field { resize: vertical; min-height: 3.2em; }
+ #fields .note {
+ font-size: 0.75em;
+ color: var(--text-medium);
+ margin-top: 1.2em;
+ line-height: 1.5;
+ }
+ #empty {
+ margin: auto;
+ color: var(--text-medium);
+ text-align: center;
+ }
+</style>
+</head>
+<body>
+ <nav id="sidebar">
+ <h1>📧 Email templates</h1>
+ <div id="template-list"></div>
+ <div class="group-label">Partials (shared header/footer)</div>
+ <div id="partial-list"></div>
+ </nav>
+ <div id="main">
+ <div id="toolbar">
+ <span class="name" id="current-name">—</span>
+ <button data-width="900">Desktop</button>
+ <button data-width="600">Narrow</button>
+ <button data-width="375">Phone</button>
+ <button id="copy-html" title="Copy rendered HTML to clipboard">Copy HTML</button>
+ </div>
+ <div id="error"></div>
+ <div id="content">
+ <div id="preview-pane">
+ <div id="empty">← Pick a template.<br><br>Edit the .hbs file in any editor and<br>the preview refreshes automatically.</div>
+ <iframe id="frame" hidden></iframe>
+ </div>
+ <div id="context-pane">
+ <header>
+ <span>Sample data</span>
+ <button class="tab on" data-tab="fields">Fields</button>
+ <button class="tab" data-tab="json">JSON</button>
+ <button id="reset-context" title="Discard edits, restore the default sample data">Reset</button>
+ </header>
+ <div id="fields"></div>
+ <textarea id="context" spellcheck="false" hidden></textarea>
+ </div>
+ </div>
+ </div>
+
+<script>
+'use strict';
+
+const TEMPLATE_DIR = '/src/metabase/channel/email/';
+const POLL_MS = 1000;
+
+// Used only if the server doesn't provide a directory listing.
+const FALLBACK_TEMPLATES = [
+ '_dashsub_alert_header', '_footer', '_header', '_logo', '_notification_card_condition',
+ 'broken_subscription_notification', 'card_notification_archived', 'card_notification_changed_stopped',
+ 'comment_created', 'creator_sentiment_email', 'dashboard_subscription', 'follow_up_email',
+ 'login_from_new_device', 'mfa_disabled', 'mfa_enabled', 'mfa_login_code', 'mfa_removed_by_admin',
+ 'new_user_invite', 'notification_card', 'notification_card_new_confirmation',
+ 'notification_card_unsubscribed', 'notification_card_you_were_added', 'notification_card_you_were_removed',
+ 'password_reset', 'persisted-model-error', 'security_advisory', 'slack_token_error',
+ 'support_access_grant', 'transform_failed', 'transform_failure_digest', 'user_joined_notification',
+ 'warn_deprecate_pulse',
+];
+
+// ---- Custom helpers, mirroring metabase.channel.template.handlebars-helper ----
+
+const SITE_URL = (window.COMMON_CONTEXT && window.COMMON_CONTEXT.siteUrl) || 'http://localhost:3000';
+
+Handlebars.registerHelper('equals', (x, y) => x === y || String(x) === String(y));
+Handlebars.registerHelper('now', () => new Date());
+Handlebars.registerHelper('initials', (name) => {
+ const m = String(name || '').match(/\b\w/g);
+ return m ? m.slice(0, 2).join('').toUpperCase() : '';
+});
+Handlebars.registerHelper('card-url', (id) => `${SITE_URL}/question/${id}`);
+Handlebars.registerHelper('dashboard-url', (id) => `${SITE_URL}/dashboard/${id}`);
+Handlebars.registerHelper('trash-url', () => `${SITE_URL}/trash`);
+// Approximates java-time formatting for the common tokens.
+Handlebars.registerHelper('format-date', (date, fmt) => {
+ const d = date instanceof Date ? date : new Date(date);
+ if (isNaN(d)) return String(date);
+ const pad = (n) => String(n).padStart(2, '0');
+ const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
+ const tokens = {
+ yyyy: d.getFullYear(), YYYY: d.getFullYear(),
+ MMMM: MONTHS[d.getMonth()], MMM: MONTHS[d.getMonth()].slice(0, 3), MM: pad(d.getMonth() + 1),
+ dd: pad(d.getDate()), d: d.getDate(),
+ HH: pad(d.getHours()), h: ((d.getHours() + 11) % 12) + 1,
+ mm: pad(d.getMinutes()), a: d.getHours() < 12 ? 'AM' : 'PM',
+ };
+ if (typeof fmt !== 'string') return d.toLocaleString();
+ return fmt.replace(/yyyy|YYYY|MMMM|MMM|MM|dd|d|HH|h|mm|a/g, (t) => tokens[t]);
+});
+
+// ---- State ----
+
+let allNames = [];
+let currentName = null;
+let sources = {}; // name -> .hbs source text
+let lastRenderedHtml = '';
+let contextDebounce = null;
+
+const $ = (sel) => document.querySelector(sel);
+const isPartial = (name) => name.startsWith('_');
+const partials = () => allNames.filter(isPartial);
+
+// ---- Template discovery & fetching ----
+
+async function fetchSource(name) {
+ const res = await fetch(TEMPLATE_DIR + name + '.hbs', { cache: 'no-store' });
+ if (!res.ok) throw new Error(`Could not load ${name}.hbs (HTTP ${res.status})`);
+ return res.text();
+}
+
+async function discoverTemplates() {
+ // Served by dev/email-preview/serve.ts (bun run email-dev).
+ try {
+ const res = await fetch('/templates.json', { cache: 'no-store' });
+ if (res.ok) {
+ const names = await res.json();
+ if (Array.isArray(names) && names.length) return names.sort();
+ }
+ } catch (e) { /* fall through */ }
+ // Any static server with directory listings (e.g. python3 -m http.server).
+ try {
+ const res = await fetch(TEMPLATE_DIR, { cache: 'no-store' });
+ const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
+ const names = [...doc.querySelectorAll('a')]
+ .map((a) => a.getAttribute('href') || '')
+ .filter((h) => h.endsWith('.hbs'))
+ .map((h) => decodeURIComponent(h.split('/').pop().replace(/\.hbs$/, '')));
+ if (names.length) return names.sort();
+ } catch (e) { /* fall through */ }
+ return FALLBACK_TEMPLATES;
+}
+
+// ---- Context handling ----
+
+function deepMerge(a, b) {
+ if (Array.isArray(a) || Array.isArray(b) || typeof a !== 'object' || typeof b !== 'object' || !a || !b) {
+ return b === undefined ? a : b;
+ }
+ const out = { ...a };
+ for (const k of Object.keys(b)) out[k] = deepMerge(a[k], b[k]);
+ return out;
+}
+
+function defaultContext(name) {
+ const sample = (window.SAMPLE_CONTEXTS || {})[name] || {};
+ return deepMerge(window.COMMON_CONTEXT || {}, sample);
+}
+
+const storageKey = (name) => `email-preview:ctx:${name}`;
+
+function loadContextText(name) {
+ return localStorage.getItem(storageKey(name))
+ || JSON.stringify(defaultContext(name), null, 2);
+}
+
+function currentContext() {
+ return JSON.parse($('#context').value);
+}
+
+// ---- Fields form: a simple fill-in-the-blanks view over the same JSON ----
+
+function leafPaths(obj, prefix = []) {
+ const out = [];
+ for (const [k, v] of Object.entries(obj || {})) {
+ const path = [...prefix, k];
+ if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
+ out.push(...leafPaths(v, path));
+ } else {
+ out.push({ path, value: v });
+ }
+ }
+ return out;
+}
+
+function setPath(obj, path, value) {
+ let o = obj;
+ for (const k of path.slice(0, -1)) o = o[k] ?? (o[k] = {});
+ o[path[path.length - 1]] = value;
+}
+
+let fieldDebounce = null;
+
+function updateFromField(path, value) {
+ clearTimeout(fieldDebounce);
+ fieldDebounce = setTimeout(() => {
+ let ctx;
+ try { ctx = currentContext(); } catch (e) { return; }
+ setPath(ctx, path, value);
+ $('#context').value = JSON.stringify(ctx, null, 2);
+ localStorage.setItem(storageKey(currentName), $('#context').value);
+ render();
+ }, 300);
+}
+
+function buildFieldsForm() {
+ const el = $('#fields');
+ el.innerHTML = '';
+ let ctx;
+ try {
+ ctx = currentContext();
+ } catch (e) {
+ el.innerHTML = '<div class="note">The JSON tab has a syntax error — fix it there first.</div>';
+ return;
+ }
+ for (const { path, value } of leafPaths(ctx)) {
+ const label = document.createElement('label');
+ label.textContent = path.join(' › ');
+ el.appendChild(label);
+ let input;
+ if (typeof value === 'boolean') {
+ input = document.createElement('input');
+ input.type = 'checkbox';
+ input.checked = value;
+ input.addEventListener('change', () => updateFromField(path, input.checked));
+ } else if (Array.isArray(value)) {
+ input = document.createElement('textarea');
+ input.className = 'field';
+ input.value = JSON.stringify(value, null, 2);
+ input.addEventListener('input', () => {
+ try { updateFromField(path, JSON.parse(input.value)); } catch (e) { /* keep typing */ }
+ });
+ } else {
+ const isLong = typeof value === 'string' && value.length > 60;
+ input = document.createElement(isLong ? 'textarea' : 'input');
+ if (isLong) { input.className = 'field'; } else { input.type = 'text'; }
+ input.value = value == null ? '' : String(value);
+ const wasNumber = typeof value === 'number';
+ input.addEventListener('input', () =>
+ updateFromField(path, wasNumber && input.value !== '' && !isNaN(input.value) ? Number(input.value) : input.value));
+ }
+ el.appendChild(input);
+ }
+ el.insertAdjacentHTML('beforeend',
+ '<div class="note">These are demo values — they only affect this preview, never real emails. ' +
+ 'For arrays or new keys, use the JSON tab. Edits are saved in your browser; Reset restores the defaults.</div>');
+}
+
+// ---- Rendering ----
+
+function showError(msg) {
+ const el = $('#error');
+ el.textContent = msg;
+ el.style.display = 'block';
+}
+function clearError() { $('#error').style.display = 'none'; }
+
+function render() {
+ if (!currentName) return;
+ let ctx;
+ try {
+ ctx = currentContext();
+ $('#context').classList.remove('bad');
+ } catch (e) {
+ $('#context').classList.add('bad');
+ showError('Sample data is not valid JSON: ' + e.message);
+ return;
+ }
+ try {
+ for (const p of partials()) Handlebars.registerPartial(p, sources[p] ?? '');
+ const template = Handlebars.compile(sources[currentName] ?? '');
+ lastRenderedHtml = template(ctx);
+ clearError();
+ } catch (e) {
+ showError('Template error: ' + e.message);
+ return;
+ }
+ const frame = $('#frame');
+ const scrollY = frame.contentWindow ? frame.contentWindow.scrollY : 0;
+ frame.onload = () => frame.contentWindow.scrollTo(0, scrollY);
+ frame.srcdoc = lastRenderedHtml;
+ frame.hidden = false;
+ $('#empty').style.display = 'none';
+}
+
+// ---- Selection ----
+
+async function selectTemplate(name) {
+ currentName = name;
+ $('#current-name').textContent = name + '.hbs';
+ document.querySelectorAll('#sidebar button').forEach((b) =>
+ b.classList.toggle('active', b.dataset.name === name));
+ $('#context').value = loadContextText(name);
+ buildFieldsForm();
+ const needed = [name, ...partials()];
+ await Promise.all(needed.map(async (n) => { sources[n] = await fetchSource(n); }));
+ render();
+ history.replaceState(null, '', '#' + name);
+}
+
+// ---- Live reload: poll the current template + partials for changes ----
+
+setInterval(async () => {
+ if (!currentName) return;
+ let changed = false;
+ for (const n of [currentName, ...partials()]) {
+ try {
+ const text = await fetchSource(n);
+ if (text !== sources[n]) { sources[n] = text; changed = true; }
+ } catch (e) { /* transient; keep last good copy */ }
+ }
+ if (changed) render();
+}, POLL_MS);
+
+// ---- UI wiring ----
+
+$('#context').addEventListener('input', () => {
+ clearTimeout(contextDebounce);
+ contextDebounce = setTimeout(() => {
+ localStorage.setItem(storageKey(currentName), $('#context').value);
+ render();
+ }, 300);
+});
+
+$('#reset-context').addEventListener('click', () => {
+ localStorage.removeItem(storageKey(currentName));
+ $('#context').value = loadContextText(currentName);
+ buildFieldsForm();
+ render();
+});
+
+document.querySelectorAll('#context-pane .tab').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ document.querySelectorAll('#context-pane .tab').forEach((b) => b.classList.remove('on'));
+ btn.classList.add('on');
+ const showFields = btn.dataset.tab === 'fields';
+ $('#fields').hidden = !showFields;
+ $('#context').hidden = showFields;
+ if (showFields) buildFieldsForm(); // pick up any JSON-tab edits
+ });
+});
+
+document.querySelectorAll('#toolbar button[data-width]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ document.querySelectorAll('#toolbar button[data-width]').forEach((b) => b.classList.remove('on'));
+ btn.classList.add('on');
+ $('#frame').style.maxWidth = btn.dataset.width + 'px';
+ });
+});
+
+$('#copy-html').addEventListener('click', async () => {
+ await navigator.clipboard.writeText(lastRenderedHtml);
+ $('#copy-html').textContent = 'Copied!';
+ setTimeout(() => { $('#copy-html').textContent = 'Copy HTML'; }, 1200);
+});
+
+// ---- Boot ----
+
+(async function init() {
+ if (typeof Handlebars === 'undefined') {
+ showError('Could not load handlebars.js from the CDN — this tool needs an internet connection.');
+ return;
+ }
+ allNames = await discoverTemplates();
+ const list = $('#template-list');
+ const plist = $('#partial-list');
+ for (const name of allNames) {
+ const btn = document.createElement('button');
+ btn.textContent = name;
+ btn.dataset.name = name;
+ btn.addEventListener('click', () => selectTemplate(name));
+ (isPartial(name) ? plist : list).appendChild(btn);
+ }
+ const fromHash = location.hash.slice(1);
+ if (fromHash && allNames.includes(fromHash)) selectTemplate(fromHash);
+})();
+</script>
+</body>
+</html>
diff --git a/dev/email-preview/sample-contexts.js b/dev/email-preview/sample-contexts.js
new file mode 100644
index 00000000000..d503a24f003
--- /dev/null
+++ b/dev/email-preview/sample-contexts.js
@@ -0,0 +1,407 @@
+/*
+ * Default sample data for the email template preview tool (index.html).
+ *
+ * COMMON_CONTEXT mirrors `common-context` in metabase.channel.email.messages —
+ * values every template receives. SAMPLE_CONTEXTS holds per-template extras,
+ * shaped to match what each template's real render call site passes (see the
+ * render calls in messages.clj, impl/email.clj, and the notification handlers
+ * seeded in notification/seed.clj).
+ *
+ * These are demo values only — the preview never sends email. Tweak freely;
+ * per-browser edits live in localStorage, this file is just the defaults.
+ */
+
+const BUTTON_STYLE =
+ "display: inline-block; box-sizing: border-box; padding: 0.5rem 1.375rem; " +
+ "font-size: 1.063rem; font-weight: bold; text-decoration: none; cursor: pointer; " +
+ "color: #fff; border: 1px solid #509EE3; background-color: #509EE3; border-radius: 4px;";
+
+// Templates rendered through the notification pipeline get a snake_case
+// `context` map instead of the camelCase top-level keys.
+const NOTIFICATION_CONTEXT = {
+ application_name: "Metabase",
+ application_color: "#509EE3",
+ application_logo_url: "http://static.metabase.com/email_logo.png",
+ site_url: "http://localhost:3000",
+};
+
+const NOTIFICATION_STYLE = {
+ color_text_dark: "#4C5773",
+ color_text_medium: "#696E7B",
+ color_text_light: "#949AAB",
+};
+
+const CARD_PLACEHOLDER = (name) =>
+ `<div style="padding:2em;background:#f9fbfc;border:1px dashed #ccc;text-align:center;color:#949AAB;margin-bottom:1em;">[rendered card: ${name}]</div>`;
+
+window.COMMON_CONTEXT = {
+ applicationName: "Metabase",
+ applicationColor: "#509EE3",
+ applicationLogoUrl: "http://static.metabase.com/email_logo.png",
+ buttonStyle: BUTTON_STYLE,
+ colorTextLight: "#B8BBC3",
+ colorTextMedium: "#949AAB",
+ colorTextDark: "#4C5773",
+ siteUrl: "http://localhost:3000",
+};
+
+window.SAMPLE_CONTEXTS = {
+ // ---- Account & auth ----
+
+ mfa_enabled: {},
+ mfa_disabled: {},
+ mfa_removed_by_admin: {},
+ mfa_login_code: { code: "836114" },
+
+ password_reset: {
+ emailType: "password_reset",
+ logoHeader: true,
+ google: false,
+ nonGoogleSSO: false,
+ isActive: true,
+ passwordResetUrl: "http://localhost:3000/auth/reset_password/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ adminEmail: "[email protected]",
+ adminEmailSet: true,
+ },
+
+ login_from_new_device: {
+ context: NOTIFICATION_CONTEXT,
+ payload: { style: { color_text_dark: "#4C5773" } },
+ "first-name": "Meredith",
+ device: "Chrome (Mac OS X 10.15)",
+ location: "Oakland, California",
+ timestamp: "Friday, July 10, 2026 at 9:14 AM (PDT)",
+ },
+
+ new_user_invite: {
+ context: NOTIFICATION_CONTEXT,
+ payload: {
+ event_info: {
+ details: { invitor: { first_name: "Meredith", email: "[email protected]" } },
+ object: { is_from_setup: false },
+ },
+ custom: {
+ user_invited_join_url: "http://localhost:3000/auth/join/a1b2c3d4-e5f6-7890",
+ // Set a name here (and optionally invite_target_is_dashboard) to
+ // preview the "wants to share a question/dashboard" variant.
+ invite_target_name: "",
+ invite_target_is_dashboard: false,
+ },
+ },
+ },
+
+ user_joined_notification: {
+ context: NOTIFICATION_CONTEXT,
+ payload: { style: { color_text_dark: "#4C5773" } },
+ joinedUserName: "Oscar",
+ joinedViaSSO: false,
+ joinedUserEmail: "[email protected]",
+ joinedDate: "Friday, July 10",
+ adminEmail: "[email protected]",
+ joinedUserEditUrl: "http://localhost:3000/admin/people",
+ },
+
+ // ---- Surveys & follow-ups ----
+
+ follow_up_email: {
+ emailType: "notification",
+ logoHeader: true,
+ heading: "We hope you've been enjoying Metabase.",
+ callToAction: "Would you mind taking a quick 5 minute survey to tell us how it's going?",
+ link: "https://metabase.com/feedback/active",
+ },
+
+ creator_sentiment_email: {
+ emailType: "notification",
+ logoHeader: true,
+ "first-name": "Meredith",
+ link: "https://metabase.com/feedback/creator",
+ "self-hosted": "http://localhost:3000",
+ },
+
+ // ---- Subscriptions & alerts ----
+
+ dashboard_subscription: {
+ context: { ...NOTIFICATION_CONTEXT, include_branding: true },
+ creator: { common_name: "Meredith Palmer" },
+ payload: {
+ dashboard: {
+ id: 12,
+ name: "Quarterly Revenue Overview",
+ description: "<p>Key revenue metrics, refreshed daily for the leadership team.</p>",
+ },
+ parameters: [
+ { id: "a1b2c3d4", name: "Date Range", value: "past30days" },
+ { id: "e5f6a7b8", name: "Category", value: "Gadget" },
+ ],
+ dashboard_subscription: { id: 301, disable_links: false },
+ style: NOTIFICATION_STYLE,
+ },
+ computed: {
+ icon_cid: "dashboard-icon@metabase", // cid: inline attachment; shows broken in browser
+ dashboard_has_tabs: false,
+ dashboard_content: CARD_PLACEHOLDER("Monthly Orders") + CARD_PLACEHOLDER("Revenue by Region"),
+ filters:
+ "<table cellpadding='0' cellspacing='0'><tr>" +
+ "<td style='font-size:12px;color:#949AAB;padding-right:12px;'><strong style='color:#696E7B;'>Date Range:</strong> Past 30 days</td>" +
+ "<td style='font-size:12px;color:#949AAB;'><strong style='color:#696E7B;'>Category:</strong> Gadget</td>" +
+ "</tr></table>",
+ management_text: "Manage your subscriptions",
+ management_url: "http://localhost:3000/account/notifications",
+ },
+ },
+
+ notification_card: {
+ context: { ...NOTIFICATION_CONTEXT, include_branding: true },
+ creator: { common_name: "Meredith Palmer" },
+ payload: {
+ card: { id: 42, name: "Monthly Orders" },
+ notification_card: { send_condition: "goal_above", send_once: true, disable_links: false },
+ style: NOTIFICATION_STYLE,
+ },
+ computed: {
+ icon_cid: "bell-icon@metabase", // cid: inline attachment; shows broken in browser
+ content: CARD_PLACEHOLDER("Monthly Orders"),
+ alert_schedule: "Run daily at 9:00 AM",
+ goal_value: 5000,
+ management_text: "Manage your subscriptions",
+ management_url: "http://localhost:3000/account/notifications",
+ },
+ },
+
+ notification_card_new_confirmation: {
+ emailType: "notification",
+ logoHeader: true,
+ payload: {
+ event_info: {
+ object: {
+ payload: {
+ card_id: 42,
+ card: { name: "Monthly Orders" },
+ send_condition: "has_result",
+ disable_links: false,
+ },
+ },
+ },
+ },
+ },
+
+ notification_card_unsubscribed: {
+ emailType: "notification",
+ logoHeader: true,
+ payload: { card_id: 42, card: { name: "Monthly Orders" } },
+ },
+
+ notification_card_you_were_added: {
+ emailType: "notification",
+ logoHeader: true,
+ payload: { card_id: 42, card: { name: "Monthly Orders" }, send_condition: "has_result" },
+ },
+
+ notification_card_you_were_removed: {
+ emailType: "notification",
+ logoHeader: true,
+ actor_name: "Meredith Palmer",
+ payload: { card_id: 42, card: { name: "Monthly Orders" }, disable_links: false },
+ },
+
+ card_notification_archived: {
+ emailType: "notification",
+ logoHeader: true,
+ card: { id: 42, name: "Monthly Orders" },
+ actor: { first_name: "Meredith", last_name: "Palmer" },
+ disable_links: false,
+ },
+
+ card_notification_changed_stopped: {
+ emailType: "notification",
+ logoHeader: true,
+ card: { id: 42, name: "Monthly Orders" },
+ actor: { first_name: "Meredith", last_name: "Palmer" },
+ disable_links: false,
+ },
+
+ broken_subscription_notification: {
+ emailType: "notification",
+ logoHeader: true,
+ dashboardName: "Quarterly Revenue Overview",
+ dashboardUrl: "http://localhost:3000/dashboard/12",
+ disable_links: false,
+ badParameters: [
+ { name: "Region", value: "West or Midwest" },
+ { name: "Product Category", value: "Gadget" },
+ ],
+ affectedUsers: [
+ { "notification-type": "email", recipient: "Meredith Palmer", role: "Dashboard Creator" },
+ { "notification-type": "email", recipient: "Oscar Nunez", role: "Subscription Creator" },
+ ],
+ },
+
+ warn_deprecate_pulse: {
+ emailType: "notification",
+ logoHeader: true,
+ userName: "Meredith Palmer",
+ instanceURL: "http://localhost:3000",
+ pulses: [
+ { name: "Weekly Sales Pulse", url: "http://localhost:3000/pulse/23" },
+ { name: "Support Ticket Volume", url: "http://localhost:3000/pulse/31" },
+ ],
+ },
+
+ // ---- Comments & collaboration ----
+
+ comment_created: {
+ context: NOTIFICATION_CONTEXT,
+ payload: {
+ style: { color_text_dark: "#4C5773" },
+ event_info: {
+ author: "Oscar Nunez",
+ parent_author: "Meredith Palmer",
+ entity_type: "document",
+ entity_title: "Q3 Planning Notes",
+ document_href: "/document/87",
+ comment_href: "/document/87?comment=214",
+ parent_comment: "<p>Should we fold the churn analysis into this doc, or keep it separate?</p>",
+ comment: "<p>Let's fold it in — I'll add a section under <strong>Retention</strong> this afternoon.</p>",
+ },
+ },
+ },
+
+ // ---- Admin & ops ----
+
+ security_advisory: {
+ emailType: "notification",
+ logoHeader: false,
+ context: {
+ ...NOTIFICATION_CONTEXT,
+ style: { button: BUTTON_STYLE },
+ },
+ payload: {
+ custom: {
+ severity_label: "Critical",
+ severity_color: "#E65050",
+ status_label: "Active",
+ security_center_url: "http://localhost:3000/admin/tools/security-center",
+ },
+ event_info: {
+ object: {
+ title: "SQL injection in embedded question parameters",
+ description:
+ "A vulnerability was identified that could allow specially crafted embedded question parameters " +
+ "to execute arbitrary SQL against connected databases. Your instance version matches the affected range.",
+ remediation: "Upgrade to Metabase 55.8.2 or later, or disable static embedding until you can upgrade.",
+ advisory_url: "https://www.metabase.com/security/advisories/MB-2026-0042",
+ },
+ },
+ },
+ },
+
+ slack_token_error: {
+ emailType: "notification",
+ logoHeader: false,
+ context: {
+ ...NOTIFICATION_CONTEXT,
+ style: { button: BUTTON_STYLE },
+ },
+ },
+
+ support_access_grant: {
+ context: NOTIFICATION_CONTEXT,
+ payload: {
+ style: { color_text_dark: "#4C5773" },
+ event_info: {
+ duration_minutes: 120,
+ grant_end_time: "2026-07-10T21:14:00Z",
+ notes:
+ "Investigating slow dashboard loads reported by the customer.\n" +
+ "Access limited to admin settings and query diagnostics.",
+ ticket_number: "SUP-18342",
+ password_reset_url: "http://localhost:3000/auth/reset_password/a1b2c3d4-e5f6-7890-abcd-ef1234567890",
+ },
+ },
+ },
+
+ "persisted-model-error": {
+ "database-name": "Sample Database",
+ errors: [
+ {
+ "is-not-first": false,
+ error: "Table 'orders_source' not found; it may have been renamed or dropped.",
+ "card-id": 42,
+ "card-name": "Monthly Orders",
+ "collection-name": "Finance",
+ "last-run-at": "July 10, 2026, 3:10 AM PDT",
+ "last-run-trigger": "Scheduled",
+ "card-url": "http://localhost:3000/question/42",
+ "collection-url": "http://localhost:3000/collection/7",
+ "caching-log-details-url": "http://localhost:3000/admin/tools/model-caching/101",
+ },
+ {
+ "is-not-first": true,
+ error: "Query timed out after 600 seconds.",
+ "card-id": 43,
+ "card-name": "Customer LTV",
+ "collection-name": "Finance",
+ "last-run-at": "July 10, 2026, 3:12 AM PDT",
+ "last-run-trigger": "Scheduled",
+ "card-url": "http://localhost:3000/question/43",
+ "collection-url": "http://localhost:3000/collection/7",
+ "caching-log-details-url": "http://localhost:3000/admin/tools/model-caching/102",
+ },
+ ],
+ },
+
+ transform_failed: {
+ context: NOTIFICATION_CONTEXT,
+ payload: {
+ style: { color_text_dark: "#4C5773" },
+ event_info: {
+ job_name: "Nightly Warehouse Refresh",
+ job_href: "http://localhost:3000/admin/transforms/jobs/7",
+ failures: [
+ {
+ transform_name: "Orders Enriched",
+ transform_href: "http://localhost:3000/admin/transforms/15/runs",
+ message: {
+ first_line: 'Column "discount_pct" does not exist in source table.',
+ details: [
+ "at stage 2 of 3 (join with promotions)",
+ "last successful run: July 9, 2026, 2:00 AM",
+ ],
+ },
+ },
+ {
+ transform_name: "Customer LTV Rollup",
+ transform_href: "http://localhost:3000/admin/transforms/16/runs",
+ message: { first_line: "Query timed out after 600 seconds.", details: [] },
+ },
+ ],
+ },
+ },
+ },
+
+ transform_failure_digest: {
+ context: NOTIFICATION_CONTEXT,
+ payload: {
+ style: { color_text_dark: "#4C5773" },
+ event_info: {
+ job_count: 2,
+ failure_count: 5,
+ jobs: [
+ {
+ job_name: "Nightly Warehouse Refresh",
+ job_href: "http://localhost:3000/admin/transforms/jobs/7",
+ failure_count: 3,
+ latest_error: 'Column "discount_pct" does not exist in source table.',
+ },
+ {
+ job_name: "Hourly Events Rollup",
+ job_href: "http://localhost:3000/admin/transforms/jobs/9",
+ failure_count: 2,
+ latest_error: "Query timed out after 600 seconds.",
+ },
+ ],
+ },
+ },
+ },
+};
diff --git a/dev/email-preview/serve.ts b/dev/email-preview/serve.ts
new file mode 100644
index 00000000000..ee571c48cda
--- /dev/null
+++ b/dev/email-preview/serve.ts
@@ -0,0 +1,60 @@
+/**
+ * Dev server for the email template preview tool.
+ *
+ * bun run email-dev # serves on :8455 and opens the browser
+ * PORT=9000 bun run email-dev
+ *
+ * Serves dev/email-preview/index.html, exposes the list of templates at
+ * /templates.json, and serves the .hbs files themselves so the page can
+ * fetch (and live-reload) them.
+ */
+import { readdir } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+
+const REPO_ROOT = fileURLToPath(new URL("../..", import.meta.url));
+const PREVIEW_DIR = `${REPO_ROOT}dev/email-preview/`;
+const TEMPLATE_DIR = `${REPO_ROOT}src/metabase/channel/email/`;
+const PORT = Number(process.env.PORT || 8455);
+
+const server = Bun.serve({
+ port: PORT,
+ async fetch(req) {
+ const pathname = decodeURIComponent(new URL(req.url).pathname);
+ if (pathname.includes("..")) {
+ return new Response("bad path", { status: 400 });
+ }
+ if (pathname === "/" || pathname === "/index.html") {
+ return new Response(Bun.file(`${PREVIEW_DIR}index.html`));
+ }
+ if (pathname === "/sample-contexts.js") {
+ return new Response(Bun.file(`${PREVIEW_DIR}sample-contexts.js`));
+ }
+ if (pathname === "/templates.json") {
+ const names = (await readdir(TEMPLATE_DIR))
+ .filter((f) => f.endsWith(".hbs"))
+ .map((f) => f.replace(/\.hbs$/, ""))
+ .sort();
+ return Response.json(names);
+ }
+ // .hbs sources, fetched by the page as /src/metabase/channel/email/<name>.hbs
+ const file = Bun.file(REPO_ROOT + pathname.slice(1));
+ if (await file.exists()) {
+ return new Response(file, {
+ headers: { "cache-control": "no-store" },
+ });
+ }
+ return new Response("not found", { status: 404 });
+ },
+});
+
+const url = `http://localhost:${server.port}/`;
+console.log(`📧 Email template preview → ${url}`);
+console.log(` Templates: src/metabase/channel/email/*.hbs (edits reload live)`);
+
+if (!process.env.EMAIL_DEV_NO_OPEN) {
+ const opener =
+ process.platform === "darwin" ? "open"
+ : process.platform === "win32" ? "start"
+ : "xdg-open";
+ Bun.spawn([opener, url], { stdout: "ignore", stderr: "ignore" });
+}
diff --git a/package.json b/package.json
index 464b8c45a44..10669ff097d 100644
--- a/package.json
+++ b/package.json
@@ -508,6 +508,7 @@
"dev-hot-be": "bun install && bun run clean-dev:cljs && concurrently -n 'backend,frontend,cljs,static-viz' -c 'blue,green,yellow,magenta,red,cyan' 'clojure -M:run:dev:dev-start --hot' 'ENABLE_CLJS_HOT_RELOAD=true bun run build-hot:js-wait' 'bun run build-hot:cljs' 'bun run build-static-viz:watch-wait'",
"dev-ee": "bun install && bun run clean-dev:cljs && concurrently -n 'backend,frontend,cljs,static-viz' -c 'blue,green,yellow,magenta,red,cyan' 'clojure -M:run:ee:dev:dev-start --hot' 'MB_EDITION=ee bun run build-hot:js-wait' 'MB_EDITION=ee bun run build:cljs' 'bun run build-static-viz:watch-wait'",
"dev-ee-hot-be": "bun install && bun run clean-dev:cljs && concurrently -n 'backend,frontend,cljs,static-viz' -c 'blue,green,yellow,magenta,red,cyan' 'clojure -M:run:ee:dev:dev-start --hot' 'MB_EDITION=ee ENABLE_CLJS_HOT_RELOAD=true bun run build-hot:js-wait' 'MB_EDITION=ee bun run build-hot:cljs' 'bun run build-static-viz:watch-wait'",
+ "email-dev": "bun dev/email-preview/serve.ts",
"embedding-sdk:generate-package": "node ./bin/embedding-sdk/generate-sdk-package-files.js",
"embedding-sdk:publish": "cd ./resources/embedding-sdk && npm publish",
"embedding-sdk:generate-package-support-files": "tsx enterprise/frontend/src/embedding-sdk-package/bin/generate-package-support-files.ts",