# Templates

Source: https://molted.email/docs/templates

Create, version, and publish email templates with approval workflows and lint checks.

Templates define the structure and content of your outbound emails. Each template has versioned content, automatic linting, and optional approval workflows.

Every template endpoint requires authentication: a Bearer API key (on `api.molted.email` also your `tenantId`, in the query string or body), or a signed-in portal session. The CLI and MCP server handle this for you. Requests only ever see your own tenant's templates: another tenant's template or approval ID returns `404 Not Found`.

Templates are shared by every mailbox, so the writes (create, add a version, publish, review an approval) need a key with a write scope that reaches every mailbox: a mailbox-scoped key gets `403`. Listing, reading and test-rendering are open to any key of the workspace. In MCP, `list_templates` and `render_template` cover the reads; creating and editing templates is CLI or API only.

## Creating a template

**CLI**

```bash title="CLI"
molted templates create \
  --name "Order Confirmation" \
  --slug order-confirmation \
  --type transactional \
  --subject "Your order {{orderId}} has been confirmed" \
  --body "<h1>Order Confirmed</h1><p>Hi {{customerName}}, your order is on its way.</p>" \
  --text "Order Confirmed. Hi {{customerName}}, your order is on its way." \
  --variables '[{"name":"orderId","type":"string","required":true},{"name":"customerName","type":"string","required":true}]' \
  --auto-publish
```

**API**

```bash title="curl"
curl -X POST https://mailbox.molted.email/v1/templates \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "slug": "order-confirmation",
    "name": "Order Confirmation",
    "type": "transactional",
    "content": {
      "subjectTemplate": "Your order {{orderId}} has been confirmed",
      "htmlTemplate": "<h1>Order Confirmed</h1><p>Hi {{customerName}}, your order is on its way.</p>",
      "textTemplate": "Order Confirmed. Hi {{customerName}}, your order is on its way.",
      "variables": [
        { "name": "orderId", "type": "string", "required": true },
        { "name": "customerName", "type": "string", "required": true }
      ]
    },
    "autoPublish": true
  }'
```

### Request body

| Field | Type | Required | Description |
| - | - | - | - |
| `tenantId` | `string` | No | Only on `api.molted.email`, where it is required; `mailbox.molted.email` fills it in from your key. |
| `slug` | `string` | Yes | URL-friendly identifier (e.g. `order-confirmation`). |
| `name` | `string` | Yes | Human-readable template name. |
| `type` | `string` | No | `transactional` or `marketing`. Defaults to `marketing` -- which requires an unsubscribe link to pass lint, and should carry a physical mailing address for CAN-SPAM. The CLI prints a stderr note when `--type` is omitted. |
| `approvalRequired` | `boolean` | No | Whether publishing requires approval. Default `false`. |
| `content` | `object` | No | Initial template content (see below). |
| `autoPublish` | `boolean` | No | If `true` and `content` is provided, publishes immediately after creation. With `approvalRequired`, it starts the approval instead -- see note below. |

With `content`, the response is `{ "template", "version", "publishResult" }` (`publishResult` is `null` without `autoPublish`); without it, the template alone. A slug already used in your workspace is `409`: add a version to that template instead.

**`autoPublish` and `approvalRequired` interaction:** If you set both `autoPublish: true` and `approvalRequired: true`, the template is created with approval required and the publish flow is triggered automatically -- but because approval is required, the result is a `pending_approval` status, not an immediate publish. The version will not go live until it is explicitly approved. If you need immediate publishing, do not set `approvalRequired`.

### Content fields

| Field | Type | Required | Description |
| - | - | - | - |
| `subjectTemplate` | `string` | Yes | Subject line with variable placeholders. |
| `htmlTemplate` | `string` | Yes | HTML body with variable placeholders. |
| `textTemplate` | `string` | No | Plain text fallback body. |
| `variables` | `array` | No | Variable definitions for validation (see schema below). |

Variables use double curly brace syntax: `{{variableName}}` (letters, digits and underscores only; there are no conditionals, loops or filters). A variable left out of the payload uses its `defaultValue`, else renders empty; a `required` one with no value and no default fails the render.

### Variables schema

The `variables` array defines the expected variables for a template. Each entry is an object with:

