> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Email

> How a GatoJS app sends transactional email through SMTP or Resend, previews it locally in Mailpit, and renders React Email templates for invitations and password resets.

A GatoJS app sends three kinds of transactional email: password reset, welcome with a set-password link, and organization invitation. All three go through one private function, `sendTransactionalEmail` in `src/shared/lib/mailer.ts`, which picks the transport based on your environment variables.

## Choosing the transport

```ts src/shared/lib/mailer.ts theme={null}
const smtpUrl = env.SMTP_URL;
const apiKey = env.RESEND_API_KEY;
if (!smtpUrl && !apiKey) {
  logger.info("[MAILER] SMTP_URL and RESEND_API_KEY not set, email not sent", { to, subject });
  return { data: null };
}
// ...
const delivery = smtpUrl
  ? await deliverViaSmtp(smtpUrl, message)
  : await deliverViaResend(apiKey as string, message);
```

| `SMTP_URL` | `RESEND_API_KEY` | Transport | Result on success |
| - | - | - | - |
| set | any | SMTP through nodemailer. The template is rendered to HTML with `@react-email/render`. | `{ data: { id: <messageId> } }` |
| empty | set | Resend API (`POST https://api.resend.com/emails`). The Resend SDK renders the React template. | `{ data }` from Resend |
| empty | empty | Nothing is sent. The mailer logs `[MAILER] SMTP_URL and RESEND_API_KEY not set, email not sent` with `to` and `subject`. | `{ data: null }` |

An empty value counts as unset, because the env schema turns blank strings into `undefined`.

> [!NOTE]
>
> **`SMTP_URL` wins over Resend, also in production.** If both are set, mail goes through SMTP. In production, leave `SMTP_URL` empty unless you deliberately send through your own SMTP server.

Behavior shared by both transports:

* **Failures don't throw.** An exception (for example `ECONNREFUSED` when Mailpit isn't running) or an error returned by Resend is logged with `logger.error` and returned as `{ error: <message> }`.
* **Addresses are masked in logs.** `maskEmail` keeps the first two characters of the local part: `jan.kowalski@example.com` becomes `ja**********@example.com`.
* **HTML only.** Messages have no plain-text part. The sender is `EMAIL_FROM`.
* **Clients are created once per process**, and `env` is read once. Restart the server after changing `SMTP_URL` or `RESEND_API_KEY`.

## Environment variables

**EMAIL\_FROM** `string` *required*

Sender address, for example `Acme <noreply@acme.com>`. Required in every environment. The format is not validated, so check it against the domain you verified in your mail provider.

**RESEND\_API\_KEY** `string`

Resend API key. Optional in development; **required when `NODE_ENV=production`**, even if `SMTP_URL` is set. Without it the server refuses to start with `RESEND_API_KEY: wymagana w produkcji` ("required in production").

**SMTP\_URL** `string`

SMTP connection URL for nodemailer, for example `smtp://localhost:1025` or `smtps://user:pass@smtp.example.com:465`. Takes precedence over Resend. The format is not validated: a malformed URL passes startup and fails on the first send.

