> For the complete documentation index, see [llms.txt](https://docs.thewalletcrew.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/email-engine.md).

# Email engine

Send the platform's emails through the brand's own email or marketing automation service, with runtime.scriptable.emailEngine and the script email provider.

The Wallet Crew sends emails at a few points of the customer journey: the identity-confirmation email of an enrolment and the emails of a registration flow's `mail` steps. By default they go through an email provider configured in the admin console. The script email provider hands each of these emails to a tenant script instead, which can forward it to the brand's own sending service, trigger a journey in a marketing automation platform, or call a CRM endpoint that sends the email itself. This page is the reference for `runtime.scriptable.emailEngine`.

The script email provider is the right tool when emails must leave from the brand's own infrastructure or be orchestrated by its marketing tools. It replaces the provider for every email the tenant sends; choosing which template the identity-confirmation email uses, or skipping it, is a narrower need covered by the [email challenge template](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/email-challenge-template.md).

<details>

<summary><strong>Real-world examples</strong></summary>

* A brand triggers a transactional journey in its marketing automation platform, passing the template name and the customer data, and lets that platform render and send the email.
* A retailer renders the email with The Wallet Crew templates, then sends the subject and body through its own transactional email API.
* A CRM sends the welcome email itself when it receives an event named after the template.

</details>

## Registration

The script registers `runtime.scriptable.emailEngine`, and `server/emails.yml` selects the script provider:

```yaml
provider:
  type: script
```

The email settings of the admin console can make this choice too: selecting the script provider stores the script in `server/scripts/email.provider.js` and offers a starter implementation to begin from. The minimal skeleton is:

```js
export default function (context) {
  context.register('runtime.scriptable.emailEngine', {
    SendEmail: async (recipient, emailTemplate, data, cultures, buildEmail) => {}
  });
}
```

## When it runs

`SendEmail` runs each time the platform sends an email for the tenant while the script provider is selected, inside the request that sends it: during an enrolment request for the identity-confirmation email, and at the position of a `mail` step in a registration flow. The request waits for the script, so a slow sending service makes the enrolment slower.

## Handlers

| Method      | Parameters                                                     | Returns               | Required           |
| ----------- | -------------------------------------------------------------- | --------------------- | ------------------ |
| `SendEmail` | `recipient`, `emailTemplate`, `data`, `cultures`, `buildEmail` | nothing, or a promise | No-op when missing |

The parameters are:

* `recipient`: the email address to send to.
* `emailTemplate`: the name of the email template, as configured on the challenger (`templateName`) or the flow step (`mailTemplate`). The editor typings show this parameter as `mailTemplate`; parameters are positional, so the name is free.
* `data`: the values the template renders from, keyed like the account (`data.email`, `data.firstName`, `data['id.crm.customerId']`). The identity-confirmation email also carries `data.authenticationToken`, the token of the link that continues the enrolment.
* `cultures`: the names of the tenant's languages, such as `['en', 'fr']`.
* `buildEmail`: an async function. `await buildEmail(templateName)` renders a template with `data` and returns `{ Subject, Body }` (PascalCase), the subject and the body, as The Wallet Crew would have sent them.

Changes the script makes to `data` before calling `buildEmail` are seen by the rendering, because both share the same object.

## Return value

The return value is ignored. The email counts as sent when `SendEmail` completes without error.

## Errors and edge cases

* **SendEmail throws or its promise rejects**: the send fails, and so does the operation that sent the email: the enrolment request returns an error, or the registration flow stops at its `mail` step.
* **The script provider is selected but no script registers the key**: every send fails with an error saying that the endpoint is not registered.
* **SendEmail is missing** from the registered object: the call does nothing and **no email is sent**, without any error.
* **Several files register the key**: the last registered wins, and the load order of files is not defined.

{% hint style="warning" %}
`data.authenticationToken` lets whoever holds it continue the enrolment as the customer. It must only be sent to the recipient, never written to logs, and only passed to a third-party platform that is trusted to send it.
{% endhint %}

## Example

The script renders the email with The Wallet Crew templates and sends it through a transactional email API. The API is called with `ThrowOnError: false` so that its error message can be logged before failing the send.

```js
import { getSecret } from 'twc/secrets';

const SEND_URL = 'https://mail.example.com/v3/send';
const FROM = { email: 'hello@example.com', name: 'Example Store' };

async function sendEmail(recipient, emailTemplate, data, cultures, buildEmail) {
  const { Subject, Body } = await buildEmail(emailTemplate);
  const apiKey = await getSecret('MAIL-API-KEY');

  const response = await fetch(SEND_URL, {
    Method: 'POST',
    Headers: { Authorization: `Bearer ${apiKey}` },
    Body: {
      from: FROM,
      to: [{ email: recipient }],
      subject: Subject,
      html: Body,
      tags: ['wallet', emailTemplate]
    },
    ThrowOnError: false
  });

  if (response.StatusCode < 200 || response.StatusCode >= 300) {
    console.error(`Email ${emailTemplate} was refused by the sending service: ${response.StatusCode}`);
    throw new Error(`Email ${emailTemplate} could not be sent`);
  }
}

export default function (context) {
  context.register('runtime.scriptable.emailEngine', {
    SendEmail: sendEmail
  });
}
```

A marketing automation variant skips `buildEmail` and posts `emailTemplate`, `recipient` and the useful keys of `data` to the platform's event or journey endpoint, which then owns the content of the email.

{% hint style="info" %}
`fetch` retries a POST on transient failures. When the sending service accepts an idempotency key, sending one built from the recipient and the template prevents a duplicate email after a retry. See [fetch](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md).
{% endhint %}

## Checking the result

Submitting a test enrolment with a mailbox the team controls exercises the identity-confirmation email; a flow with a `mail` step exercises the other path. When nothing arrives, the platform's monitoring shows whether `SendEmail` threw, and the sending service's own logs show whether it received the call.

## Common pitfalls

* A sending error is caught and only logged: the customer never receives the email and the enrolment still reports success.

## FAQ

<details>

<summary><strong>Can the script choose the language of the email?</strong></summary>

`cultures` lists the tenant's languages, and `data` holds the account values the enrolment carried. A script that keeps one template per language picks it from these values and renders it with `buildEmail`, or passes the language on to the sending platform.

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/email-engine.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