| Field | Type | Required | Description |
| - | - | - | - |
| `name` | `string` | Yes | Variable name matching the `{{name}}` placeholder in the template. |
| `type` | `string` | Yes | Data type: `string`, `number`, `boolean`, or `date`. |
| `required` | `boolean` | Yes | Whether the variable must be provided in the send payload. |
| `defaultValue` | `any` | No | Fallback value when the variable is not provided. |
| `description` | `string` | No | Human-readable description of the variable's purpose. |

```json title="Example"
[
  { "name": "customerName", "type": "string", "required": true, "description": "Recipient's display name" },
  { "name": "orderId", "type": "string", "required": true },
  { "name": "showPromo", "type": "boolean", "required": false, "defaultValue": false }
]
```

Variables are validated during template linting. If a `{{placeholder}}` in the template body does not have a matching entry in `variables`, linting flags an `undeclared_variable` error. Templates with lint errors are blocked from sending by the policy engine.

To fix an `undeclared_variable` error, add the missing variable to `--variables` when creating the template or when adding a new version:

```bash title="CLI"
molted templates create \
  --name "Welcome" --slug welcome --type transactional \
  --subject "Welcome, {{name}}!" \
  --body "<h1>Hello {{name}}</h1>" \
  --variables '[{"name":"name","type":"string","required":true}]' \
  --auto-publish
```

(`--type transactional` sidesteps the separate `missing_unsubscribe` and `missing_physical_address` lint rules that apply to marketing templates -- see [Lint rules](#lint-rules) below. A marketing template, which is the default when `--type`/`type` is omitted, needs an unsubscribe link in its body as well; the CLI prints a stderr note when it defaults.)

If you omit `--variables` and your template uses `{{placeholders}}`, the template is created but lint fails. At render time:

- If the placeholder name appears in the render payload, the value is substituted from the payload so ad-hoc renders still work. The template still failed lint, so it cannot be sent through the policy engine.
- If the placeholder is missing from the payload too, the render response includes an `errors` entry such as `"Unresolved variable \"name\" is used in the template but not declared and not in the payload"`, and the placeholder is substituted with an empty string. A send without that variable is blocked with reason `template_render_failed`; one that has it gets past rendering and is blocked with `template_lint_failed`.

Always declare your variables with `--variables` so lint passes and the policy engine enforces required fields consistently.

## Listing templates

**CLI**

```bash title="CLI"
molted templates list
```

**API**

```bash title="curl"
curl https://mailbox.molted.email/v1/templates \
  -H "Authorization: Bearer YOUR_API_KEY"
```

Returns an array of templates (most recently updated first), each with its live version's `version` number and `lintPassed`.

## IDs vs slugs

`get`, `render`, `add-version`, and `publish` accept either the template **ID** (UUID) or **slug**. Slugs are scoped to the tenant resolved from your API key. Approval routes take the **approval ID** returned by `publish`.

The `send` command also accepts either form via the `templateId` field. Slugs are the recommended convention for sending because they are human-readable.

To find a template's ID or slug, use `list` and look for the `id` and `slug` fields in the response.

## Getting a template

**CLI**

```bash title="CLI"
molted templates get TEMPLATE_ID
```

**API**

```bash title="curl"
curl "https://mailbox.molted.email/v1/templates/TEMPLATE_ID" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

`TEMPLATE_ID` may be either the UUID or the slug. Slug lookups are scoped to your tenant.

Returns the template with its current version's full content (subject, HTML, text templates, variables, and lint results).

## Versioning

Templates are versioned. Each update creates a new version that must be published before it takes effect.

### Adding a new version

**CLI**

```bash title="CLI"
molted templates add-version TEMPLATE_ID \
  --subject "Updated: Your order {{orderId}}" \
  --body "<h1>Order Update</h1><p>Hi {{customerName}}.</p>" \
  --variables '[{"name":"orderId","type":"string","required":true},{"name":"customerName","type":"string","required":true}]'
```

**API**

```bash title="curl"
curl -X POST "https://mailbox.molted.email/v1/templates/TEMPLATE_ID/versions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "subjectTemplate": "Updated: Your order {{orderId}}",
    "htmlTemplate": "<h1>Order Update</h1><p>Hi {{customerName}}.</p>",
    "variables": [
      { "name": "orderId", "type": "string", "required": true },
      { "name": "customerName", "type": "string", "required": true }
    ]
  }'
```

New versions are automatically linted on creation. The lint results are stored with the version.

### Publishing a version

**CLI**

```bash title="CLI"
molted templates publish TEMPLATE_ID
```

**API**

```bash title="curl"
curl -X POST "https://mailbox.molted.email/v1/templates/TEMPLATE_ID/publish" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "requestedBy": "operator@example.com" }'
```

Publishing makes the template's **latest** version live. It does not check lint: a version with lint errors can be published, and sends through it are then blocked with `template_lint_failed`. The body's `requestedBy` is recorded on an approval (the CLI's `--requested-by` defaults to `cli`).

If the template has `approvalRequired: true`, this creates a pending approval instead of publishing directly:

```json title="Pending approval"
{
  "status": "pending_approval",
  "approvalId": "...",
  "versionId": "..."
}
```

Otherwise it publishes immediately:

```json title="Published"
{
  "status": "published",
  "versionId": "..."
}
```

### Reviewing approvals

**CLI**

```bash title="Approve"
molted templates approve APPROVAL_ID --reviewed-by "admin@example.com" --comment "Looks good"
```

```bash title="Reject"
molted templates reject APPROVAL_ID --reviewed-by "admin@example.com" --reason "Subject too long"
```

**API**

```bash title="curl"
curl -X PATCH "https://mailbox.molted.email/v1/templates/approvals/APPROVAL_ID" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "decision": "approved",
    "comment": "Looks good"
  }'