See [Environment variables](https://docs.gatojs.com/configuration/environment-variables.md) for the full reference.

## Local preview with Mailpit

`docker-compose.yml` runs [Mailpit](https://mailpit.axllent.org) as the `mail` service, and `.env.example` sets `SMTP_URL=smtp://localhost:1025`. Every email the app sends locally lands in Mailpit, with the web UI at [http://localhost:8025](http://localhost:8025).

```bash theme={null}
docker compose up -d
```

If the ports are taken, change `MAILPIT_UI_PORT` and `MAILPIT_SMTP_PORT` (defaults `8025` and `1025`) and update `SMTP_URL` in `.env` to match.

There is no separate template preview server. To see a template after a change, trigger the action that sends it:

| Email | How to trigger it |
| - | - |
| Password reset | The "forgot password" link on the sign-in page. |
| Welcome / set password | **Invite user** on the **Users** page, signed in as a global `admin` or `superadmin`. |
| Organization invitation | The invite form on the **Members** page with `MULTI_ORG=true`, signed in as a global `user` who is `owner` or `admin` of the organization. |

The end-to-end tests read mail through the Mailpit API as well (see [Testing](https://docs.gatojs.com/guides/testing.md)).

## Templates

Templates are React components built with [React Email](https://react.email), in `src/app/emails/`. The shared `EmailLayout` (`src/app/emails/components/email-layout.tsx`) provides the inbox preview text, a header and footer with `project.name`, and Tailwind styles.

| Function in `mailer.ts` | Template | Subject | Sent by | Link |
| - | - | - | - | - |
| `sendPasswordResetEmail` | `PasswordResetEmail` | "Zresetuj hasło" | better-auth `sendResetPassword` | The reset URL from better-auth, valid for 48 hours. |
| `sendWelcomeSetPasswordEmail` | `WelcomeSetPasswordEmail` | "Witamy w `<project name>`" | The users feature's `inviteUserCommand` | A set-password URL, also valid for 48 hours. |
| `sendOrganizationInvitationEmail` | `OrganizationInvitationEmail` | "Zaproszenie do `<organization>`" | better-auth organization plugin `sendInvitationEmail` | `<APP_URL>/accept-invitation/<id>` |

Links are built from `APP_URL`, so a wrong `APP_URL` in production sends people to the wrong host.

> [!WARNING]
>
> Templates and subjects are written in Polish and don't receive a locale, so English-speaking users get the same Polish email. To localize them, edit the templates and subjects in the core files. See [Translations](https://docs.gatojs.com/guides/i18n.md#text-outside-translation-files).

### Editing a template

Templates are ordinary components. Change the copy or layout directly:

```tsx src/app/emails/password-reset-email.tsx theme={null}
export function PasswordResetEmail({ resetUrl }: PasswordResetEmailProps) {
  return (
    <EmailLayout preview="Zresetuj hasło">
      <Text className="text-base leading-6 text-[#525f7f]">
        Otrzymaliśmy prośbę o zresetowanie hasła do Twojego konta.
      </Text>
      <Button href={resetUrl}>Zresetuj hasło</Button>
    </EmailLayout>
  );
}
```

### Adding a new kind of email

`sendTransactionalEmail` is not exported. A new email needs a template in `src/app/emails/` and a new exported function in `mailer.ts`, built the same way as the existing three. Both files belong to the core module, so this is a local change to the core in your project; a kit module has no way to send its own email without editing the core.

## How results are handled

* **Password reset and organization invitation** are sent by better-auth, which ignores the result. The user sees success even when the email didn't go out; the failure appears only in logs.
* **Welcome email**: on `{ error }`, `inviteUserCommand` still returns success but with `warning: "mail-failed"`, and the invite dialog shows a warning asking you to send a password reset instead. With neither transport configured the result is `{ data: null }`, not an error, so the invite succeeds without a warning even though nothing was sent.

## Production checklist

**1. Verify a sender domain**

Add and verify your domain in Resend (or your SMTP provider), then set `EMAIL_FROM` to an address on it.

**2. Set the API key**

Set `RESEND_API_KEY` and leave `SMTP_URL` unset.

**3. Set up log export**

Set `OTEL_EXPORTER_OTLP_ENDPOINT`. In production the logger doesn't write to the console, so without an OTLP endpoint failed sends leave no trace. See [Logging and observability](https://docs.gatojs.com/configuration/logging-and-observability.md).

**4. Send a test email**

After deploying, request a password reset for your own account and confirm it arrives.

## Related

> [card] [Auth and roles](https://docs.gatojs.com/concepts/auth-and-roles.md)
>
> Invitations, sign-up and password flows that trigger these emails.

> [card] [Deploy on Railway](https://docs.gatojs.com/deployment/railway.md)
>
> Production variables, including mail settings.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.