Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Added the Admin API for editing store email templates

Damian Legawiecaa69c35807f4
diff --git a/.changeset/admin-sdk-email-templates.md b/.changeset/admin-sdk-email-templates.md
new file mode 100644
index 0000000000..50e9237d12
--- /dev/null
+++ b/.changeset/admin-sdk-email-templates.md
@@ -0,0 +1,5 @@
+---
+"@spree/admin-sdk": minor
+---
+
+Added `client.emailTemplates` for editing a store's customer email templates, email layout and shared partials: list and read them per language, save and discard drafts, preview with sample data, send a test email to yourself, publish, revert to Spree's default, and list or restore published revisions. Also added `EmailTemplate`, `EmailTemplateDraft`, `EmailTemplatePreview` and `EmailTemplateRevision`, and `Email*` types (`EmailOrder`, `EmailStore`, ...) describing the data each customer email template renders with.
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yaml
index 395909c4d9..0dccf09154 100644
--- a/docs/api-reference/admin.yaml
+++ b/docs/api-reference/admin.yaml
@@ -7345,6 +7345,1306 @@ paths:
type: string
example:
- vip
+ "/api/v3/admin/email_templates":
+ get:
+ summary: List email templates
+ tags:
+ - Email Templates
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Returns every email template merchants may edit: the emails customers
+ receive, the email layout and the shared partials. Each shows what
+ customers receive now (the store's published version, else Spree's
+ default) and any draft in progress. Staff emails are not editable.
+
+
+ **Required scope:** `read_email_templates` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const templates = await client.emailTemplates.list()
+ - lang: bash
+ label: Spree CLI
+ source: spree api get /email_templates
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ - name: language
+ in: query
+ required: false
+ description: A language code, or `any` (the default) for the version every
+ language uses
+ schema:
+ type: string
+ responses:
+ '200':
+ description: email templates found
+ content:
+ application/json:
+ example:
+ data:
+ - id: spree.admin_user_mailer.password_reset_email
+ key: spree/admin_user_mailer/password_reset_email
+ subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ language: any
+ customized_languages: []
+ kind: email
+ customized: false
+ published_at:
+ default_subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ default_body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ default_changed: false
+ base_subject:
+ base_body:
+ draft:
+ - id: layouts.spree.base_mailer
+ key: layouts/spree/base_mailer
+ subject:
+ body: |
+ <mjml lang="{{ locale }}">
+ <mj-head>
+ <mj-title>{{ subject }}</mj-title>
+ <mj-attributes>
+ <mj-all font-family="Inter, Helvetica, Arial, sans-serif" />
+ <mj-section padding="0" />
+ <mj-column padding="0" />
+ <mj-text padding="0" color="#726A6A" font-size="14px" line-height="1.6" align="center" />
+ <mj-button background-color="#FFFFFF" border="1px solid #E8E9E9" border-radius="8px" color="#1F2222" font-size="15px" font-weight="500" line-height="1.6" inner-padding="12px 20px" padding="32px 0 0" />
+ <mj-table padding="0" color="#726A6A" font-size="14px" line-height="1.6" />
+ <mj-class name="heading" font-family="Geist, Inter, Helvetica, Arial, sans-serif" font-size="40px" font-weight="700" line-height="1.2" letter-spacing="-0.8px" color="#332C2C" css-class="heading" />
+ <mj-class name="greeting" padding="24px 0 0" font-size="15px" font-weight="500" color="#332C2C" />
+ <mj-class name="lead" padding="12px 0 0" />
+ <mj-class name="note" padding="24px 0 0" font-size="13px" css-class="note" />
+ <mj-class name="section-heading" padding="48px 0 16px" font-family="Geist, Inter, Helvetica, Arial, sans-serif" font-size="16px" font-weight="500" letter-spacing="-0.16px" align="left" />
+ <mj-class name="body" padding="16px 0 0" align="left" />
+ <mj-class name="footer" padding="12px 0 0" font-size="11px" line-height="1.5" />
+ </mj-attributes>
+ <mj-style>
+ @font-face { font-family: "Geist"; font-style: normal; font-weight: 500 700; src: url("https://fonts.gstatic.com/s/geist/v4/gyByhwUxId8gMEwcGFU.woff2") format("woff2"); }
+ @font-face { font-family: "Inter"; font-style: normal; font-weight: 400 450; src: url("https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuOKfMZg.ttf") format("truetype"); }
+ @font-face { font-family: "Inter"; font-style: normal; font-weight: 500; src: url("https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuI6fMZg.ttf") format("truetype"); }
+ @font-face { font-family: "Inter"; font-style: normal; font-weight: 600; src: url("https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf") format("truetype"); }
+ a { color: #332C2C; }
+ .hero > table { max-width: 420px; margin: 0 auto; }
+ .note a { color: #726A6A; word-break: break-all; }
+ .footer a { color: #726A6A; }
+ .item { width: 100%; background-color: #F0F0F0; border-radius: 16px; margin: 0 0 8px; }
+ .item_image { padding: 8px; width: 96px; }
+ .item_thumb { display: block; width: 80px; height: auto; border-radius: 12px; }
+ .item_thumb_placeholder { width: 80px; height: 80px; background-color: #E4E4E4; border-radius: 12px; }
+ .item_info { padding: 8px 16px 8px 8px; }
+ .item_name { font-size: 15px; line-height: 1.5; font-weight: 500; color: #332C2C; text-decoration: none; }
+ .item_meta { margin: 2px 0 0; font-size: 13px; line-height: 1.5; color: #726A6A; }
+ .item_amount { padding: 8px 16px 8px 8px; text-align: right; white-space: nowrap; }
+ .item_qty { margin: 0; font-size: 13px; line-height: 1.5; color: #726A6A; }
+ .item_price { margin: 2px 0 0; font-size: 15px; line-height: 1.5; font-weight: 500; color: #332C2C; }
+ .summary td { padding: 6px 0; font-size: 14px; line-height: 1.6; color: #726A6A; }
+ .summary_value { font-size: 15px; font-weight: 500; text-align: right; white-space: nowrap; color: #332C2C; }
+ .summary_sub { display: block; font-size: 13px; line-height: 1.5; }
+ .summary_total td { padding: 14px 0 0; border-top: 1px solid #E8E9E9; font-weight: 500; color: #332C2C; }
+ .summary_total .summary_value { font-weight: 600; }
+ .mailer_hero h1 { margin: 0; font-family: Geist, Inter, Helvetica, Arial, sans-serif; font-size: 40px; line-height: 1.2; letter-spacing: -0.8px; font-weight: 700; color: #332C2C; }
+ .mailer_hero p { margin: 12px 0 0; }
+ .mailer_hero .greeting { margin-top: 24px; font-size: 15px; font-weight: 500; color: #332C2C; }
+ .mailer_hero .sub { margin-top: 24px; font-size: 13px; }
+ @media only screen and (max-width: 600px) {
+ .heading div { font-size: 32px !important; letter-spacing: -0.64px !important; }
+ }
+ </mj-style>
+ </mj-head>
+ <mj-body background-color="#FFFFFF" width="640px">
+ <mj-wrapper background-color="#F6F6F6" padding="56px 24px">
+ <mj-section padding="0 0 32px">
+ <mj-column>
+ {% if store.logo_url and store.logo_width %}
+ <mj-image src="{{ store.logo_url }}" href="{{ store.url }}" alt="{{ store.name }}" width="{{ store.logo_width }}px" height="32px" padding="0" />
+ {% elsif store.logo_url %}
+ <mj-text><a href="{{ store.url }}"><img src="{{ store.logo_url }}" alt="{{ store.name }}" height="32" style="height: 32px; width: auto; border: 0;" /></a></mj-text>
+ {% else %}
+ <mj-text font-size="22px" font-weight="700" color="#332C2C" text-transform="uppercase"><a href="{{ store.url }}" style="color: #332C2C; text-decoration: none;">{{ store.name }}</a></mj-text>
+ {% endif %}
+ </mj-column>
+ </mj-section>
+ {{ content_for_layout }}
+ </mj-wrapper>
+ <mj-section padding="64px 24px">
+ <mj-column>
+ <mj-text font-size="13px" line-height="1.5" css-class="footer"><a href="{{ store.url }}" style="font-weight: 500; text-decoration: none;">{{ store.name }}</a></mj-text>
+ {% if store.address != blank %}<mj-text mj-class="footer">{{ store.address }}</mj-text>{% endif %}
+ {% if store.support_email != blank %}<mj-text mj-class="footer" css-class="footer"><a href="mailto:{{ store.support_email }}">{{ store.support_email }}</a></mj-text>{% endif %}
+ <mj-text mj-class="footer" padding="20px 0 0">&copy; {{ 'now' | date: '%Y' }} {{ store.name }}</mj-text>
+ </mj-column>
+ </mj-section>
+ </mj-body>
+ </mjml>
+ language: any
+ customized_languages: []
+ kind: layout
+ customized: false
+ published_at:
+ default_subject:
+ default_body: |
+ <mjml lang="{{ locale }}">
+ <mj-head>
+ <mj-title>{{ subject }}</mj-title>
+ <mj-attributes>
+ <mj-all font-family="Inter, Helvetica, Arial, sans-serif" />
+ <mj-section padding="0" />
+ <mj-column padding="0" />
+ <mj-text padding="0" color="#726A6A" font-size="14px" line-height="1.6" align="center" />
+ <mj-button background-color="#FFFFFF" border="1px solid #E8E9E9" border-radius="8px" color="#1F2222" font-size="15px" font-weight="500" line-height="1.6" inner-padding="12px 20px" padding="32px 0 0" />
+ <mj-table padding="0" color="#726A6A" font-size="14px" line-height="1.6" />
+ <mj-class name="heading" font-family="Geist, Inter, Helvetica, Arial, sans-serif" font-size="40px" font-weight="700" line-height="1.2" letter-spacing="-0.8px" color="#332C2C" css-class="heading" />
+ <mj-class name="greeting" padding="24px 0 0" font-size="15px" font-weight="500" color="#332C2C" />
+ <mj-class name="lead" padding="12px 0 0" />
+ <mj-class name="note" padding="24px 0 0" font-size="13px" css-class="note" />
+ <mj-class name="section-heading" padding="48px 0 16px" font-family="Geist, Inter, Helvetica, Arial, sans-serif" font-size="16px" font-weight="500" letter-spacing="-0.16px" align="left" />
+ <mj-class name="body" padding="16px 0 0" align="left" />
+ <mj-class name="footer" padding="12px 0 0" font-size="11px" line-height="1.5" />
+ </mj-attributes>
+ <mj-style>
+ @font-face { font-family: "Geist"; font-style: normal; font-weight: 500 700; src: url("https://fonts.gstatic.com/s/geist/v4/gyByhwUxId8gMEwcGFU.woff2") format("woff2"); }
+ @font-face { font-family: "Inter"; font-style: normal; font-weight: 400 450; src: url("https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuOKfMZg.ttf") format("truetype"); }
+ @font-face { font-family: "Inter"; font-style: normal; font-weight: 500; src: url("https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuI6fMZg.ttf") format("truetype"); }
+ @font-face { font-family: "Inter"; font-style: normal; font-weight: 600; src: url("https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf") format("truetype"); }
+ a { color: #332C2C; }
+ .hero > table { max-width: 420px; margin: 0 auto; }
+ .note a { color: #726A6A; word-break: break-all; }
+ .footer a { color: #726A6A; }
+ .item { width: 100%; background-color: #F0F0F0; border-radius: 16px; margin: 0 0 8px; }
+ .item_image { padding: 8px; width: 96px; }
+ .item_thumb { display: block; width: 80px; height: auto; border-radius: 12px; }
+ .item_thumb_placeholder { width: 80px; height: 80px; background-color: #E4E4E4; border-radius: 12px; }
+ .item_info { padding: 8px 16px 8px 8px; }
+ .item_name { font-size: 15px; line-height: 1.5; font-weight: 500; color: #332C2C; text-decoration: none; }
+ .item_meta { margin: 2px 0 0; font-size: 13px; line-height: 1.5; color: #726A6A; }
+ .item_amount { padding: 8px 16px 8px 8px; text-align: right; white-space: nowrap; }
+ .item_qty { margin: 0; font-size: 13px; line-height: 1.5; color: #726A6A; }
+ .item_price { margin: 2px 0 0; font-size: 15px; line-height: 1.5; font-weight: 500; color: #332C2C; }
+ .summary td { padding: 6px 0; font-size: 14px; line-height: 1.6; color: #726A6A; }
+ .summary_value { font-size: 15px; font-weight: 500; text-align: right; white-space: nowrap; color: #332C2C; }
+ .summary_sub { display: block; font-size: 13px; line-height: 1.5; }
+ .summary_total td { padding: 14px 0 0; border-top: 1px solid #E8E9E9; font-weight: 500; color: #332C2C; }
+ .summary_total .summary_value { font-weight: 600; }
+ .mailer_hero h1 { margin: 0; font-family: Geist, Inter, Helvetica, Arial, sans-serif; font-size: 40px; line-height: 1.2; letter-spacing: -0.8px; font-weight: 700; color: #332C2C; }
+ .mailer_hero p { margin: 12px 0 0; }
+ .mailer_hero .greeting { margin-top: 24px; font-size: 15px; font-weight: 500; color: #332C2C; }
+ .mailer_hero .sub { margin-top: 24px; font-size: 13px; }
+ @media only screen and (max-width: 600px) {
+ .heading div { font-size: 32px !important; letter-spacing: -0.64px !important; }
+ }
+ </mj-style>
+ </mj-head>
+ <mj-body background-color="#FFFFFF" width="640px">
+ <mj-wrapper background-color="#F6F6F6" padding="56px 24px">
+ <mj-section padding="0 0 32px">
+ <mj-column>
+ {% if store.logo_url and store.logo_width %}
+ <mj-image src="{{ store.logo_url }}" href="{{ store.url }}" alt="{{ store.name }}" width="{{ store.logo_width }}px" height="32px" padding="0" />
+ {% elsif store.logo_url %}
+ <mj-text><a href="{{ store.url }}"><img src="{{ store.logo_url }}" alt="{{ store.name }}" height="32" style="height: 32px; width: auto; border: 0;" /></a></mj-text>
+ {% else %}
+ <mj-text font-size="22px" font-weight="700" color="#332C2C" text-transform="uppercase"><a href="{{ store.url }}" style="color: #332C2C; text-decoration: none;">{{ store.name }}</a></mj-text>
+ {% endif %}
+ </mj-column>
+ </mj-section>
+ {{ content_for_layout }}
+ </mj-wrapper>
+ <mj-section padding="64px 24px">
+ <mj-column>
+ <mj-text font-size="13px" line-height="1.5" css-class="footer"><a href="{{ store.url }}" style="font-weight: 500; text-decoration: none;">{{ store.name }}</a></mj-text>
+ {% if store.address != blank %}<mj-text mj-class="footer">{{ store.address }}</mj-text>{% endif %}
+ {% if store.support_email != blank %}<mj-text mj-class="footer" css-class="footer"><a href="mailto:{{ store.support_email }}">{{ store.support_email }}</a></mj-text>{% endif %}
+ <mj-text mj-class="footer" padding="20px 0 0">&copy; {{ 'now' | date: '%Y' }} {{ store.name }}</mj-text>
+ </mj-column>
+ </mj-section>
+ </mj-body>
+ </mjml>
+ default_changed: false
+ base_subject:
+ base_body:
+ draft:
+ meta: {}
+ "/api/v3/admin/email_templates/{id}":
+ parameters:
+ - name: id
+ in: path
+ required: true
+ description: The template key with dots, e.g. `spree.order_mailer.confirm_email`
+ schema:
+ type: string
+ get:
+ summary: Get an email template
+ tags:
+ - Email Templates
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Returns the template for one language: what customers receive now,
+ Spree's default, and the draft with its `lock_version`. When Spree's
+ default changed since the store's version started from it,
+ `default_changed` is true and `base_body` holds the default it
+ started from, to compare with `default_body`.
+
+
+ **Required scope:** `read_email_templates` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const template = await client.emailTemplates.get('spree.order_mailer.confirm_email', {
+ language: 'de',
+ expand: ['draft.updated_by'],
+ })
+ - lang: bash
+ label: Spree CLI
+ source: spree api get /email_templates/{id} -d '{"language":"de","expand":["draft.updated_by"]}'
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ - name: language
+ in: query
+ required: false
+ description: A language code, or `any` (the default)
+ schema:
+ type: string
+ - name: expand
+ in: query
+ required: false
+ description: Comma-separated associations to expand (`draft.updated_by`)
+ schema:
+ type: string
+ responses:
+ '200':
+ description: email template found
+ content:
+ application/json:
+ example:
+ id: spree.admin_user_mailer.password_reset_email
+ key: spree/admin_user_mailer/password_reset_email
+ subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ language: any
+ customized_languages: []
+ kind: email
+ customized: false
+ published_at:
+ default_subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ default_body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ default_changed: true
+ base_subject: Reset {{ store.name }}
+ base_body: "<mj-section><mj-column><mj-text>Default</mj-text></mj-column></mj-section>"
+ draft:
+ id: etdr_UkLWZg9DAJ
+ subject: Reset {{ store.name }}
+ body: "<mj-section><mj-column><mj-text>Hi {{ user.first_name }}</mj-text></mj-column></mj-section>"
+ lock_version: 0
+ created_at: '2026-01-15T12:00:00.000Z'
+ updated_at: '2026-01-15T12:00:00.000Z'
+ updated_by_id: adm_UkLWZg9DAJ
+ updated_by_type: admin_user
+ schema:
+ "$ref": "#/components/schemas/EmailTemplate"
+ '404':
+ description: not an editable template
+ content:
+ application/json:
+ example:
+ error:
+ code: record_not_found
+ message: record not found
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ delete:
+ summary: Revert an email template to Spree's default
+ tags:
+ - Email Templates
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Goes back to Spree's default for one language and discards the draft.
+ The store's published versions are kept, so one can still be restored.
+
+
+ **Required scope:** `write_email_templates` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ // Goes back to Spree's default. Published versions stay in the history.
+ const template = await client.emailTemplates.revert('spree.order_mailer.confirm_email')
+ - lang: bash
+ label: Spree CLI
+ source: spree api delete /email_templates/{id}
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ - name: language
+ in: query
+ required: false
+ description: A language code, or `any` (the default)
+ schema:
+ type: string
+ responses:
+ '200':
+ description: email template reverted
+ content:
+ application/json:
+ example:
+ id: spree.admin_user_mailer.password_reset_email
+ key: spree/admin_user_mailer/password_reset_email
+ subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ language: any
+ customized_languages: []
+ kind: email
+ customized: false
+ published_at:
+ default_subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ default_body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ default_changed: false
+ base_subject:
+ base_body:
+ draft:
+ schema:
+ "$ref": "#/components/schemas/EmailTemplate"
+ "/api/v3/admin/email_templates/{email_template_id}/draft":
+ parameters:
+ - name: email_template_id
+ in: path
+ required: true
+ description: The template key with dots
+ schema:
+ type: string
+ put:
+ summary: Save an email template draft
+ tags:
+ - Email Templates
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Saves the draft, in any state; customers keep receiving the published
+ version until it is published. Send the `lock_version` the draft was
+ loaded with: a save made from an older copy is refused with 409,
+ naming who saved last. The first save starts from what is published,
+ else Spree's default.
+
+
+ **Required scope:** `write_email_templates` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ // Pass the lock_version the draft was loaded with: a save made from an
+ // older copy is refused with 409, naming who saved last.
+ const template = await client.emailTemplates.draft.update('spree.order_mailer.confirm_email', {
+ subject: 'Your order {{ order.number }} is confirmed',
+ body: '<mj-section><mj-column><mj-text>Thanks, {{ order.customer_name }}!</mj-text></mj-column></mj-section>',
+ lock_version: 0,
+ })
+ - lang: bash
+ label: Spree CLI
+ source: spree api put /email_templates/{email_template_id}/draft -d '{"subject":"Your
+ order {{ order.number }} is confirmed","body":"<mj-section><mj-column><mj-text>Thanks,
+ {{ order.customer_name }}!</mj-text></mj-column></mj-section>","lock_version":0}'
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ responses:
+ '200':
+ description: draft saved
+ content:
+ application/json:
+ example:
+ id: spree.admin_user_mailer.password_reset_email
+ key: spree/admin_user_mailer/password_reset_email
+ subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ language: any
+ customized_languages: []
+ kind: email
+ customized: false
+ published_at:
+ default_subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ default_body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ default_changed: false
+ base_subject:
+ base_body:
+ draft:
+ id: etdr_UkLWZg9DAJ
+ subject: Reset your {{ store.name }} password
+ body: "<mj-section><mj-column><mj-text>Hi {{ user.first_name }}</mj-text></mj-column></mj-section>"
+ lock_version: 0
+ created_at: '2026-01-15T12:00:00.000Z'
+ updated_at: '2026-01-15T12:00:00.000Z'
+ updated_by_id: adm_UkLWZg9DAJ
+ updated_by_type: admin_user
+ schema:
+ "$ref": "#/components/schemas/EmailTemplate"
+ '409':
+ description: saved by someone else since it was loaded
+ content:
+ application/json:
+ example:
+ error:
+ code: email_template_stale
+ message: Mirta Hamill saved this draft after you opened it. Reload
+ to see their changes before saving yours.
+ details:
+ updated_by: Mirta Hamill
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ language:
+ type: string
+ example: any
+ subject:
+ type: string
+ example: Reset your {{ store.name }} password
+ body:
+ type: string
+ example: "<mj-section><mj-column><mj-text>Hi {{ user.first_name
+ }}</mj-text></mj-column></mj-section>"
+ lock_version:
+ type: integer
+ example: 0
+ delete:
+ summary: Discard an email template draft
+ tags:
+ - Email Templates
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: "**Required scope:** `write_email_templates` (for API-key authentication)."
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const template = await client.emailTemplates.draft.delete('spree.order_mailer.confirm_email')
+ - lang: bash
+ label: Spree CLI
+ source: spree api delete /email_templates/{email_template_id}/draft
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ - name: language
+ in: query
+ required: false
+ description: A language code, or `any` (the default)
+ schema:
+ type: string
+ responses:
+ '200':
+ description: draft discarded
+ content:
+ application/json:
+ example:
+ id: spree.admin_user_mailer.password_reset_email
+ key: spree/admin_user_mailer/password_reset_email
+ subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ language: any
+ customized_languages: []
+ kind: email
+ customized: false
+ published_at:
+ default_subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ default_body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ default_changed: false
+ base_subject:
+ base_body:
+ draft:
+ schema:
+ "$ref": "#/components/schemas/EmailTemplate"
+ "/api/v3/admin/email_templates/{email_template_id}/publication":
+ parameters:
+ - name: email_template_id
+ in: path
+ required: true
+ description: The template key with dots
+ schema:
+ type: string
+ post:
+ summary: Publish an email template draft
+ tags:
+ - Email Templates
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Makes the draft what customers receive. The draft is first rendered
+ with sample data; one that does not render (for the layout or a
+ partial: in any email using it) is refused with 422, listing each
+ problem with its email and line.
+
+
+ **Required scope:** `write_email_templates` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ // Refused with 422 and each problem's email and line when the draft does not render.
+ const template = await client.emailTemplates.publish('spree.order_mailer.confirm_email')
+ - lang: bash
+ label: Spree CLI
+ source: spree api post /email_templates/{email_template_id}/publication -d
+ '{ ... }'
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ responses:
+ '201':
+ description: draft published
+ content:
+ application/json:
+ example:
+ id: spree.admin_user_mailer.password_reset_email
+ key: spree/admin_user_mailer/password_reset_email
+ subject: Reset {{ store.name }}
+ body: "<mj-section><mj-column><mj-text>Hi {{ user.first_name }}</mj-text></mj-column></mj-section>"
+ language: any
+ customized_languages:
+ - any
+ kind: email
+ customized: true
+ published_at: '2026-01-15T12:00:00Z'
+ default_subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ default_body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ default_changed: true
+ base_subject: Reset {{ store.name }}
+ base_body: "<mj-section><mj-column><mj-text>Default</mj-text></mj-column></mj-section>"
+ draft:
+ schema:
+ "$ref": "#/components/schemas/EmailTemplate"
+ '422':
+ description: the draft does not render
+ content:
+ application/json:
+ example:
+ error:
+ code: email_template_invalid
+ message: 'Liquid error (line 1): undefined variable nickname'
+ details:
+ problems:
+ - email: spree.admin_user_mailer.password_reset_email
+ message: 'Liquid error (line 1): undefined variable nickname'
+ line: 1
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ language:
+ type: string
+ example: any
+ "/api/v3/admin/email_templates/{email_template_id}/preview":
+ parameters:
+ - name: email_template_id
+ in: path
+ required: true
+ description: The template key with dots
+ schema:
+ type: string
+ post:
+ summary: Preview an email template
+ tags:
+ - Email Templates
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Renders the template with sample data built from the store's latest
+ matching record, or the one `record_id` names, and returns the email
+ with the variables it was rendered with. An unsaved `subject` and
+ `body` take the place of the current version. The layout and partials
+ render inside an email, `email_key` or the first one.
+
+
+ **Required scope:** `write_email_templates` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const preview = await client.emailTemplates.preview('spree.order_mailer.confirm_email', {
+ body: '<mj-section><mj-column><mj-text>Thanks, {{ order.customer_name }}!</mj-text></mj-column></mj-section>',
+ record_id: 'or_m3Rp9wXz',
+ })
+ - lang: bash
+ label: Spree CLI
+ source: spree api post /email_templates/{email_template_id}/preview -d '{"body":"<mj-section><mj-column><mj-text>Thanks,
+ {{ order.customer_name }}!</mj-text></mj-column></mj-section>","record_id":"or_m3Rp9wXz"}'
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ responses:
+ '200':
+ description: email template rendered
+ content:
+ application/json:
+ example:
+ id:
+ subject: ''
+ html: |-
+ <!doctype html><html lang="en" dir="auto" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!--><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
+ <style type="text/css">
+ #outlook a { padding: 0; }
+ body { margin: 0; padding: 0; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
+ table, td { border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; }
+ img { border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; }
+ p { display: block; margin: 13px 0; }
+ </style>
+ <!--[if mso]>
+ <noscript>
+ <xml>
+ <o:OfficeDocumentSettings>
+ <o:AllowPNG/>
+ <o:PixelsPerInch>96</o:PixelsPerInch>
+ </o:OfficeDocumentSettings>
+ </xml>
+ </noscript>
+ <![endif]-->
+ <!--[if lte mso 11]>
+ <style type="text/css">
+ .mj-outlook-group-fix { width:100% !important; }
+ </style>
+ <![endif]-->
+ <style type="text/css">@media only screen and (min-width:480px) { .mj-column-per-100 { width:100% !important; max-width:100%; } }</style><style media="screen and (min-width:480px)">.moz-text-html .mj-column-per-100 { width:100% !important; max-width:100%; } </style><style type="text/css">@font-face { font-family: "Geist"; font-style: normal; font-weight: 500 700; src: url("https://fonts.gstatic.com/s/geist/v4/gyByhwUxId8gMEwcGFU.woff2") format("woff2"); }
+ @font-face { font-family: "Inter"; font-style: normal; font-weight: 400 450; src: url("https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuOKfMZg.ttf") format("truetype"); }
+ @font-face { font-family: "Inter"; font-style: normal; font-weight: 500; src: url("https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuI6fMZg.ttf") format("truetype"); }
+ @font-face { font-family: "Inter"; font-style: normal; font-weight: 600; src: url("https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf") format("truetype"); }
+ a { color: #332C2C; }
+ .hero > table { max-width: 420px; margin: 0 auto; }
+ .note a { color: #726A6A; word-break: break-all; }
+ .footer a { color: #726A6A; }
+ .item { width: 100%; background-color: #F0F0F0; border-radius: 16px; margin: 0 0 8px; }
+ .item_image { padding: 8px; width: 96px; }
+ .item_thumb { display: block; width: 80px; height: auto; border-radius: 12px; }
+ .item_thumb_placeholder { width: 80px; height: 80px; background-color: #E4E4E4; border-radius: 12px; }
+ .item_info { padding: 8px 16px 8px 8px; }
+ .item_name { font-size: 15px; line-height: 1.5; font-weight: 500; color: #332C2C; text-decoration: none; }
+ .item_meta { margin: 2px 0 0; font-size: 13px; line-height: 1.5; color: #726A6A; }
+ .item_amount { padding: 8px 16px 8px 8px; text-align: right; white-space: nowrap; }
+ .item_qty { margin: 0; font-size: 13px; line-height: 1.5; color: #726A6A; }
+ .item_price { margin: 2px 0 0; font-size: 15px; line-height: 1.5; font-weight: 500; color: #332C2C; }
+ .summary td { padding: 6px 0; font-size: 14px; line-height: 1.6; color: #726A6A; }
+ .summary_value { font-size: 15px; font-weight: 500; text-align: right; white-space: nowrap; color: #332C2C; }
+ .summary_sub { display: block; font-size: 13px; line-height: 1.5; }
+ .summary_total td { padding: 14px 0 0; border-top: 1px solid #E8E9E9; font-weight: 500; color: #332C2C; }
+ .summary_total .summary_value { font-weight: 600; }
+ .mailer_hero h1 { margin: 0; font-family: Geist, Inter, Helvetica, Arial, sans-serif; font-size: 40px; line-height: 1.2; letter-spacing: -0.8px; font-weight: 700; color: #332C2C; }
+ .mailer_hero p { margin: 12px 0 0; }
+ .mailer_hero .greeting { margin-top: 24px; font-size: 15px; font-weight: 500; color: #332C2C; }
+ .mailer_hero .sub { margin-top: 24px; font-size: 13px; }
+ @media only screen and (max-width: 600px) {
+ .heading div { font-size: 32px !important; letter-spacing: -0.64px !important; }
+ }</style></head><body style="word-spacing:normal;background-color:#FFFFFF;"><div lang="en" dir="auto" style="background-color:#FFFFFF;"><!--[if mso | IE]><table border="0" cellpadding="0" cellspacing="0" role="presentation" bgcolor="#F6F6F6" align="center" width="640" style="width:640px;"><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="background:#F6F6F6;background-color:#F6F6F6;margin:0px auto;max-width:640px;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" align="center" style="background:#F6F6F6;background-color:#F6F6F6;width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:56px 24px;text-align:center;"><!--[if mso | IE]><table border="0" cellpadding="0" cellspacing="0" role="presentation"><tr><td width="640px"><![endif]--><!--[if mso | IE]><table border="0" cellpadding="0" cellspacing="0" role="presentation" align="center" width="592" style="width:592px;"><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="margin:0px auto;max-width:592px;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" align="center" style="width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:0 0 32px;text-align:center;"><!--[if mso | IE]><table border="0" cellpadding="0" cellspacing="0" role="presentation"><tr><![endif]--><!--[if mso | IE]><td style="vertical-align:top;width:592px;"><![endif]--><div class="mj-outlook-group-fix mj-column-per-100" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%"><tbody><tr><td style="vertical-align:top;padding:0;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%"><tbody><tr><td align="center" style="font-size:0px;padding:0;word-break:break-word;"><div style="font-family:Inter, Helvetica, Arial, sans-serif;font-size:22px;font-weight:700;line-height:1.6;text-align:center;text-transform:uppercase;color:#332C2C;"><a href="http://www.example.com:3000" style="color: #332C2C; text-decoration: none;">Spree Test Store</a></div></td></tr></tbody></table></td></tr></tbody></table></div><!--[if mso | IE]></td><![endif]--><!--[if mso | IE]></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--><!--[if mso | IE]></td></tr><tr><td width="640px"><![endif]--><!--[if mso | IE]><table border="0" cellpadding="0" cellspacing="0" role="presentation" align="center" width="592" style="width:592px;"><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="margin:0px auto;max-width:592px;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" align="center" style="width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:0;text-align:center;"><!--[if mso | IE]><table border="0" cellpadding="0" cellspacing="0" role="presentation"><tr><![endif]--><!--[if mso | IE]><td style="vertical-align:top;width:592px;"><![endif]--><div class="mj-outlook-group-fix mj-column-per-100" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%"><tbody><tr><td style="vertical-align:top;padding:0;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%"><tbody><tr><td align="center" style="font-size:0px;padding:0;word-break:break-word;"><div style="font-family:Inter, Helvetica, Arial, sans-serif;font-size:14px;line-height:1.6;text-align:center;color:#726A6A;">Hi Ann</div></td></tr></tbody></table></td></tr></tbody></table></div><!--[if mso | IE]></td><![endif]--><!--[if mso | IE]></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--><!--[if mso | IE]><table border="0" cellpadding="0" cellspacing="0" role="presentation" align="center" width="640" style="width:640px;"><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="margin:0px auto;max-width:640px;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" align="center" style="width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:64px 24px;text-align:center;"><!--[if mso | IE]><table border="0" cellpadding="0" cellspacing="0" role="presentation"><tr><![endif]--><!--[if mso | IE]><td style="vertical-align:top;width:640px;"><![endif]--><div class="mj-outlook-group-fix mj-column-per-100" style="font-size:0px;text-align:left;direction:ltr;display:inline-block;vertical-align:top;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%"><tbody><tr><td style="vertical-align:top;padding:0;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" width="100%"><tbody><tr><td align="center" class="footer" style="font-size:0px;padding:0;word-break:break-word;"><div style="font-family:Inter, Helvetica, Arial, sans-serif;font-size:13px;line-height:1.5;text-align:center;color:#726A6A;"><a href="http://www.example.com:3000" style="font-weight: 500; text-decoration: none;">Spree Test Store</a></div></td></tr><tr><td align="center" class="footer" style="font-size:0px;padding:12px 0 0;word-break:break-word;"><div style="font-family:Inter, Helvetica, Arial, sans-serif;font-size:11px;line-height:1.5;text-align:center;color:#726A6A;"><a href="mailto:[email protected]">[email protected]</a></div></td></tr><tr><td align="center" style="font-size:0px;padding:20px 0 0;word-break:break-word;"><div style="font-family:Inter, Helvetica, Arial, sans-serif;font-size:11px;line-height:1.5;text-align:center;color:#726A6A;">&copy; 2026 Spree Test Store</div></td></tr></tbody></table></td></tr></tbody></table></div><!--[if mso | IE]></td><![endif]--><!--[if mso | IE]></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>
+ text: |
+ Spree Test Store (http://www.example.com:3000)
+
+ Hi Ann
+
+ Spree Test Store (http://www.example.com:3000)
+
+
+ © 2026 Spree Test Store
+ email_key: spree.admin_user_mailer.password_reset_email
+ variables:
+ store:
+ id: store_UkLWZg9DAJ
+ name: Spree Test Store
+ address:
+ mail_from_address: [email protected]
+ default_currency: USD
+ default_locale: en
+ url: http://www.example.com:3000
+ support_email: [email protected]
+ logo_url:
+ logo_width:
+ locale: en
+ user:
+ first_name: Ann
+ reset_url: http://www.example.com:3000/reset-password?token=preview
+ schema:
+ "$ref": "#/components/schemas/EmailTemplatePreview"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ language:
+ type: string
+ example: any
+ subject:
+ type: string
+ example: Reset your {{ store.name }} password
+ body:
+ type: string
+ example: "<mj-section><mj-column><mj-text>Hi {{ user.first_name
+ }}</mj-text></mj-column></mj-section>"
+ record_id:
+ type: string
+ example: or_m3Rp9wXz
+ description: The record to build sample data from
+ email_key:
+ type: string
+ example: spree.order_mailer.confirm_email
+ description: For the layout or a partial, the email to show it in
+ "/api/v3/admin/email_templates/{email_template_id}/test_email":
+ parameters:
+ - name: email_template_id
+ in: path
+ required: true
+ description: The template key with dots
+ schema:
+ type: string
+ post:
+ summary: Send a test email
+ tags:
+ - Email Templates
+ security:
+ - bearer_auth: []
+ description: |-
+ Sends the template, rendered as the preview renders it, to the
+ signed-in admin, and never to another address: the sample data comes
+ from a real customer's records. Takes the same body as the preview.
+
+
+ **Required scope:** `write_email_templates` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ // Always sent to the signed-in admin.
+ const { sent_to } = await client.emailTemplates.sendTest('spree.order_mailer.confirm_email', {
+ body: '<mj-section><mj-column><mj-text>Thanks, {{ order.customer_name }}!</mj-text></mj-column></mj-section>',
+ })
+ - lang: bash
+ label: Spree CLI
+ source: spree api post /email_templates/{email_template_id}/test_email -d
+ '{"body":"<mj-section><mj-column><mj-text>Thanks, {{ order.customer_name
+ }}!</mj-text></mj-column></mj-section>"}'
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ responses:
+ '202':
+ description: test email queued
+ content:
+ application/json:
+ example:
+ schema:
+ type: object
+ properties:
+ sent_to:
+ type: string
+ required:
+ - sent_to
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ language:
+ type: string
+ example: any
+ subject:
+ type: string
+ body:
+ type: string
+ record_id:
+ type: string
+ email_key:
+ type: string
+ "/api/v3/admin/email_templates/{email_template_id}/revisions":
+ parameters:
+ - name: email_template_id
+ in: path
+ required: true
+ description: The template key with dots
+ schema:
+ type: string
+ get:
+ summary: List email template revisions
+ tags:
+ - Email Templates
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Every version of the template published in one language, newest
+ first. Reverting to Spree's default keeps them.
+
+
+ **Required scope:** `read_email_templates` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ const revisions = await client.emailTemplates.revisions.list('spree.order_mailer.confirm_email', {
+ expand: ['published_by'],
+ })
+ - lang: bash
+ label: Spree CLI
+ source: spree api get /email_templates/{email_template_id}/revisions -d '{"expand":["published_by"]}'
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ - name: language
+ in: query
+ required: false
+ description: A language code, or `any` (the default)
+ schema:
+ type: string
+ - name: page
+ in: query
+ required: false
+ description: Page number
+ schema:
+ type: integer
+ - name: limit
+ in: query
+ required: false
+ description: Number of records per page
+ schema:
+ type: integer
+ - name: expand
+ in: query
+ required: false
+ description: Comma-separated associations to expand (`published_by`)
+ schema:
+ type: string
+ responses:
+ '200':
+ description: revisions found
+ content:
+ application/json:
+ example:
+ data:
+ - id: etrv_UkLWZg9DAJ
+ subject: Reset {{ store.name }}
+ body: "<mj-section><mj-column><mj-text>Hello</mj-text></mj-column></mj-section>"
+ created_at: '2026-01-15T12:00:00.000Z'
+ published_by_id: adm_UkLWZg9DAJ
+ published_by_type: admin_user
+ meta:
+ page: 1
+ limit: 25
+ count: 1
+ pages: 1
+ from: 1
+ to: 1
+ in: 1
+ previous:
+ next:
+ "/api/v3/admin/email_templates/{email_template_id}/revisions/{revision_id}/restoration":
+ parameters:
+ - name: email_template_id
+ in: path
+ required: true
+ description: The template key with dots
+ schema:
+ type: string
+ - name: revision_id
+ in: path
+ required: true
+ schema:
+ type: string
+ post:
+ summary: Restore an email template revision
+ tags:
+ - Email Templates
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ Copies the revision into the draft, to be published like any change.
+ Send the draft's `lock_version` when one is open, as when saving it.
+
+
+ **Required scope:** `write_email_templates` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ // Copies the revision into the draft, to publish like any change.
+ const template = await client.emailTemplates.revisions.restore(
+ 'spree.order_mailer.confirm_email',
+ 'etrv_k5nR8xLq',
+ )
+ - lang: bash
+ label: Spree CLI
+ source: spree api post /email_templates/{email_template_id}/revisions/{revision_id}/restoration
+ -d '{ ... }'
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ responses:
+ '201':
+ description: revision copied into the draft
+ content:
+ application/json:
+ example:
+ id: spree.admin_user_mailer.password_reset_email
+ key: spree/admin_user_mailer/password_reset_email
+ subject: Reset {{ store.name }}
+ body: "<mj-section><mj-column><mj-text>Hello</mj-text></mj-column></mj-section>"
+ language: any
+ customized_languages:
+ - any
+ kind: email
+ customized: true
+ published_at: '2026-01-15T12:00:00Z'
+ default_subject: "{{ store.name }} {{ 'admin_user_mailer.password_reset_email.subject'
+ | t }}"
+ default_body: |
+ {% assign name = user.first_name | default: user.email %}
+ <mj-section>
+ <mj-column css-class="hero">
+ <mj-text mj-class="heading">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-text>
+ <mj-text mj-class="greeting">{{ 'admin_user_mailer.password_reset_email.greeting' | t: name: name }}</mj-text>
+ <mj-text mj-class="lead">{{ 'admin_user_mailer.password_reset_email.instructions' | t: store_name: store.name }}</mj-text>
+ <mj-button href="{{ reset_url }}">{{ 'admin_user_mailer.password_reset_email.action' | t }}</mj-button>
+ <mj-text mj-class="note">{{ 'admin_user_mailer.password_reset_email.expiry_notice' | t }}</mj-text>
+ <mj-text mj-class="note" padding="16px 0 0">{{ 'admin_user_mailer.password_reset_email.ignore_notice' | t }}</mj-text>
+ </mj-column>
+ </mj-section>
+ default_changed: true
+ base_subject: Reset {{ store.name }}
+ base_body: "<mj-section><mj-column><mj-text>Default</mj-text></mj-column></mj-section>"
+ draft:
+ id: etdr_UkLWZg9DAJ
+ subject: Reset {{ store.name }}
+ body: "<mj-section><mj-column><mj-text>Hi {{ user.first_name }}</mj-text></mj-column></mj-section>"
+ lock_version: 0
+ created_at: '2026-01-15T12:00:00.000Z'
+ updated_at: '2026-01-15T12:00:00.000Z'
+ updated_by_id: adm_UkLWZg9DAJ
+ updated_by_type: admin_user
+ schema:
+ "$ref": "#/components/schemas/EmailTemplate"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ language:
+ type: string
+ example: any
+ lock_version:
+ type: integer
"/api/v3/admin/exports":
get:
summary: List exports
@@ -41740,6 +43040,9 @@ tags:
by pricing and promotions
- name: Customers
description: Customer profiles, addresses, credit cards, and store credits
+- name: Email Templates
+ description: 'Customer email templates, the email layout and shared partials: drafts,
+ previews, publishing and history'
- name: Exports
description: Async CSV exports of admin resources
- name: Fulfillments
@@ -50897,4 +52200,166 @@ components:
- credential
- deprecated
- replaced_by
+ EmailTemplateDraft:
+ type: object
+ properties:
+ id:
+ type: string
+ subject:
+ type: string
+ nullable: true
+ body:
+ type: string
+ lock_version:
+ type: number
+ created_at:
+ type: string
+ updated_at:
+ type: string
+ updated_by_id:
+ type: string
+ nullable: true
+ updated_by_type:
+ anyOf:
+ - type: string
+ enum:
+ - admin_user
+ - api_key
+ - type: string
+ nullable: true
+ description: The values listed are the built-in ones; extensions may add
+ more.
+ updated_by:
+ "$ref": "#/components/schemas/Actor"
+ required:
+ - id
+ - subject
+ - body
+ - lock_version
+ - created_at
+ - updated_at
+ - updated_by_id
+ - updated_by_type
+ x-typelizer: true
+ EmailTemplatePreview:
+ type: object
+ properties:
+ id:
+ type: string
+ nullable: true
+ subject:
+ type: string
+ html:
+ type: string
+ text:
+ type: string
+ email_key:
+ type: string
+ variables:
+ type: object
+ required:
+ - id
+ - subject
+ - html
+ - text
+ - email_key
+ - variables
+ x-typelizer: true
+ EmailTemplateRevision:
+ type: object
+ properties:
+ id:
+ type: string
+ subject:
+ type: string
+ nullable: true
+ body:
+ type: string
+ created_at:
+ type: string
+ published_by_id:
+ type: string
+ nullable: true
+ published_by_type:
+ anyOf:
+ - type: string
+ enum:
+ - admin_user
+ - api_key
+ - type: string
+ nullable: true
+ description: The values listed are the built-in ones; extensions may add
+ more.
+ published_by:
+ "$ref": "#/components/schemas/Actor"
+ required:
+ - id
+ - subject
+ - body
+ - created_at
+ - published_by_id
+ - published_by_type
+ x-typelizer: true
+ EmailTemplate:
+ type: object
+ properties:
+ id:
+ type: string
+ key:
+ type: string
+ subject:
+ type: string
+ nullable: true
+ body:
+ type: string
+ language:
+ type: string
+ customized_languages:
+ type: array
+ items:
+ type: string
+ kind:
+ type: string
+ enum:
+ - email
+ - layout
+ - partial
+ customized:
+ type: boolean
+ published_at:
+ type: string
+ nullable: true
+ default_subject:
+ type: string
+ nullable: true
+ default_body:
+ type: string
+ default_changed:
+ type: boolean
+ base_subject:
+ type: string
+ nullable: true
+ base_body:
+ type: string
+ nullable: true
+ draft:
+ allOf:
+ - "$ref": "#/components/schemas/EmailTemplateDraft"
+ nullable: true
+ required:
+ - id
+ - key
+ - subject
+ - body
+ - language
+ - customized_languages
+ - kind
+ - customized
+ - published_at
+ - default_subject
+ - default_body
+ - default_changed
+ - base_subject
+ - base_body
+ - draft
x-typelizer: true
diff --git a/packages/admin-sdk/examples/email-templates/discard-draft.ts b/packages/admin-sdk/examples/email-templates/discard-draft.ts
new file mode 100644
index 0000000000..f28f70eda9
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/discard-draft.ts
@@ -0,0 +1,13 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const template = await client.emailTemplates.draft.delete('spree.order_mailer.confirm_email')
+
+// endregion:example
+
+export { template }
diff --git a/packages/admin-sdk/examples/email-templates/get.ts b/packages/admin-sdk/examples/email-templates/get.ts
new file mode 100644
index 0000000000..2ec789030e
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/get.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const template = await client.emailTemplates.get('spree.order_mailer.confirm_email', {
+ language: 'de',
+ expand: ['draft.updated_by'],
+})
+
+// endregion:example
+
+export { template }
diff --git a/packages/admin-sdk/examples/email-templates/list.ts b/packages/admin-sdk/examples/email-templates/list.ts
new file mode 100644
index 0000000000..0c7df5c2e7
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/list.ts
@@ -0,0 +1,13 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const templates = await client.emailTemplates.list()
+
+// endregion:example
+
+export { templates }
diff --git a/packages/admin-sdk/examples/email-templates/preview.ts b/packages/admin-sdk/examples/email-templates/preview.ts
new file mode 100644
index 0000000000..1654c1d950
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/preview.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const preview = await client.emailTemplates.preview('spree.order_mailer.confirm_email', {
+ body: '<mj-section><mj-column><mj-text>Thanks, {{ order.customer_name }}!</mj-text></mj-column></mj-section>',
+ record_id: 'or_m3Rp9wXz',
+})
+
+// endregion:example
+
+export { preview }
diff --git a/packages/admin-sdk/examples/email-templates/publish.ts b/packages/admin-sdk/examples/email-templates/publish.ts
new file mode 100644
index 0000000000..645dc630c7
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/publish.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+// Refused with 422 and each problem's email and line when the draft does not render.
+const template = await client.emailTemplates.publish('spree.order_mailer.confirm_email')
+
+// endregion:example
+
+export { template }
diff --git a/packages/admin-sdk/examples/email-templates/revert.ts b/packages/admin-sdk/examples/email-templates/revert.ts
new file mode 100644
index 0000000000..af3435f181
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/revert.ts
@@ -0,0 +1,14 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+// Goes back to Spree's default. Published versions stay in the history.
+const template = await client.emailTemplates.revert('spree.order_mailer.confirm_email')
+
+// endregion:example
+
+export { template }
diff --git a/packages/admin-sdk/examples/email-templates/revisions/list.ts b/packages/admin-sdk/examples/email-templates/revisions/list.ts
new file mode 100644
index 0000000000..4ffde58383
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/revisions/list.ts
@@ -0,0 +1,15 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+const revisions = await client.emailTemplates.revisions.list('spree.order_mailer.confirm_email', {
+ expand: ['published_by'],
+})
+
+// endregion:example
+
+export { revisions }
diff --git a/packages/admin-sdk/examples/email-templates/revisions/restore.ts b/packages/admin-sdk/examples/email-templates/revisions/restore.ts
new file mode 100644
index 0000000000..94c4a0e2d5
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/revisions/restore.ts
@@ -0,0 +1,17 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+// Copies the revision into the draft, to publish like any change.
+const template = await client.emailTemplates.revisions.restore(
+ 'spree.order_mailer.confirm_email',
+ 'etrv_k5nR8xLq',
+)
+
+// endregion:example
+
+export { template }
diff --git a/packages/admin-sdk/examples/email-templates/save-draft.ts b/packages/admin-sdk/examples/email-templates/save-draft.ts
new file mode 100644
index 0000000000..e24d9efdf0
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/save-draft.ts
@@ -0,0 +1,19 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+// Pass the lock_version the draft was loaded with: a save made from an
+// older copy is refused with 409, naming who saved last.
+const template = await client.emailTemplates.draft.update('spree.order_mailer.confirm_email', {
+ subject: 'Your order {{ order.number }} is confirmed',
+ body: '<mj-section><mj-column><mj-text>Thanks, {{ order.customer_name }}!</mj-text></mj-column></mj-section>',
+ lock_version: 0,
+})
+
+// endregion:example
+
+export { template }
diff --git a/packages/admin-sdk/examples/email-templates/send-test.ts b/packages/admin-sdk/examples/email-templates/send-test.ts
new file mode 100644
index 0000000000..8be2c3c839
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/send-test.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+// Always sent to the signed-in admin.
+const { sent_to } = await client.emailTemplates.sendTest('spree.order_mailer.confirm_email', {
+ body: '<mj-section><mj-column><mj-text>Thanks, {{ order.customer_name }}!</mj-text></mj-column></mj-section>',
+})
+
+// endregion:example
+
+export { sent_to }
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index cfd25490a0..5e4364516a 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -265,6 +265,10 @@ import type {
DigitalAssetProvider,
DigitalAssetUpdateParams,
DirectUploadCreateParams,
+ EmailTemplateDraftParams,
+ EmailTemplateLanguageParams,
+ EmailTemplatePreviewParams,
+ EmailTemplateRestoreParams,
ExchangeCreateParams,
ExchangeFulfillParams,
ExchangeReceiveParams,
@@ -428,6 +432,9 @@ import type {
DigitalAsset,
DigitalLink,
Discount,
+ EmailTemplate,
+ EmailTemplatePreview,
+ EmailTemplateRevision,
Exchange,
Export,
Fee,
@@ -5754,6 +5761,120 @@ export class AdminClient {
// Webhook Endpoints + Deliveries
// ============================================
+ readonly emailTemplates = {
+ /** Every editable email template: customer emails, the layout and shared partials. */
+ list: (
+ params?: EmailTemplateLanguageParams,
+ options?: RequestOptions,
+ ): Promise<{ data: EmailTemplate[] }> =>
+ this.request<{ data: EmailTemplate[] }>('GET', '/email_templates', { ...options, params }),
+
+ /** One template in one language, with the draft (`expand: ['draft.updated_by']` names who saved it). */
+ get: (
+ id: string,
+ params?: EmailTemplateLanguageParams & { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<EmailTemplate> =>
+ this.request<EmailTemplate>('GET', `/email_templates/${id}`, {
+ ...options,
+ params: getParams(params),
+ }),
+
+ /** Goes back to Spree's default and discards the draft. Published versions stay in the history. */
+ revert: (
+ id: string,
+ params?: EmailTemplateLanguageParams,
+ options?: RequestOptions,
+ ): Promise<EmailTemplate> =>
+ this.request<EmailTemplate>('DELETE', `/email_templates/${id}`, { ...options, params }),
+
+ draft: {
+ /** Saves the draft. A save from a stale `lock_version` is refused with 409. */
+ update: (
+ id: string,
+ params: EmailTemplateDraftParams,
+ options?: RequestOptions,
+ ): Promise<EmailTemplate> =>
+ this.request<EmailTemplate>('PUT', `/email_templates/${id}/draft`, {
+ ...options,
+ body: params,
+ }),
+
+ delete: (
+ id: string,
+ params?: EmailTemplateLanguageParams,
+ options?: RequestOptions,
+ ): Promise<EmailTemplate> =>
+ this.request<EmailTemplate>('DELETE', `/email_templates/${id}/draft`, {
+ ...options,
+ params,
+ }),
+ },
+
+ /** Makes the draft live; refused with 422 and each problem's email and line when it does not render. */
+ publish: (
+ id: string,
+ params?: EmailTemplateLanguageParams,
+ options?: RequestOptions,
+ ): Promise<EmailTemplate> =>
+ this.request<EmailTemplate>('POST', `/email_templates/${id}/publication`, {
+ ...options,
+ body: params ?? {},
+ }),
+
+ /** Renders the template, or unsaved changes to it, with sample data. */
+ preview: (
+ id: string,
+ params?: EmailTemplatePreviewParams,
+ options?: RequestOptions,
+ ): Promise<EmailTemplatePreview> =>
+ this.request<EmailTemplatePreview>('POST', `/email_templates/${id}/preview`, {
+ ...options,
+ body: params ?? {},
+ }),
+
+ /** Sends the rendered template to the signed-in admin. */
+ sendTest: (
+ id: string,
+ params?: EmailTemplatePreviewParams,
+ options?: RequestOptions,
+ ): Promise<{ sent_to: string }> =>
+ this.request<{ sent_to: string }>('POST', `/email_templates/${id}/test_email`, {
+ ...options,
+ body: params ?? {},
+ }),
+
+ revisions: {
+ /** Published versions in one language, newest first. */
+ list: (
+ id: string,
+ params?: ListParams & EmailTemplateLanguageParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<EmailTemplateRevision>> =>
+ this.request<PaginatedResponse<EmailTemplateRevision>>(
+ 'GET',
+ `/email_templates/${id}/revisions`,
+ {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ },
+ ),
+
+ /** Copies a revision into the draft, to publish like any change. */
+ restore: (
+ id: string,
+ revisionId: string,
+ params?: EmailTemplateRestoreParams,
+ options?: RequestOptions,
+ ): Promise<EmailTemplate> =>
+ this.request<EmailTemplate>(
+ 'POST',
+ `/email_templates/${id}/revisions/${revisionId}/restoration`,
+ { ...options, body: params ?? {} },
+ ),
+ },
+ }
+
/**
* The events a webhook endpoint can subscribe to, including those installed
* extensions declare. A `credential` event carries a live credential and
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 156afb06f8..2490ec8067 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -3135,3 +3135,31 @@ export interface StoreCreditListResponse {
data: StoreCredit[]
meta: StoreCreditListMeta
}
+
+export type EmailTemplateLanguageParams = {
+ /** A language code, or `any` (the default) for the version every language uses. */
+ language?: string
+}
+
+export interface EmailTemplateDraftParams extends EmailTemplateLanguageParams {
+ subject?: string | null
+ body?: string
+ /** The `lock_version` the draft was loaded with. A save from an older copy is refused with 409. */
+ lock_version?: number
+}
+
+export interface EmailTemplatePreviewParams extends EmailTemplateLanguageParams {
+ /** An unsaved subject, in place of the current one. */
+ subject?: string | null
+ /** An unsaved body, in place of the current one. */
+ body?: string
+ /** The record to build sample data from; the store's latest matching record otherwise. */
+ record_id?: string
+ /** For the layout or a partial, the email to show it in. */
+ email_key?: string
+}
+
+export interface EmailTemplateRestoreParams extends EmailTemplateLanguageParams {
+ /** The open draft's `lock_version`, when there is one. */
+ lock_version?: number
+}
diff --git a/packages/admin-sdk/src/types/generated/EmailTemplate.ts b/packages/admin-sdk/src/types/generated/EmailTemplate.ts
new file mode 100644
index 0000000000..907898a339
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/EmailTemplate.ts
@@ -0,0 +1,24 @@
+// Typelizer digest 33a1cbda41b1fe284b7147560021b264
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {EmailTemplateDraft} from '@/types'
+
+interface EmailTemplate {
+ id: string;
+ key: string;
+ subject: string | null;
+ body: string;
+ language: string;
+ customized_languages: Array<string>;
+ kind: 'email' | 'layout' | 'partial';
+ customized: boolean;
+ published_at: string | null;
+ default_subject: string | null;
+ default_body: string;
+ default_changed: boolean;
+ base_subject: string | null;
+ base_body: string | null;
+ draft: EmailTemplateDraft | null;
+}
+
+export default EmailTemplate;
diff --git a/packages/admin-sdk/src/types/generated/EmailTemplateDraft.ts b/packages/admin-sdk/src/types/generated/EmailTemplateDraft.ts
new file mode 100644
index 0000000000..fdd3c2b136
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/EmailTemplateDraft.ts
@@ -0,0 +1,18 @@
+// Typelizer digest 504fb35cefcb3210e6e4ae2893a5ce22
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {Actor, ActorKind} from '@/types'
+
+interface EmailTemplateDraft {
+ id: string;
+ subject: string | null;
+ body: string;
+ lock_version: number;
+ created_at: string;
+ updated_at: string;
+ updated_by_id: string | null;
+ updated_by_type: ActorKind | null;
+ updated_by?: Actor;
+}
+
+export default EmailTemplateDraft;
diff --git a/packages/admin-sdk/src/types/generated/EmailTemplatePreview.ts b/packages/admin-sdk/src/types/generated/EmailTemplatePreview.ts
new file mode 100644
index 0000000000..cc9c3e4c33
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/EmailTemplatePreview.ts
@@ -0,0 +1,14 @@
+// Typelizer digest 38910fdbd9ee295a32c59c3046e51d41
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+interface EmailTemplatePreview {
+ id: string | null;
+ subject: string;
+ html: string;
+ text: string;
+ email_key: string;
+ variables: Record<string, unknown>;
+}
+
+export default EmailTemplatePreview;
diff --git a/packages/admin-sdk/src/types/generated/EmailTemplateRevision.ts b/packages/admin-sdk/src/types/generated/EmailTemplateRevision.ts
new file mode 100644
index 0000000000..dbccd170db
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/EmailTemplateRevision.ts
@@ -0,0 +1,16 @@
+// Typelizer digest 91484d0e4bfb593251bf2dc2985aa842
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {Actor, ActorKind} from '@/types'
+
+interface EmailTemplateRevision {
+ id: string;
+ subject: string | null;
+ body: string;
+ created_at: string;
+ published_by_id: string | null;
+ published_by_type: ActorKind | null;
+ published_by?: Actor;
+}
+
+export default EmailTemplateRevision;
diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.ts
index a731300fa3..f2f0bf481d 100644
--- a/packages/admin-sdk/src/types/generated/index.ts
+++ b/packages/admin-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest ba521a005182a20314e162fa136ad8b6
+// Typelizer digest d58432aa78970c927a25efba27407762
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { ActorKind, ClaimStatus, DataRequestStatus, ExchangeStatus, FeeKind, FulfillmentItemStatus, FulfillmentStatus, GiftCardStatus, ImportRowStatus, ImportStatus, InvitationStatus, PaymentStatus, PriceListStatus, ProductStatus, ProductSubmissionStatus, ReturnStatus, SellerPayoutStatus, SellerRequirementSubmissionStatus, SellerStatus, SellerTransferStatus, ShippingLabelStatus, StockLocationKind, TaxExemptionCertificateStatus } from './Enums'
@@ -52,6 +52,10 @@ export type { default as DeliveryZone } from './DeliveryZone'
export type { default as DigitalAsset } from './DigitalAsset'
export type { default as DigitalLink } from './DigitalLink'
export type { default as Discount } from './Discount'
+export type { default as EmailTemplateDraft } from './EmailTemplateDraft'
+export type { default as EmailTemplatePreview } from './EmailTemplatePreview'
+export type { default as EmailTemplateRevision } from './EmailTemplateRevision'
+export type { default as EmailTemplate } from './EmailTemplate'
export type { default as ExchangeLineItem } from './ExchangeLineItem'
export type { default as Exchange } from './Exchange'
export type { default as Export } from './Export'
@@ -140,4 +144,3 @@ export type { default as TaxRate } from './TaxRate'
export type { default as Variant } from './Variant'
export type { default as WebhookDelivery } from './WebhookDelivery'
export type { default as WebhookEndpoint } from './WebhookEndpoint'
-export type { default as WebhookEvent } from './WebhookEvent'
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index 9802a28734..c671c7406b 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -60,6 +60,10 @@ export type { default as DeliveryZoneMember } from './generated/DeliveryZoneMemb
export type { default as DigitalAsset } from './generated/DigitalAsset'
export type { default as DigitalLink } from './generated/DigitalLink'
export type { default as Discount } from './generated/Discount'
+export type { default as EmailTemplate } from './generated/EmailTemplate'
+export type { default as EmailTemplateDraft } from './generated/EmailTemplateDraft'
+export type { default as EmailTemplatePreview } from './generated/EmailTemplatePreview'
+export type { default as EmailTemplateRevision } from './generated/EmailTemplateRevision'
// Named enums — open string unions for lists an extension may extend (statuses, fee kinds)
export type * from './generated/Enums'
export type { default as Exchange } from './generated/Exchange'
diff --git a/packages/admin-sdk/src/zod/generated/EmailTemplate.ts b/packages/admin-sdk/src/zod/generated/EmailTemplate.ts
new file mode 100644
index 0000000000..bb6b050eaa
--- /dev/null
+++ b/packages/admin-sdk/src/zod/generated/EmailTemplate.ts
@@ -0,0 +1,23 @@
+// This file is auto-generated. Do not edit directly.
+import { z } from 'zod';
+import { EmailTemplateDraftSchema } from './EmailTemplateDraft';
+
+export const EmailTemplateSchema = z.object({
+ id: z.string(),
+ key: z.string(),
+ subject: z.string().nullable(),
+ body: z.string(),
+ language: z.string(),
+ customized_languages: z.array(z.string()),
+ kind: z.string(),
+ customized: z.boolean(),
+ published_at: z.string().nullable(),
+ default_subject: z.string().nullable(),
+ default_body: z.string(),
+ default_changed: z.boolean(),
+ base_subject: z.string().nullable(),
+ base_body: z.string().nullable(),
+ draft: EmailTemplateDraftSchema.nullable(),
+});
+
+export type EmailTemplate = z.infer<typeof EmailTemplateSchema>;
diff --git a/packages/admin-sdk/src/zod/generated/EmailTemplateDraft.ts b/packages/admin-sdk/src/zod/generated/EmailTemplateDraft.ts
new file mode 100644
index 0000000000..8b8d5e8e32
--- /dev/null
+++ b/packages/admin-sdk/src/zod/generated/EmailTemplateDraft.ts
@@ -0,0 +1,17 @@
+// This file is auto-generated. Do not edit directly.
+import { z } from 'zod';
+import { ActorSchema } from './Actor';
+
+export const EmailTemplateDraftSchema = z.object({
+ id: z.string(),
+ subject: z.string().nullable(),
+ body: z.string(),
+ lock_version: z.number(),
+ created_at: z.string(),
+ updated_at: z.string(),
+ updated_by_id: z.string().nullable(),
+ updated_by_type: z.string().nullable(),
+ updated_by: ActorSchema.optional(),
+});
+
+export type EmailTemplateDraft = z.infer<typeof EmailTemplateDraftSchema>;
diff --git a/packages/admin-sdk/src/zod/generated/EmailTemplatePreview.ts b/packages/admin-sdk/src/zod/generated/EmailTemplatePreview.ts
new file mode 100644
index 0000000000..ba70bd5bc7
--- /dev/null
+++ b/packages/admin-sdk/src/zod/generated/EmailTemplatePreview.ts
@@ -0,0 +1,13 @@
+// This file is auto-generated. Do not edit directly.
+import { z } from 'zod';
+
+export const EmailTemplatePreviewSchema = z.object({
+ id: z.string().nullable(),
+ subject: z.string(),
+ html: z.string(),
+ text: z.string(),
+ email_key: z.string(),
+ variables: z.record(z.string(), z.unknown()),
+});
+
+export type EmailTemplatePreview = z.infer<typeof EmailTemplatePreviewSchema>;
diff --git a/packages/admin-sdk/src/zod/generated/EmailTemplateRevision.ts b/packages/admin-sdk/src/zod/generated/EmailTemplateRevision.ts
new file mode 100644
index 0000000000..5648be1b5b
--- /dev/null
+++ b/packages/admin-sdk/src/zod/generated/EmailTemplateRevision.ts
@@ -0,0 +1,15 @@
+// This file is auto-generated. Do not edit directly.
+import { z } from 'zod';
+import { ActorSchema } from './Actor';
+
+export const EmailTemplateRevisionSchema = z.object({
+ id: z.string(),
+ subject: z.string().nullable(),
+ body: z.string(),
+ created_at: z.string(),
+ published_by_id: z.string().nullable(),
+ published_by_type: z.string().nullable(),
+ published_by: ActorSchema.optional(),
+});
+
+export type EmailTemplateRevision = z.infer<typeof EmailTemplateRevisionSchema>;
diff --git a/packages/admin-sdk/src/zod/generated/index.ts b/packages/admin-sdk/src/zod/generated/index.ts
index f59dabdee9..e5ef4dd06d 100644
--- a/packages/admin-sdk/src/zod/generated/index.ts
+++ b/packages/admin-sdk/src/zod/generated/index.ts
@@ -49,6 +49,10 @@ export { DeliveryZoneMemberSchema, type DeliveryZoneMember } from './DeliveryZon
export { DigitalAssetSchema, type DigitalAsset } from './DigitalAsset';
export { DigitalLinkSchema, type DigitalLink } from './DigitalLink';
export { DiscountSchema, type Discount } from './Discount';
+export { EmailTemplateSchema, type EmailTemplate } from './EmailTemplate';
+export { EmailTemplateDraftSchema, type EmailTemplateDraft } from './EmailTemplateDraft';
+export { EmailTemplatePreviewSchema, type EmailTemplatePreview } from './EmailTemplatePreview';
+export { EmailTemplateRevisionSchema, type EmailTemplateRevision } from './EmailTemplateRevision';
export { ExchangeSchema, type Exchange } from './Exchange';
export { ExchangeLineItemSchema, type ExchangeLineItem } from './ExchangeLineItem';
export { ExportSchema, type Export } from './Export';
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 60b3de6af9..1dcbdfb85c 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -4159,6 +4159,7 @@
"customers": "حسابات العملاء والعناوين والبطاقات والمجموعات",
"dashboard": "تحليلات المبيعات والأداء",
"delivery_methods": "خيارات الشحن والأسعار والقواعد التي تتحكم بها",
+ "email_templates": "قوالب رسائل العملاء وتخطيط البريد والهوية البصرية",
"fulfillments": "تجهيز الطلبات وشحنها وتتبعها",
"gift_cards": "بطاقات الهدايا ودفعاتها",
"integrations": "بيانات اعتماد مزوّدي الخدمة واتصالاتهم",
@@ -4210,6 +4211,7 @@
"customers": "العملاء",
"dashboard": "Dashboard",
"delivery_methods": "طرق التوصيل",
+ "email_templates": "قوالب البريد الإلكتروني",
"fulfillments": "Fulfillments",
"gift_cards": "بطاقات الهدايا",
"integrations": "عمليات التكامل",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index ad24e980eb..54a77e592f 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -4131,6 +4131,7 @@
"customers": "Kundenkonten, Adressen, Karten und Gruppen",
"dashboard": "Umsatz- und Leistungsanalysen",
"delivery_methods": "Versandoptionen, Tarife und die Regeln, die sie steuern",
+ "email_templates": "Kunden-E-Mail-Vorlagen, das E-Mail-Layout und Branding",
"fulfillments": "Bestellungen packen, versenden und verfolgen",
"gift_cards": "Geschenkkarten und Geschenkkarten-Chargen",
"integrations": "Anbieter-Zugangsdaten und Verbindungen",
@@ -4182,6 +4183,7 @@
"customers": "Kunden",
"dashboard": "Dashboard",
"delivery_methods": "Versandarten",
+ "email_templates": "E-Mail-Vorlagen",
"fulfillments": "Fulfillments",
"gift_cards": "Geschenkkarten",
"integrations": "Integrationen",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index f0d42d6ebc..fd94c51813 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -4131,6 +4131,7 @@
"customers": "Customer accounts, addresses, cards and groups",
"dashboard": "Sales and performance analytics",
"delivery_methods": "Shipping options, rates and the rules that gate them",
+ "email_templates": "Customer email templates, the email layout and branding",
"fulfillments": "Pack, ship and track order fulfillments",
"gift_cards": "Gift cards and gift card batches",
"integrations": "Provider credentials and connections",
@@ -4182,6 +4183,7 @@
"customers": "Customers",
"dashboard": "Dashboard",
"delivery_methods": "Delivery methods",
+ "email_templates": "Email templates",
"fulfillments": "Fulfillments",
"gift_cards": "Gift cards",
"integrations": "Integrations",
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index a99fea8e74..d0f1e17a7e 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -4051,6 +4051,7 @@
"customers": "Cuentas, direcciones, tarjetas y grupos de clientes",
"dashboard": "Análisis de ventas y rendimiento",
"delivery_methods": "Opciones de envío, tarifas y las reglas que las controlan",
+ "email_templates": "Plantillas de correo para clientes, el diseño del correo y la marca",
"fulfillments": "Armar, despachar y rastrear cumplimientos de pedidos",
"gift_cards": "Tarjetas de regalo y lotes de tarjetas",
"integrations": "Credenciales y conexiones de proveedores",
@@ -4102,6 +4103,7 @@
"customers": "Clientes",
"dashboard": "Dashboard",
"delivery_methods": "Métodos de entrega",
+ "email_templates": "Plantillas de correo",
"fulfillments": "Cumplimientos",
"gift_cards": "Tarjetas de regalo",
"integrations": "Integraciones",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index cc4bb3cae3..34cc9381ff 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -4131,6 +4131,7 @@
"customers": "Comptes clients, adresses, cartes et groupes",
"dashboard": "Analyses des ventes et des performances",
"delivery_methods": "Options de livraison, tarifs et règles qui les conditionnent",
+ "email_templates": "Modèles d'e-mails clients, mise en page et image de marque des e-mails",
"fulfillments": "Préparer, expédier et suivre les commandes",
"gift_cards": "Cartes cadeaux et lots de cartes cadeaux",
"integrations": "Identifiants et connexions des fournisseurs",
@@ -4182,6 +4183,7 @@
"customers": "Clients",
"dashboard": "Tableau de bord",
"delivery_methods": "Modes de livraison",
+ "email_templates": "Modèles d'e-mail",
"fulfillments": "Exécutions des commandes",
"gift_cards": "Cartes cadeaux",
"integrations": "Intégrations",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 119dc21357..052bece73a 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -4185,6 +4185,7 @@
"customers": "Konta klientów, adresy, karty i grupy",
"dashboard": "Analizy sprzedaży i wyników",
"delivery_methods": "Opcje wysyłki, stawki i reguły, które nimi sterują",
+ "email_templates": "Szablony e-maili do klientów, układ e-maili i wygląd marki",
"fulfillments": "Pakowanie, wysyłka i śledzenie realizacji",
"gift_cards": "Karty podarunkowe i ich partie",
"integrations": "Dane dostępowe i połączenia dostawców",
@@ -4236,6 +4237,7 @@
"customers": "Klienci",
"dashboard": "Panel",
"delivery_methods": "Metody dostawy",
+ "email_templates": "Szablony e-maili",
"fulfillments": "Realizacje",
"gift_cards": "Karty podarunkowe",
"integrations": "Integracje",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 130e24c912..6c355b88cc 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -4121,6 +4121,7 @@
"customers": "客户账户、地址、卡片与分组",
"dashboard": "销售与业绩分析",
"delivery_methods": "配送选项、费率及其适用规则",
+ "email_templates": "客户邮件模板、邮件布局和品牌样式",
"fulfillments": "打包、发货并跟踪订单履约",
"gift_cards": "礼品卡及其批次",
"integrations": "服务商凭据与连接",
@@ -4172,6 +4173,7 @@
"customers": "客户",
"dashboard": "仪表盘",
"delivery_methods": "配送方式",
+ "email_templates": "邮件模板",
"fulfillments": "履约",
"gift_cards": "礼品卡",
"integrations": "集成",
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/email_template_lookup.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/email_template_lookup.rb
new file mode 100644
index 0000000000..ea7854c31f
--- /dev/null
+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/email_template_lookup.rb
@@ -0,0 +1,95 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Finds the editable email template a request is about, from its
+ # dotted key, for the language the request names.
+ module EmailTemplateLookup
+ extend ActiveSupport::Concern
+
+ included do
+ scoped_resource :email_templates
+
+ before_action :load_email_template
+
+ rescue_from Spree::EmailTemplates::NoSampleRecord, with: :render_no_sample
+ rescue_from Liquid::Error, MRML::Error, with: :render_render_error
+ end
+
+ private
+
+ attr_reader :email_template
+
+ def load_email_template
+ @email_template = Spree::EmailTemplates::Entry.find(
+ current_store, params[:email_template_id] || params[:id], locale: language
+ )
+ end
+
+ # A language code, or "any" for the version every language uses. Named
+ # `language` rather than `locale`, which picks the response's language.
+ def language
+ @language ||= params[:language].to_s.strip.presence || Spree::EmailTemplate::ANY_LOCALE
+ end
+
+ def serialize_email_template(reload: false)
+ load_email_template if reload
+ Spree.api.admin_email_template_serializer.new(email_template, params: serializer_params).to_h
+ end
+
+ def serializer_class
+ Spree.api.admin_email_template_serializer
+ end
+
+ # An unsaved subject and body are previewed only when sent, so an
+ # empty body still previews as empty.
+ def preview_arguments
+ arguments = params.permit(:record_id, :subject, :body).to_h.symbolize_keys
+ arguments[:locale] = language
+ arguments[:email_key] = params[:email_key].to_s.tr('.', '/').presence
+ arguments
+ end
+
+ def build_preview
+ Spree::EmailTemplates::Preview.new(store: current_store, key: email_template.key, strict: true, **preview_arguments)
+ end
+
+ def render_template_problems(problems)
+ problems = problems.map { |problem| problem.merge(email: problem[:email].tr('/', '.')) }
+
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:email_template_invalid],
+ message: problems.map { |problem| problem[:message] }.uniq.to_sentence,
+ status: :unprocessable_content,
+ details: { problems: problems }
+ )
+ end
+
+ def render_render_error(error)
+ email = params[:email_key].presence || email_template.id
+ render_template_problems([{ email: email.to_s, message: error.message, line: error.try(:line_number) }])
+ end
+
+ def render_no_sample(error)
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:email_template_no_sample],
+ message: error.message,
+ status: :unprocessable_content
+ )
+ end
+
+ def render_stale_draft
+ saved_by = email_template.draft&.updated_by&.actor_label
+
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:email_template_stale],
+ message: Spree.t('email_templates.stale_draft', name: saved_by || Spree.t('email_templates.another_admin')),
+ status: :conflict,
+ details: { updated_by: saved_by }
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
index 421fe3332a..34116339eb 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
@@ -74,6 +74,11 @@ module Spree
# Export errors
export_not_ready: 'export_not_ready',
+ # Email template errors
+ email_template_stale: 'email_template_stale',
+ email_template_invalid: 'email_template_invalid',
+ email_template_no_sample: 'email_template_no_sample',
+
# Rate limiting errors
rate_limit_exceeded: 'rate_limit_exceeded',
diff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/drafts_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/drafts_controller.rb
new file mode 100644
index 0000000000..077b4d353f
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/drafts_controller.rb
@@ -0,0 +1,40 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module EmailTemplates
+ # The draft of an editable email template: saved in any state, while
+ # customers keep receiving the published version.
+ class DraftsController < Admin::BaseController
+ include Spree::Api::V3::Admin::EmailTemplateLookup
+
+ # PUT /api/v3/admin/email_templates/:email_template_id/draft
+ #
+ # Send the `lock_version` the draft was loaded with: a save made from
+ # an older copy is refused with 409, naming who saved last.
+ def update
+ authorize! :update, Spree::EmailTemplate
+
+ result = Spree.email_template_save_draft_workflow.call(
+ store: current_store, key: email_template.key, locale: language, actor: current_actor,
+ attributes: params.permit(:subject, :body, :lock_version).to_h.symbolize_keys
+ )
+ return render_stale_draft if result.error&.value == :stale
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_email_template(reload: true)
+ end
+
+ # DELETE /api/v3/admin/email_templates/:email_template_id/draft
+ def destroy
+ authorize! :update, Spree::EmailTemplate
+
+ current_store.email_template_drafts.for_key(email_template.key, language).destroy_all
+ render json: serialize_email_template(reload: true)
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/previews_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/previews_controller.rb
new file mode 100644
index 0000000000..83e51254b7
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/previews_controller.rb
@@ -0,0 +1,28 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module EmailTemplates
+ class PreviewsController < Admin::BaseController
+ include Spree::Api::V3::Admin::EmailTemplateLookup
+
+ # POST /api/v3/admin/email_templates/:email_template_id/preview
+ #
+ # Renders the template with sample data built from the store's latest
+ # matching record, or the one `record_id` names. An unsaved `subject`
+ # and `body` take the place of the current version. Returns the
+ # rendered email and the variables it was rendered with.
+ def create
+ authorize! :update, Spree::EmailTemplate
+
+ preview = build_preview
+ preview.call
+
+ render json: Spree.api.admin_email_template_preview_serializer.new(preview, params: serializer_params).to_h
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/publications_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/publications_controller.rb
new file mode 100644
index 0000000000..74315ab670
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/publications_controller.rb
@@ -0,0 +1,30 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module EmailTemplates
+ class PublicationsController < Admin::BaseController
+ include Spree::Api::V3::Admin::EmailTemplateLookup
+
+ # POST /api/v3/admin/email_templates/:email_template_id/publication
+ #
+ # Makes the draft live. A draft that does not render with sample data
+ # (for the layout or a partial: in any email using it) is refused with
+ # 422 and each problem's email and line.
+ def create
+ authorize! :update, Spree::EmailTemplate
+
+ result = Spree.email_template_publish_workflow.call(
+ store: current_store, key: email_template.key, locale: language, actor: current_actor
+ )
+ return render_template_problems(result.value) if result.error&.value == :invalid_template
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_email_template(reload: true), status: :created
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/restorations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/restorations_controller.rb
new file mode 100644
index 0000000000..9f604ba38b
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/restorations_controller.rb
@@ -0,0 +1,32 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module EmailTemplates
+ class RestorationsController < Admin::BaseController
+ include Spree::Api::V3::Admin::EmailTemplateLookup
+
+ # POST /api/v3/admin/email_templates/:email_template_id/revisions/:revision_id/restoration
+ #
+ # Copies the revision into the draft, to be published like any change.
+ def create
+ authorize! :update, Spree::EmailTemplate
+
+ revision = Spree::EmailTemplateRevision.where(
+ email_template: current_store.email_templates.for_key(email_template.key, language)
+ ).find_by_prefix_id!(params[:revision_id])
+
+ result = Spree.email_template_restore_revision_workflow.call(
+ revision: revision, actor: current_actor, lock_version: params[:lock_version]
+ )
+ return render_stale_draft if result.error&.value == :stale
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_email_template(reload: true), status: :created
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/revisions_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/revisions_controller.rb
new file mode 100644
index 0000000000..2bb77e73bb
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/revisions_controller.rb
@@ -0,0 +1,35 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module EmailTemplates
+ # The published versions of an email template in one language, newest
+ # first. Reverting keeps them, so they outlive the published version.
+ class RevisionsController < ResourceController
+ include Spree::Api::V3::Admin::EmailTemplateLookup
+
+ protected
+
+ def model_class
+ Spree::EmailTemplateRevision
+ end
+
+ def serializer_class
+ Spree.api.admin_email_template_revision_serializer
+ end
+
+ def scope
+ Spree::EmailTemplateRevision.where(
+ email_template: current_store.email_templates.for_key(email_template.key, language)
+ ).order(created_at: :desc)
+ end
+
+ def collection_includes
+ [:published_by]
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/test_emails_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/test_emails_controller.rb
new file mode 100644
index 0000000000..c1df129b3b
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/test_emails_controller.rb
@@ -0,0 +1,38 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module EmailTemplates
+ class TestEmailsController < Admin::BaseController
+ include Spree::Api::V3::Admin::EmailTemplateLookup
+
+ # POST /api/v3/admin/email_templates/:email_template_id/test_email
+ #
+ # Sends the template, rendered as the preview renders it, to the
+ # signed-in admin. Never to another address: the sample data comes
+ # from a real customer's records.
+ def create
+ authorize! :update, Spree::EmailTemplate
+ return render_no_recipient unless current_user
+
+ build_preview.call
+ Spree::EmailTemplateMailer.test_email(current_store, current_user.email, email_template.key, **preview_arguments).deliver_later
+
+ render json: { sent_to: current_user.email }, status: :accepted
+ end
+
+ private
+
+ def render_no_recipient
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:invalid_request],
+ message: Spree.t('email_templates.test_email_needs_admin'),
+ status: :unprocessable_content
+ )
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates_controller.rb
new file mode 100644
index 0000000000..62e7169e63
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates_controller.rb
@@ -0,0 +1,47 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # The customer email templates, layout and shared partials merchants
+ # may edit, addressed by their key with dots
+ # (`spree.order_mailer.confirm_email`). `language` picks the version:
+ # a language code, or `any` (the default) for every language.
+ class EmailTemplatesController < Admin::BaseController
+ include Spree::Api::V3::Admin::EmailTemplateLookup
+
+ skip_before_action :load_email_template, only: :index
+
+ # GET /api/v3/admin/email_templates
+ def index
+ authorize! :read, Spree::EmailTemplate
+
+ entries = Spree::EmailTemplates::Entry.all(current_store, locale: language)
+ render json: { data: serialize_collection(entries), meta: {} }
+ end
+
+ # GET /api/v3/admin/email_templates/:id
+ def show
+ authorize! :read, Spree::EmailTemplate
+
+ render json: serialize_email_template
+ end
+
+ # DELETE /api/v3/admin/email_templates/:id
+ #
+ # Goes back to Spree's default for this language. The store's version
+ # and its history are kept, so a revision can still be restored.
+ def destroy
+ authorize! :update, Spree::EmailTemplate
+
+ result = Spree.email_template_revert_workflow.call(
+ store: current_store, key: email_template.key, locale: language, actor: current_actor
+ )
+ return render_result_error(result) unless result.success?
+
+ render json: serialize_email_template(reload: true)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/email_template_draft_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/email_template_draft_serializer.rb
new file mode 100644
index 0000000000..6f2b12a68a
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/email_template_draft_serializer.rb
@@ -0,0 +1,19 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class EmailTemplateDraftSerializer < V3::BaseSerializer
+ typelize subject: [:string, nullable: true],
+ body: :string,
+ lock_version: :number,
+ updated_by_id: [:string, nullable: true],
+ updated_by_type: [:string, nullable: true, enum: Spree::Actor::BUILT_IN_KINDS, enum_type_name: 'ActorKind']
+
+ attributes :subject, :body, :lock_version, created_at: :iso8601, updated_at: :iso8601
+
+ actor_attributes :updated_by
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/email_template_preview_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/email_template_preview_serializer.rb
new file mode 100644
index 0000000000..f6249cc8c2
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/email_template_preview_serializer.rb
@@ -0,0 +1,38 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # A rendered preview of an email template, with the variables it was
+ # rendered with, as example values for the editor.
+ class EmailTemplatePreviewSerializer < V3::BaseSerializer
+ typelize id: [:string, nullable: true],
+ subject: :string,
+ html: :string,
+ text: :string,
+ email_key: :string,
+ variables: 'Record<string, unknown>'
+
+ attribute :subject do |preview|
+ preview.rendered.subject
+ end
+
+ attribute :html do |preview|
+ preview.rendered.html
+ end
+
+ attribute :text do |preview|
+ preview.rendered.text
+ end
+
+ # The email the preview renders: the template itself, or for the
+ # layout and partials, the email shown around them.
+ attribute :email_key do |preview|
+ preview.email.key.tr('/', '.')
+ end
+
+ attribute :variables, &:variables
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/email_template_revision_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/email_template_revision_serializer.rb
new file mode 100644
index 0000000000..9df85c1cff
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/email_template_revision_serializer.rb
@@ -0,0 +1,18 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class EmailTemplateRevisionSerializer < V3::BaseSerializer
+ typelize subject: [:string, nullable: true],
+ body: :string,
+ published_by_id: [:string, nullable: true],
+ published_by_type: [:string, nullable: true, enum: Spree::Actor::BUILT_IN_KINDS, enum_type_name: 'ActorKind']
+
+ attributes :subject, :body, created_at: :iso8601
+
+ actor_attributes :published_by
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/email_template_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/email_template_serializer.rb
new file mode 100644
index 0000000000..42fb65cf66
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/email_template_serializer.rb
@@ -0,0 +1,68 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # An editable email template for one language: what customers receive
+ # now (the store's published version, else Spree's default), Spree's
+ # default, and the draft in progress.
+ class EmailTemplateSerializer < V3::BaseSerializer
+ typelize key: :string,
+ kind: [:string, enum: Spree::Emails::EditableTemplates::KINDS.map(&:to_s)],
+ language: :string,
+ customized: :boolean,
+ customized_languages: [:string, multi: true],
+ subject: [:string, nullable: true],
+ body: :string,
+ published_at: [:string, nullable: true],
+ default_subject: [:string, nullable: true],
+ default_body: :string,
+ default_changed: :boolean,
+ base_subject: [:string, nullable: true],
+ base_body: [:string, nullable: true],
+ draft: ['EmailTemplateDraft', nullable: true]
+
+ attributes :key, :subject, :body
+
+ # A language code, or `any` for the version every language uses.
+ attribute :language, &:locale
+
+ attribute :customized_languages, &:customized_locales
+
+ attribute :kind do |entry|
+ entry.kind.to_s
+ end
+
+ attribute :customized, &:customized?
+
+ attribute :published_at do |entry|
+ entry.published&.published_at&.iso8601
+ end
+
+ attribute :default_subject do |entry|
+ entry.default&.subject
+ end
+
+ attribute :default_body do |entry|
+ entry.default&.body
+ end
+
+ attribute :default_changed do |entry|
+ entry.outdated_version.present?
+ end
+
+ # The default the store's version started from, when Spree's default
+ # has changed since: compare it with `default_body` to see what changed.
+ attribute :base_subject do |entry|
+ entry.outdated_version&.base_subject
+ end
+
+ attribute :base_body do |entry|
+ entry.outdated_version&.base_body
+ end
+
+ one :draft, resource: proc { Spree.api.admin_email_template_draft_serializer }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 57821a60f5..ca06ed0b6f 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -282,6 +282,19 @@ Spree::Core::Engine.add_routes do
post :redeliver, on: :member
end
end
+ # Addressed by template key with dots (`spree.order_mailer.confirm_email`).
+ resources :email_templates, only: [:index, :show, :destroy], format: false,
+ constraints: { id: /[a-z0-9_.]+/, email_template_id: /[a-z0-9_.]+/ } do
+ scope module: :email_templates do
+ resource :draft, only: [:update, :destroy]
+ resource :publication, only: [:create]
+ resource :preview, only: [:create]
+ resource :test_email, only: [:create]
+ resources :revisions, only: [:index], constraints: { id: %r{[^/]+} } do
+ resource :restoration, only: [:create]
+ end
+ end
+ end
resources :roles, only: [:index, :show, :create, :update, :destroy]
resources :permissions, only: [:index]
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 1852cbda8d..92d714fc7a 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -41,7 +41,8 @@ module Spree
store setup_task api_key allowed_origin webhook_endpoint webhook_event webhook_delivery invitation
invitation_acceptance_link role permission export saved_report import import_row import_mapping promotion
promotion_action promotion_rule coupon_code price_adjustment_tier price_list price_rule
- resource_translations].freeze
+ resource_translations email_template email_template_draft email_template_revision email_template_preview
+ email_template_sample_record].freeze
SELLER_SERIALIZERS =
%i[profile policy team_member account invitation invitation_acceptance_link product product_type
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/drafts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/drafts_controller_spec.rb
new file mode 100644
index 0000000000..5a52898ad9
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/drafts_controller_spec.rb
@@ -0,0 +1,59 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::EmailTemplates::DraftsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+ include_context 'with an editable email template'
+
+ let(:id) { editable_key.tr('/', '.') }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'PUT #update' do
+ it 'saves the draft, leaving what customers receive alone' do
+ put :update, params: { email_template_id: id, subject: 'New subject', body: '<mj-section></mj-section>' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['customized']).to be(false)
+ expect(json_response['draft']).to include('subject' => 'New subject', 'body' => '<mj-section></mj-section>')
+ expect(store.email_template_drafts.first.updated_by).to eq(admin_user)
+ end
+
+ it 'saves a version for one language' do
+ put :update, params: { email_template_id: id, language: 'de', body: 'German draft' }, as: :json
+
+ expect(store.email_template_drafts.first.locale).to eq('de')
+ end
+
+ it 'refuses a save from a stale copy with 409, naming who saved last' do
+ create(:email_template_draft, store: store, key: editable_key, body: 'Theirs', updated_by: create(:admin_user, first_name: 'Maria', last_name: 'Lopez'))
+ store.email_template_drafts.first.update!(body: 'Theirs again')
+
+ put :update, params: { email_template_id: id, body: 'Mine', lock_version: 0 }, as: :json
+
+ expect(response).to have_http_status(:conflict)
+ expect(json_response['error']['code']).to eq('email_template_stale')
+ expect(json_response['error']['message']).to include('Maria')
+ expect(store.email_template_drafts.first.body).to eq('Theirs again')
+ end
+
+ it 'refuses a language code that is not one' do
+ put :update, params: { email_template_id: id, language: 'not a language', body: 'x' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'discards the draft' do
+ create(:email_template_draft, store: store, key: editable_key)
+
+ delete :destroy, params: { email_template_id: id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['draft']).to be_nil
+ expect(store.email_template_drafts.count).to eq(0)
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/previews_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/previews_controller_spec.rb
new file mode 100644
index 0000000000..bd71cdcf60
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/previews_controller_spec.rb
@@ -0,0 +1,42 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::EmailTemplates::PreviewsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+ include_context 'with an editable email template'
+
+ let(:id) { editable_key.tr('/', '.') }
+
+ before { request.headers.merge!(headers) }
+
+ it 'renders unsaved changes with sample data and returns the variables used' do
+ post :create, params: {
+ email_template_id: id, subject: 'Hi {{ user.first_name }}',
+ body: '<mj-section><mj-column><mj-text>For {{ user.email }}</mj-text></mj-column></mj-section>'
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response).to include('subject' => 'Hi Ann', 'email_key' => id)
+ expect(json_response['html']).to include('For [email protected]')
+ expect(json_response['text']).to include('For [email protected]')
+ expect(json_response['variables']['user']).to include('first_name' => 'Ann')
+ end
+
+ it 'says what is wrong and where when the template does not render' do
+ post :create, params: { email_template_id: id, body: "<mj-section>\n{% if %}</mj-section>" }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['details']['problems'].first).to include('email' => id, 'line' => 2)
+ end
+
+ it 'says so when the store has nothing to preview with' do
+ allow(Spree::TestingSupport::EmailTemplateSample).to receive(:new).
+ and_raise(Spree::EmailTemplates::NoSampleRecord, 'There is no order in this store to preview this email with yet.')
+
+ post :create, params: { email_template_id: id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']).to include('code' => 'email_template_no_sample', 'message' => a_string_including('no order'))
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/publications_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/publications_controller_spec.rb
new file mode 100644
index 0000000000..1a9d208d1e
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/publications_controller_spec.rb
@@ -0,0 +1,41 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::EmailTemplates::PublicationsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+ include_context 'with an editable email template'
+
+ let(:id) { editable_key.tr('/', '.') }
+ let(:body) { '<mj-section><mj-column><mj-text>Hi {{ user.first_name }}</mj-text></mj-column></mj-section>' }
+
+ before { request.headers.merge!(headers) }
+
+ it 'makes the draft live' do
+ create(:email_template_draft, store: store, key: editable_key, body: body)
+
+ post :create, params: { email_template_id: id }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response).to include('customized' => true, 'body' => body, 'draft' => nil)
+ end
+
+ it 'refuses a draft that does not render, with each problem and its line' do
+ create(:email_template_draft, store: store, key: editable_key, body: "<mj-section>\n<mj-column><mj-text>{{ user.nickname }}</mj-text></mj-column></mj-section>")
+
+ post :create, params: { email_template_id: id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('email_template_invalid')
+ expect(json_response['error']['details']['problems']).to contain_exactly(
+ hash_including('email' => id, 'line' => 2, 'message' => a_string_including('nickname'))
+ )
+ expect(store.email_templates.count).to eq(0)
+ end
+
+ it 'refuses when there is no draft' do
+ post :create, params: { email_template_id: id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/restorations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/restorations_controller_spec.rb
new file mode 100644
index 0000000000..abb192749c
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/restorations_controller_spec.rb
@@ -0,0 +1,29 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::EmailTemplates::RestorationsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+ include_context 'with an editable email template'
+
+ let(:id) { editable_key.tr('/', '.') }
+ let(:template) { create(:email_template, store: store, key: editable_key) }
+ let(:revision) { create(:email_template_revision, email_template: template, subject: 'Old subject', body: 'Old body') }
+
+ before { request.headers.merge!(headers) }
+
+ it 'copies the revision into the draft' do
+ post :create, params: { email_template_id: id, revision_id: revision.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['draft']).to include('subject' => 'Old subject', 'body' => 'Old body')
+ end
+
+ it "does not restore another store's revision" do
+ other = create(:email_template_revision, email_template: create(:email_template, store: create(:store), key: editable_key))
+
+ post :create, params: { email_template_id: id, revision_id: other.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/revisions_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/revisions_controller_spec.rb
new file mode 100644
index 0000000000..060b1fb20d
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/revisions_controller_spec.rb
@@ -0,0 +1,26 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::EmailTemplates::RevisionsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+ include_context 'with an editable email template'
+
+ let(:id) { editable_key.tr('/', '.') }
+ let(:template) { create(:email_template, store: store, key: editable_key) }
+
+ before { request.headers.merge!(headers) }
+
+ it "lists the template's published versions in one language, newest first" do
+ older = create(:email_template_revision, email_template: template, created_at: 2.days.ago, published_by: admin_user)
+ newer = create(:email_template_revision, email_template: template, created_at: 1.day.ago)
+ create(:email_template_revision, email_template: create(:email_template, store: store, key: editable_key, locale: 'de'))
+ create(:email_template_revision, email_template: create(:email_template, store: create(:store), key: editable_key))
+
+ get :index, params: { email_template_id: id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].map { |revision| revision['id'] }).to eq([newer.prefixed_id, older.prefixed_id])
+ expect(json_response['data'].last['published_by_type']).to eq('admin_user')
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/test_emails_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/test_emails_controller_spec.rb
new file mode 100644
index 0000000000..104f8236a3
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/test_emails_controller_spec.rb
@@ -0,0 +1,39 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::EmailTemplates::TestEmailsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+ include_context 'with an editable email template'
+
+ let(:id) { editable_key.tr('/', '.') }
+
+ before { request.headers.merge!(headers) }
+
+ it 'sends the rendered template to the signed-in admin only' do
+ expect do
+ post :create, params: { email_template_id: id, to: '[email protected]', body: '<mj-section><mj-column><mj-text>Test</mj-text></mj-column></mj-section>' }, as: :json
+ end.to have_enqueued_mail(Spree::EmailTemplateMailer, :test_email).with(store, admin_user.email, editable_key, hash_including(body: a_string_including('Test')))
+
+ expect(response).to have_http_status(:accepted)
+ expect(json_response['sent_to']).to eq(admin_user.email)
+ end
+
+ it 'sends nothing for a template that does not render' do
+ expect do
+ post :create, params: { email_template_id: id, body: '{{ user.nickname }}' }, as: :json
+ end.not_to have_enqueued_mail
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ context 'with a secret key, which has no inbox' do
+ let(:headers) { api_key_headers }
+
+ it 'refuses' do
+ post :create, params: { email_template_id: id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates_controller_spec.rb
new file mode 100644
index 0000000000..36992ed32d
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates_controller_spec.rb
@@ -0,0 +1,85 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::EmailTemplatesController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+ include_context 'with an editable email template'
+
+ let(:id) { editable_key.tr('/', '.') }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ it 'lists every editable template, Spree default or the store version' do
+ create(:email_template, store: store, key: editable_key, locale: 'de', body: 'German')
+
+ get :index, as: :json
+
+ entry = json_response['data'].find { |template| template['id'] == id }
+ expect(entry).to include('kind' => 'email', 'language' => 'any', 'customized' => false, 'customized_languages' => ['de'])
+ expect(entry['body']).to eq(entry['default_body'])
+ expect(json_response['data'].map { |template| template['id'] }).not_to include('spree.webhook_mailer.endpoint_disabled')
+ end
+ end
+
+ describe 'GET #show' do
+ it "returns the store's published version, the draft and whether the default moved on" do
+ create(:email_template, store: store, key: editable_key, body: 'Published', base_body: 'An older default')
+ create(:email_template_draft, store: store, key: editable_key, body: 'Draft', base_body: 'An older default', updated_by: admin_user)
+
+ get :show, params: { id: id, expand: 'draft.updated_by' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response).to include('customized' => true, 'body' => 'Published', 'default_changed' => true, 'base_body' => 'An older default')
+ expect(json_response['draft']).to include('body' => 'Draft', 'lock_version' => 0, 'updated_by_type' => 'admin_user')
+ expect(json_response['draft']['updated_by']['label']).to be_present
+ end
+
+ it 'reads the version for the language asked for' do
+ create(:email_template, store: store, key: editable_key, locale: 'de', body: 'German')
+
+ get :show, params: { id: id, language: 'de' }, as: :json
+
+ expect(json_response).to include('language' => 'de', 'body' => 'German')
+ end
+
+ it 'does not find a template merchants may not edit' do
+ get :show, params: { id: 'spree.webhook_mailer.endpoint_disabled' }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "never reads another store's version" do
+ create(:email_template, store: create(:store), key: editable_key, body: 'Theirs')
+
+ get :show, params: { id: id }, as: :json
+
+ expect(json_response['customized']).to be(false)
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it "goes back to Spree's default, keeping the history" do
+ template = create(:email_template, store: store, key: editable_key, body: 'Published')
+ create(:email_template_revision, email_template: template)
+
+ delete :destroy, params: { id: id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['customized']).to be(false)
+ expect(template.reload).to be_reverted
+ expect(template.revisions.count).to eq(1)
+ end
+ end
+
+ context 'with a secret key lacking the email templates scope' do
+ let(:headers) { { 'x-spree-api-key' => create(:api_key, :secret, store: store, scopes: %w[read_settings]).plaintext_token } }
+
+ it 'is refused' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb
new file mode 100644
index 0000000000..ce0a3db326
--- /dev/null
+++ b/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb
@@ -0,0 +1,417 @@
+# frozen_string_literal: true
+
+require 'swagger_helper'
+
+RSpec.describe 'Admin Email Templates API', type: :request, swagger_doc: 'api-reference/admin.yaml' do
+ include_context 'API v3 Admin'
+ include_context 'with an editable email template'
+
+ let(:Authorization) { "Bearer #{admin_jwt_token}" }
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:id) { editable_key.tr('/', '.') }
+ let(:email_template_id) { id }
+ let(:body_mjml) { '<mj-section><mj-column><mj-text>Hi {{ user.first_name }}</mj-text></mj-column></mj-section>' }
+
+ shared_context 'with admin auth parameters' do
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true,
+ description: 'Bearer token for admin authentication'
+ end
+
+ path '/api/v3/admin/email_templates' do
+ get 'List email templates' do
+ tags 'Email Templates'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Returns every email template merchants may edit: the emails customers
+ receive, the email layout and the shared partials. Each shows what
+ customers receive now (the store's published version, else Spree's
+ default) and any draft in progress. Staff emails are not editable.
+ DESC
+ admin_scope :read, :email_templates
+
+ admin_sdk_example 'email-templates/list'
+
+ include_context 'with admin auth parameters'
+ parameter name: :language, in: :query, type: :string, required: false,
+ description: 'A language code, or `any` (the default) for the version every language uses'
+
+ response '200', 'email templates found' do
+ run_test! do |response|
+ data = JSON.parse(response.body)['data']
+ expect(data.map { |template| template['id'] }).to include(id)
+ end
+ end
+ end
+ end
+
+ path '/api/v3/admin/email_templates/{id}' do
+ parameter name: :id, in: :path, type: :string, required: true,
+ description: 'The template key with dots, e.g. `spree.order_mailer.confirm_email`'
+
+ get 'Get an email template' do
+ tags 'Email Templates'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Returns the template for one language: what customers receive now,
+ Spree's default, and the draft with its `lock_version`. When Spree's
+ default changed since the store's version started from it,
+ `default_changed` is true and `base_body` holds the default it
+ started from, to compare with `default_body`.
+ DESC
+ admin_scope :read, :email_templates
+
+ admin_sdk_example 'email-templates/get'
+
+ include_context 'with admin auth parameters'
+ parameter name: :language, in: :query, type: :string, required: false,
+ description: 'A language code, or `any` (the default)'
+ parameter name: :expand, in: :query, type: :string, required: false,
+ description: 'Comma-separated associations to expand (`draft.updated_by`)'
+
+ response '200', 'email template found' do
+ schema '$ref' => '#/components/schemas/EmailTemplate'
+
+ before { create(:email_template_draft, store: store, key: editable_key, body: body_mjml, updated_by: admin_user) }
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['id']).to eq(id)
+ expect(data['draft']['body']).to eq(body_mjml)
+ end
+ end
+
+ response '404', 'not an editable template' do
+ let(:id) { 'spree.webhook_mailer.endpoint_disabled' }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+
+ delete "Revert an email template to Spree's default" do
+ tags 'Email Templates'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Goes back to Spree's default for one language and discards the draft.
+ The store's published versions are kept, so one can still be restored.
+ DESC
+ admin_scope :write, :email_templates
+
+ admin_sdk_example 'email-templates/revert'
+
+ include_context 'with admin auth parameters'
+ parameter name: :language, in: :query, type: :string, required: false,
+ description: 'A language code, or `any` (the default)'
+
+ response '200', 'email template reverted' do
+ schema '$ref' => '#/components/schemas/EmailTemplate'
+
+ before { create(:email_template, store: store, key: editable_key, body: body_mjml) }
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['customized']).to be(false)
+ end
+ end
+ end
+ end
+
+ path '/api/v3/admin/email_templates/{email_template_id}/draft' do
+ parameter name: :email_template_id, in: :path, type: :string, required: true,
+ description: 'The template key with dots'
+
+ put 'Save an email template draft' do
+ tags 'Email Templates'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Saves the draft, in any state; customers keep receiving the published
+ version until it is published. Send the `lock_version` the draft was
+ loaded with: a save made from an older copy is refused with 409,
+ naming who saved last. The first save starts from what is published,
+ else Spree's default.
+ DESC
+ admin_scope :write, :email_templates
+
+ admin_sdk_example 'email-templates/save-draft'
+
+ include_context 'with admin auth parameters'
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ properties: {
+ language: { type: :string, example: 'any' },
+ subject: { type: :string, example: 'Reset your {{ store.name }} password' },
+ body: { type: :string, example: '<mj-section><mj-column><mj-text>Hi {{ user.first_name }}</mj-text></mj-column></mj-section>' },
+ lock_version: { type: :integer, example: 0 }
+ }
+ }
+
+ response '200', 'draft saved' do
+ let(:body) { { subject: 'Reset your {{ store.name }} password', body: body_mjml } }
+
+ schema '$ref' => '#/components/schemas/EmailTemplate'
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['draft']['lock_version']).to eq(0)
+ end
+ end
+
+ response '409', 'saved by someone else since it was loaded' do
+ let(:body) { { body: body_mjml, lock_version: 0 } }
+
+ before do
+ draft = create(:email_template_draft, store: store, key: editable_key, updated_by: admin_user)
+ draft.update!(body: 'Saved again')
+ end
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+
+ delete 'Discard an email template draft' do
+ tags 'Email Templates'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ admin_scope :write, :email_templates
+
+ admin_sdk_example 'email-templates/discard-draft'
+
+ include_context 'with admin auth parameters'
+ parameter name: :language, in: :query, type: :string, required: false,
+ description: 'A language code, or `any` (the default)'
+
+ response '200', 'draft discarded' do
+ schema '$ref' => '#/components/schemas/EmailTemplate'
+
+ before { create(:email_template_draft, store: store, key: editable_key) }
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['draft']).to be_nil
+ end
+ end
+ end
+ end
+
+ path '/api/v3/admin/email_templates/{email_template_id}/publication' do
+ parameter name: :email_template_id, in: :path, type: :string, required: true,
+ description: 'The template key with dots'
+
+ post 'Publish an email template draft' do
+ tags 'Email Templates'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Makes the draft what customers receive. The draft is first rendered
+ with sample data; one that does not render (for the layout or a
+ partial: in any email using it) is refused with 422, listing each
+ problem with its email and line.
+ DESC
+ admin_scope :write, :email_templates
+
+ admin_sdk_example 'email-templates/publish'
+
+ include_context 'with admin auth parameters'
+ parameter name: :body, in: :body, required: false, schema: {
+ type: :object,
+ properties: { language: { type: :string, example: 'any' } }
+ }
+
+ response '201', 'draft published' do
+ let(:body) { {} }
+
+ schema '$ref' => '#/components/schemas/EmailTemplate'
+
+ before { create(:email_template_draft, store: store, key: editable_key, body: body_mjml) }
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['customized']).to be(true)
+ end
+ end
+
+ response '422', 'the draft does not render' do
+ let(:body) { {} }
+
+ before { create(:email_template_draft, store: store, key: editable_key, body: '{{ user.nickname }}') }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test! do |response|
+ problems = JSON.parse(response.body)['error']['details']['problems']
+ expect(problems.first['message']).to include('nickname')
+ end
+ end
+ end
+ end
+
+ path '/api/v3/admin/email_templates/{email_template_id}/preview' do
+ parameter name: :email_template_id, in: :path, type: :string, required: true,
+ description: 'The template key with dots'
+
+ post 'Preview an email template' do
+ tags 'Email Templates'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Renders the template with sample data built from the store's latest
+ matching record, or the one `record_id` names, and returns the email
+ with the variables it was rendered with. An unsaved `subject` and
+ `body` take the place of the current version. The layout and partials
+ render inside an email, `email_key` or the first one.
+ DESC
+ admin_scope :write, :email_templates
+
+ admin_sdk_example 'email-templates/preview'
+
+ include_context 'with admin auth parameters'
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ properties: {
+ language: { type: :string, example: 'any' },
+ subject: { type: :string, example: 'Reset your {{ store.name }} password' },
+ body: { type: :string, example: '<mj-section><mj-column><mj-text>Hi {{ user.first_name }}</mj-text></mj-column></mj-section>' },
+ record_id: { type: :string, example: 'or_m3Rp9wXz', description: 'The record to build sample data from' },
+ email_key: { type: :string, example: 'spree.order_mailer.confirm_email', description: 'For the layout or a partial, the email to show it in' }
+ }
+ }
+
+ response '200', 'email template rendered' do
+ let(:body) { { body: body_mjml } }
+
+ schema '$ref' => '#/components/schemas/EmailTemplatePreview'
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['html']).to include('Hi Ann')
+ end
+ end
+ end
+ end
+
+ path '/api/v3/admin/email_templates/{email_template_id}/test_email' do
+ parameter name: :email_template_id, in: :path, type: :string, required: true,
+ description: 'The template key with dots'
+
+ post 'Send a test email' do
+ tags 'Email Templates'
+ consumes 'application/json'
+ produces 'application/json'
+ security [bearer_auth: []]
+ description <<~DESC
+ Sends the template, rendered as the preview renders it, to the
+ signed-in admin, and never to another address: the sample data comes
+ from a real customer's records. Takes the same body as the preview.
+ DESC
+ admin_scope :write, :email_templates
+
+ admin_sdk_example 'email-templates/send-test'
+
+ include_context 'with admin auth parameters'
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ properties: {
+ language: { type: :string, example: 'any' },
+ subject: { type: :string },
+ body: { type: :string },
+ record_id: { type: :string },
+ email_key: { type: :string }
+ }
+ }
+
+ response '202', 'test email queued' do
+ let(:body) { { body: body_mjml } }
+
+ schema type: :object, properties: { sent_to: { type: :string } }, required: %w[sent_to]
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['sent_to']).to eq(admin_user.email)
+ end
+ end
+ end
+ end
+
+ path '/api/v3/admin/email_templates/{email_template_id}/revisions' do
+ parameter name: :email_template_id, in: :path, type: :string, required: true,
+ description: 'The template key with dots'
+
+ get 'List email template revisions' do
+ tags 'Email Templates'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Every version of the template published in one language, newest
+ first. Reverting to Spree's default keeps them.
+ DESC
+ admin_scope :read, :email_templates
+
+ admin_sdk_example 'email-templates/revisions/list'
+
+ include_context 'with admin auth parameters'
+ parameter name: :language, in: :query, type: :string, required: false,
+ description: 'A language code, or `any` (the default)'
+ parameter name: :page, in: :query, type: :integer, required: false, description: 'Page number'
+ parameter name: :limit, in: :query, type: :integer, required: false, description: 'Number of records per page'
+ parameter name: :expand, in: :query, type: :string, required: false,
+ description: 'Comma-separated associations to expand (`published_by`)'
+
+ response '200', 'revisions found' do
+ before do
+ template = create(:email_template, store: store, key: editable_key)
+ create(:email_template_revision, email_template: template, published_by: admin_user)
+ end
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['data'].size).to eq(1)
+ end
+ end
+ end
+ end
+
+ path '/api/v3/admin/email_templates/{email_template_id}/revisions/{revision_id}/restoration' do
+ parameter name: :email_template_id, in: :path, type: :string, required: true,
+ description: 'The template key with dots'
+ parameter name: :revision_id, in: :path, type: :string, required: true
+
+ post 'Restore an email template revision' do
+ tags 'Email Templates'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Copies the revision into the draft, to be published like any change.
+ Send the draft's `lock_version` when one is open, as when saving it.
+ DESC
+ admin_scope :write, :email_templates
+
+ admin_sdk_example 'email-templates/revisions/restore'
+
+ include_context 'with admin auth parameters'
+ parameter name: :body, in: :body, required: false, schema: {
+ type: :object,
+ properties: {
+ language: { type: :string, example: 'any' },
+ lock_version: { type: :integer }
+ }
+ }
+
+ response '201', 'revision copied into the draft' do
+ let(:template) { create(:email_template, store: store, key: editable_key) }
+ let(:revision_id) { create(:email_template_revision, email_template: template, body: body_mjml).prefixed_id }
+ let(:body) { {} }
+
+ schema '$ref' => '#/components/schemas/EmailTemplate'
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['draft']['body']).to eq(body_mjml)
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/spec_helper.rb b/spree/api/spec/spec_helper.rb
index 777b402769..b03b6f42e6 100644
--- a/spree/api/spec/spec_helper.rb
+++ b/spree/api/spec/spec_helper.rb
@@ -52,6 +52,7 @@ require 'spree/testing_support/store'
require 'spree/testing_support/preferences'
require 'spree/testing_support/tax_identifier_validators'
require 'spree/testing_support/image_helpers'
+require 'spree/testing_support/editable_email_templates'
require 'spree/api/testing_support/v3/base'
require 'spree/api/testing_support/factories'
diff --git a/spree/api/spec/swagger_helper.rb b/spree/api/spec/swagger_helper.rb
index 5bac86857c..e4c163f168 100644
--- a/spree/api/spec/swagger_helper.rb
+++ b/spree/api/spec/swagger_helper.rb
@@ -166,6 +166,7 @@ RSpec.configure do |config|
{ name: 'Custom Fields', description: 'Custom field definitions for products, variants, customers, and other resources' },
{ name: 'Customer Groups', description: 'Customer groups for segmenting customers (e.g. wholesale, VIP) used by pricing and promotions' },
{ name: 'Customers', description: 'Customer profiles, addresses, credit cards, and store credits' },
+ { name: 'Email Templates', description: 'Customer email templates, the email layout and shared partials: drafts, previews, publishing and history' },
{ name: 'Exports', description: 'Async CSV exports of admin resources' },
{ name: 'Fulfillments', description: 'Order fulfillments — shipments, fulfill, cancel, resume, split' },
{ name: 'Gift Cards', description: 'Gift cards and gift card batches' },
diff --git a/spree/core/app/mailers/spree/email_template_mailer.rb b/spree/core/app/mailers/spree/email_template_mailer.rb
new file mode 100644
index 0000000000..dcd182b6dd
--- /dev/null
+++ b/spree/core/app/mailers/spree/email_template_mailer.rb
@@ -0,0 +1,25 @@
+module Spree
+ # Sends an editable email template, rendered with sample data as the editor
+ # previews it, so a merchant can see it in a real inbox before publishing.
+ class EmailTemplateMailer < BaseMailer
+ # @param store [Spree::Store]
+ # @param recipient [String] the email address of the admin who asked for it
+ # @param key [String] the editable template
+ # @param locale [String] a language code, or "any"
+ # @param subject [String, nil] an unsaved subject
+ # @param body [String, nil] an unsaved body
+ # @param record_id [String, nil] the record to build sample data from
+ # @param email_key [String, nil] for the layout or a partial, the email to show it in
+ def test_email(store, recipient, key, locale: nil, subject: nil, body: nil, record_id: nil, email_key: nil)
+ @current_store = store
+ email = Spree::EmailTemplates::Preview.new(
+ store: store, key: key, locale: locale, subject: subject, body: body, record_id: record_id, email_key: email_key
+ ).call
+
+ mail(to: recipient, subject: Spree.t('email_templates.test_email_subject', subject: email.subject)) do |format|
+ format.text { render plain: email.text, layout: false }
+ format.html { render html: email.html.html_safe, layout: false }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/email_template_identity.rb b/spree/core/app/models/concerns/spree/email_template_identity.rb
index e317a95c21..ab3ab506e1 100644
--- a/spree/core/app/models/concerns/spree/email_template_identity.rb
+++ b/spree/core/app/models/concerns/spree/email_template_identity.rb
@@ -19,6 +19,7 @@ module Spree
validates :locale, format: { with: LOCALE_FORMAT }
validates :body, :base_body, presence: true
validate :key_editable
+ validate :locale_supported
scope :for_key, ->(key, locale = ANY_LOCALE) { where(key: key, locale: locale) }
end
@@ -41,5 +42,11 @@ module Spree
def key_editable
errors.add(:key, :invalid) if key.present? && definition.nil?
end
+
+ def locale_supported
+ return if locale == ANY_LOCALE || store.nil?
+
+ errors.add(:locale, :inclusion) unless store.supported_locales_list.include?(locale)
+ end
end
end
diff --git a/spree/core/app/models/spree/email_templates/entry.rb b/spree/core/app/models/spree/email_templates/entry.rb
new file mode 100644
index 0000000000..f552aed0cf
--- /dev/null
+++ b/spree/core/app/models/spree/email_templates/entry.rb
@@ -0,0 +1,83 @@
+module Spree
+ module EmailTemplates
+ # One editable email template for one store and language, as the editor
+ # shows it: what customers receive now, the draft in progress and
+ # Spree's default.
+ class Entry
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ attribute :definition
+ attribute :locale, :string, default: Spree::EmailTemplate::ANY_LOCALE
+ attribute :published
+ attribute :draft
+ attribute :customized_locales, default: -> { [] }
+
+ delegate :key, :kind, to: :definition
+
+ # @param store [Spree::Store]
+ # @param locale [String] a language code, or "any"
+ # @return [Array<Spree::EmailTemplates::Entry>] every editable template
+ def self.all(store, locale: Spree::EmailTemplate::ANY_LOCALE)
+ published = store.email_templates.published.where(locale: locale).index_by(&:key)
+ drafts = store.email_template_drafts.where(locale: locale).includes(:updated_by).index_by(&:key)
+ customized = store.email_templates.published.pluck(:key, :locale).group_by(&:first)
+
+ Spree.editable_email_templates.map do |definition|
+ new(definition: definition, locale: locale, published: published[definition.key], draft: drafts[definition.key],
+ customized_locales: customized.fetch(definition.key, []).map(&:last).sort)
+ end
+ end
+
+ # @param store [Spree::Store]
+ # @param id [String] the template's key with dots, e.g. "spree.order_mailer.confirm_email"
+ # @param locale [String]
+ # @return [Spree::EmailTemplates::Entry]
+ # @raise [ActiveRecord::RecordNotFound] when no editable template has that id
+ def self.find(store, id, locale: Spree::EmailTemplate::ANY_LOCALE)
+ definition = Spree.editable_email_templates[id.to_s.tr('.', '/')]
+ raise ActiveRecord::RecordNotFound, "Couldn't find email template #{id}" unless definition
+
+ locale = locale.presence || Spree::EmailTemplate::ANY_LOCALE
+ new(
+ definition: definition, locale: locale,
+ published: store.email_templates.published.for_key(definition.key, locale).first,
+ draft: store.email_template_drafts.for_key(definition.key, locale).first,
+ customized_locales: store.email_templates.published.where(key: definition.key).order(:locale).pluck(:locale)
+ )
+ end
+
+ # The key with dots, so it fits in a URL segment.
+ def id
+ key.tr('/', '.')
+ end
+ alias prefixed_id id
+
+ def customized?
+ published.present?
+ end
+
+ # @return [Spree::Emails::Template, nil] the template file Spree or the app ships
+ def default
+ @default ||= Spree::Emails::TemplateResolver.new(Spree::BaseMailer.view_paths.paths.map(&:path)).find_default(key)
+ end
+
+ # What customers receive now.
+ def subject
+ customized? ? published.subject : default&.subject
+ end
+
+ def body
+ customized? ? published.body : default&.body
+ end
+
+ # The default the store's version started from, when Spree's default has
+ # changed since, so the editor can show what changed.
+ #
+ # @return [Spree::EmailTemplate, Spree::EmailTemplateDraft, nil]
+ def outdated_version
+ [draft, published].compact.find { |version| version.default_changed?(default) }
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/email_templates/preview.rb b/spree/core/app/services/spree/email_templates/preview.rb
index 760881bd01..a90e246c1e 100644
--- a/spree/core/app/services/spree/email_templates/preview.rb
+++ b/spree/core/app/services/spree/email_templates/preview.rb
@@ -11,6 +11,9 @@ module Spree
# @return [Hash] the variables the email was rendered with, once {#call} has run
attr_reader :variables
+ # @return [Spree::Emails::RenderedEmail, nil] the rendered email, once {#call} has run
+ attr_reader :rendered
+
# @param store [Spree::Store]
# @param key [String] the editable template being previewed
# @param locale [String] a language code, or "any"
@@ -40,7 +43,7 @@ module Spree
renderer = Spree::Emails::Renderer.new(resolver: resolver, store: @store, currency: sample.currency, strict: @strict)
sample_variables = sample.variables
@variables = renderer.variables(sample_variables)
- renderer.render(resolver.find(email.key), sample_variables)
+ @rendered = renderer.render(resolver.find(email.key), sample_variables)
end
end
diff --git a/spree/core/app/services/spree/emails/template_resolver.rb b/spree/core/app/services/spree/emails/template_resolver.rb
index 09f324e3ff..86498c46f8 100644
--- a/spree/core/app/services/spree/emails/template_resolver.rb
+++ b/spree/core/app/services/spree/emails/template_resolver.rb
@@ -38,7 +38,7 @@ module Spree
# @return [Spree::Emails::Template, nil]
def find_default(key)
validate!(key)
- find_file(key, '.liquid')
+ Spree.editable_email_templates[key]&.kind == :partial ? partial_file(key) : find_file(key, '.liquid')
end
# A hand-written plain-text part. A store's saved template has none, so
@@ -57,11 +57,7 @@ module Spree
# @return [Spree::Emails::Template, nil] the store's version, or "spree/shared/_line_item.liquid"
def find_partial(name)
validate!(name)
- override = @drafts[name] || stored(name)
- return override if override
-
- *folders, file = name.split('/')
- find_file([*folders, "_#{file}"].join('/'), '.liquid')
+ @drafts[name] || stored(name) || partial_file(name)
end
private
@@ -77,6 +73,11 @@ module Spree
@stored[key] = record && Template.new(key: key, subject: record.subject, body: record.body)
end
+ def partial_file(name)
+ *folders, file = name.split('/')
+ find_file([*folders, "_#{file}"].join('/'), '.liquid')
+ end
+
def find_file(key, extension)
view_paths.each do |view_path|
path = File.join(view_path, "#{key}#{extension}")
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index d899259b23..02863991f1 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -922,6 +922,12 @@ en:
wrong_country: This coupon code is not eligible in your country
email: Email
email_marketing: Email marketing
+ email_templates:
+ another_admin: another admin
+ no_sample_record: There is no %{record} in this store to preview this email with yet.
+ stale_draft: "%{name} saved this draft after you opened it. Reload to see their changes before saving yours."
+ test_email_needs_admin: A test email goes to the signed-in admin, so it needs one.
+ test_email_subject: "[Test] %{subject}"
emails: Emails
empty: Empty
end: End
@@ -1291,6 +1297,9 @@ en:
dashboard:
description: Sales and performance analytics
label: Analytics dashboard
+ email_templates:
+ description: Customer email templates, the email layout and branding
+ label: Email templates
fulfillments:
description: Pack, ship and track order fulfillments
label: Fulfillments
diff --git a/spree/core/lib/spree/testing_support/editable_email_templates.rb b/spree/core/lib/spree/testing_support/editable_email_templates.rb
index 666e4bc385..ddbe39cc74 100644
--- a/spree/core/lib/spree/testing_support/editable_email_templates.rb
+++ b/spree/core/lib/spree/testing_support/editable_email_templates.rb
@@ -34,6 +34,9 @@ end
RSpec.shared_context 'with an editable email template' do
let(:editable_key) { 'spree/admin_user_mailer/password_reset_email' }
+ # Templates have per-language versions only in the store's languages.
+ before { allow_any_instance_of(Spree::Store).to receive(:supported_locales_list).and_return(%w[de en fr]) }
+
around do |example|
registry = Spree.editable_email_templates
previous = registry[editable_key]
diff --git a/spree/core/spec/mailers/spree/email_template_mailer_spec.rb b/spree/core/spec/mailers/spree/email_template_mailer_spec.rb
new file mode 100644
index 0000000000..7818f05746
--- /dev/null
+++ b/spree/core/spec/mailers/spree/email_template_mailer_spec.rb
@@ -0,0 +1,18 @@
+require 'spec_helper'
+
+describe Spree::EmailTemplateMailer, type: :mailer do
+ include_context 'with an editable email template'
+
+ let(:store) { @default_store }
+
+ it 'sends the unsaved template, rendered with sample data, marked as a test' do
+ mail = described_class.test_email(store, '[email protected]', editable_key,
+ subject: 'Hi {{ user.first_name }}',
+ body: '<mj-section><mj-column><mj-text>Draft for {{ user.email }}</mj-text></mj-column></mj-section>')
+
+ expect(mail.to).to eq(['[email protected]'])
+ expect(mail.subject).to eq('[Test] Hi Ann')
+ expect(mail.html_part.body.to_s).to include('Draft for [email protected]')
+ expect(mail.text_part.body.to_s).to include('Draft for [email protected]')
+ end
+end
diff --git a/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rb b/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rb
index 95243ebbd9..5aa7cd642a 100644
--- a/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rb
+++ b/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rb
@@ -29,6 +29,20 @@ describe Spree::EmailTemplates::SaveDraft do
expect(draft.base_body).to eq('Old default')
end
+ it "starts a shared partial from its file" do
+ Spree.editable_email_templates.register('spree/shared/summary_row', kind: :partial)
+ path = Rails.root.join('app/views/spree/shared/_summary_row.liquid')
+ FileUtils.mkdir_p(path.dirname)
+ File.write(path, '<mj-text>{{ label }}</mj-text>')
+
+ draft = described_class.new.call(store: store, key: 'spree/shared/summary_row', attributes: { subject: nil }).value
+
+ expect(draft.body).to eq('<mj-text>{{ label }}</mj-text>')
+ ensure
+ Spree.editable_email_templates.delete('spree/shared/summary_row')
+ FileUtils.rm_f(path)
+ end
+
it 'refuses a save made from a stale copy' do
draft = save({ body: 'first' }).value
save({ body: 'second', lock_version: draft.lock_version })
diff --git a/spree/emails/app/services/spree/emails/samples/base.rb b/spree/emails/app/services/spree/emails/samples/base.rb
index 566b7775da..a72ae768ff 100644
--- a/spree/emails/app/services/spree/emails/samples/base.rb
+++ b/spree/emails/app/services/spree/emails/samples/base.rb
@@ -38,7 +38,7 @@ module Spree
@record ||= if record_id
records.find_by_prefix_id!(record_id)
else
- records.first || raise(Spree::EmailTemplates::NoSampleRecord, Spree.t('emails.samples.no_record', record: self.class.record_type.to_s.humanize.downcase))
+ records.first || raise(Spree::EmailTemplates::NoSampleRecord, Spree.t('email_templates.no_sample_record', record: self.class.record_type.to_s.humanize.downcase))
end
end
diff --git a/spree/emails/config/locales/en.yml b/spree/emails/config/locales/en.yml
index 0addbf688c..4b44aedf75 100644
--- a/spree/emails/config/locales/en.yml
+++ b/spree/emails/config/locales/en.yml
@@ -31,9 +31,6 @@ en:
dear_customer: Dear %{name},
instructions: The files from your order %{number} are ready to download.
subject: Your files are ready
- emails:
- samples:
- no_record: There is no %{record} in this store to preview this email with yet.
fulfillment_mailer:
fulfilled_email:
dear_customer: Dear %{name},