```

Set `decision` to `approved` or `rejected`. The approval records who decided from your credentials (`user:<id>` for a signed-in person, `key:<id>` for an API key). A `reviewedBy` field in the body is accepted for older clients and ignored.

Reviewing is a human decision: an agent key on an account that enforces the human gate gets `403 human_decision_required` with a `decisionUrl` (kind `template`) for a person to decide in the portal, and `molted templates approve`/`reject` print that response. See [Decisions need a human](https://molted.email/docs/approval-queues.md#decisions-need-a-human). The response is the approval: `id`, `templateVersionId`, `requestedBy`, `status`, `reviewedBy`, `reviewedAt`, `comment`, `createdAt`.

Only a pending approval can be reviewed. Repeating the decision it already has returns it unchanged; the other decision returns `409` with `{ "error": "already_decided", "status": "rejected" }`, so a rejected version can never be published later by approving the same request. Publish again to ask for a new review. Approving an older version than the one that is live, or than one still waiting for review, returns `409` with `{ "error": "superseded" }`, so an old approval can never roll the template back: reject it instead.

In the portal, every pending template approval is a card on Home (`/app`). **Preview** shows the version as written, its `{{variables}}` in place, with its lint results above it. A lint error is a warning, not a block: a person can still approve the version.

A person can also browse every template from **Templates** (`/app/templates`, reachable from ⌘K "Go to"): name, live version, the live version's lint, who last changed it and when, and a "waits for you" badge when a version is pending. Opening a row shows the same preview and lint, with Approve/Reject when a version is waiting. Beyond that one decision a person can only delete a template there (**Delete** on its row, behind a confirm); creating and editing templates stays API-only, through the CLI, MCP or REST.

## Test rendering

Preview how a template renders with sample data:

**CLI**

```bash title="CLI"
molted templates render TEMPLATE_ID --payload '{"customerName":"Jane","orderId":"456"}'
```

**API**

```bash title="curl"
curl -X POST "https://mailbox.molted.email/v1/templates/TEMPLATE_ID/render" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "payload": {
      "customerName": "Jane",
      "orderId": "456"
    }
  }'
```

Returns `{ "subject", "html", "text", "errors", "warnings" }`: the live version rendered with your variables. `payload` is optional on the API (a template with no variables renders without one); the CLI requires `--payload`. In MCP the tool is `render_template` (`template_id`, `payload`).

If the template exists but has no published version (for example, it was created without `--auto-publish`, or its only version is still waiting for approval), `render` returns `422 Unprocessable Entity` with a message pointing at `molted templates publish <id>`. This is distinct from `404 Not Found`, which indicates the ID or slug doesn't exist.

## Deleting a template

Delete a template you no longer need, such as a test one, by UUID or slug:

**CLI**

```bash title="CLI"
molted templates delete welcome-test
```

**API**

```bash title="curl"
curl -X DELETE "https://mailbox.molted.email/v1/templates/TEMPLATE_ID" \
  -H "Authorization: Bearer YOUR_API_KEY"
# → { "deleted": true, "id": "TEMPLATE_ID", "slug": "welcome-test", "rejectedApprovals": 0 }
```

- The slug is free again right away: you can create a new template with the same slug.
- `_default` can't be deleted (`409`).
- A template a step of an `active` or `paused` journey uses can't be deleted (`409`, the message names those journeys). Archive or delete those journeys, or change their send steps to another template, first. A `draft` or `archived` journey doesn't block it, but its step will fail if that journey is activated again.
- Versions waiting for approval are rejected with it.
- A deleted template can't be sent, rendered or read. Emails already sent with it keep their history, including which version went out.

## Template linting

Every version is automatically linted when created. The lint results are stored with the version and determine whether the template can be used for sending.

### Lint rules

| Rule | Severity | Description |
| - | - | - |
| `undeclared_variable` | error | A `{{placeholder}}` is used in the template but not declared in `variables`. Fix: add the variable to `--variables`. System variables (see below) are exempt. |
| `unused_variable` | warning | A variable is declared in `variables` but never referenced in the template. |
| `system_variable_redeclared` | warning | A system variable was passed in `variables[]`. Remove it -- Molted auto-injects it at send time. |
| `spam_phrase` | warning | Subject or body contains a spam-trigger phrase: "act now", "limited time", "buy now", "click here", "free money", "no obligation", "winner", "congratulations", "urgent" or "guaranteed". |
| `insecure_url` | error | The HTML has an `href="http://..."` link. Use `https://` instead. |
| `missing_unsubscribe` | error | Marketing templates must include an unsubscribe link: the check looks for the word "unsubscribe" in the HTML. Not required for transactional templates. |
| `missing_physical_address` | warning | Marketing templates should include a physical mailing address (CAN-SPAM): the HTML needs `{{physical_address}}` (filled with the workspace's address at send time), "mailing address" or "postal address". |

Templates with any `error`-level lint result are blocked from sending by the policy engine with reason `template_lint_failed`. Warning-level results do not block sends.

### System variables

Variables auto-injected by Molted at send time. Use them in templates **without declaring them in `variables[]`**.

| Variable | Description |
| - | - |
| `{{unsubscribe_url}}` | Per-recipient unsubscribe link. Use this in the marketing-template unsubscribe `<a href>` -- it satisfies `missing_unsubscribe` without tripping `undeclared_variable`. The namespaced `{{molted:unsubscribe_url}}` spelling works the same way and is preferred by agent senders that build the body themselves. Both are filled in on every send path -- request-send, batch, approved (human-reviewed) sends, list broadcasts, journey `send` steps and follow-ups -- with RFC 8058 `List-Unsubscribe` / `List-Unsubscribe-Post` headers attached whenever the link is used. |
| `{{physical_address}}` | Filled with the workspace's physical mailing address (the `physicalAddress` setting) on every send path -- request-send, batch, approved sends, list broadcasts, journey `send` steps and follow-ups -- for any template type, HTML-escaped in the HTML part. The workspace setting always wins: a `physical_address` value in the payload is ignored. It satisfies the `missing_physical_address` lint rule. A marketing email whose HTML or text part doesn't already carry the address gets it appended to that part as a footer, so a footer such as `Acme · {{physical_address}} · <a href="{{unsubscribe_url}}">Unsubscribe</a>` shows the address once, where you put it. A marketing template with no address on file blocks the send with reason `missing_physical_address` rather than sending without it; any other template renders the placeholder empty. |

`templates render` fills `{{physical_address}}` from the workspace the same way a send does, and surfaces a `warnings` entry (`unfilled_system_variable`) when a system variable has no value -- for `{{physical_address}}`, when the workspace has no address set. The preview renders it as an empty string but says so instead of silently showing a blank. The `dry_run` / `simulate` preview renders the content the send would deliver instead: the unsubscribe link is a placeholder that never resolves (warning `unsubscribe_link_placeholder`), since a dry run mints no real link, and a template using `{{physical_address}}` while the workspace has none set carries the warning `physical_address_unset`.

## Default template

Every new tenant is provisioned with a `_default` transactional template. This template is used when you send without specifying a `templateId`.

Sends using a `templateId` value that does not match any template slug or ID, or a template with no published version, are blocked with reason `template_not_found`. A template with `approvalRequired` whose live version has not been approved blocks with `template_not_approved`.

If a template exists but rendering fails (for example, a required variable is missing from the send payload), the send is blocked with reason `template_render_failed` instead of sending a partially-populated email. The caller should re-submit with the missing variables in the payload.
