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

# Email

> Send branded HTML email from Start server code with Email.send from zitejs/email, and write HTML that renders well in every inbox.

Server code sends email with `Email.send` from `zitejs/email`. You write the content as HTML, and the
platform sanitizes it, frames it in the app's brand kit, and generates a plain-text part. Use it for
confirmations, receipts, notifications and digests.

## Set up the email integration

Sending always goes through the `email` integration. Add it to the workspace root `zite.config.json`, with
Zite's own sender as the provider:

```json theme={"system"}
{
  "integrations": {
    "email": { "type": "email", "provider": "zite_email" }
  }
}
```

Zite's sender needs no account and no connect step. To send from your own address instead, connect the
email integration with `setup_integration` and pick Gmail or Outlook as the provider. The standalone `gmail`
and `outlook` integrations are for reading and managing a mailbox, not for sending.

`zitejs/email` is generated once the app has an `email` settings entry in its own `zite.config.json`. An
empty entry is enough:

```json theme={"system"}
{
  "integrationSettings": {
    "email": {}
  }
}
```

The entry also takes `fromName`, `fromEmail` and `replyTo`. See
[App config](https://developers.zite.com/framework/app-config.md#integrations-and-integrationsettings).

## Send an email

`Email.send({ to, subject, html })` sends an email written in HTML. Call it from a server function's handler
or a `*.server.ts` helper, never from a page.

```typescript theme={"system"}
import { Email } from 'zitejs/email';

const result = await Email.send({
  to: customer.email,
  subject: 'Order #1042 shipped',
  html: '<p style="margin:0 0 16px;">Your order is on its way.</p>',
  lang: 'en',
});
// result: { success: boolean; messageId: string; warnings?: string[] }
```

| Option | Type | What it does |
| - | - | - |
| `to` | `string \| string[]` | Recipient addresses. Take them from your data, never straight from a function's input (see [rule 10](#rules-and-why)) |
| `subject` | `string` | The subject line |
| `html` | `string` | The email's content, as HTML |
| `text` | `string` | The plain-text part. Generated from `html` when omitted |
| `layout` | `'formatted' \| 'plain'` | How the content is framed. Defaults to `'formatted'` |
| `background` | `string` | Hex colour around the card, or behind a plain email's text. Defaults to the brand kit's |
| `cardBackground` | `string` | Hex colour of the card in a formatted email. Defaults to the brand kit's |
| `replyTo` | `string` | Where replies to this email go |
| `lang` | `string` | The language the email is written in, such as `'en'`, `'es'` or `'pt-BR'` |
| `cc`, `bcc` | `string[]` | Copy recipients |
| `attachments` | `{ filename, url, contentType? }[]` | Files attached to the email, each fetched from its URL at send time |
| `logo` | `{ url, width?, height? }` | Replaces the brand kit's logo for this email |
| `direction` | `'ltr' \| 'rtl'` | Text direction, `'rtl'` for right-to-left languages |

Read the result: `warnings` lists problems that didn't stop the send, such as a hand-built button or an
email large enough for Gmail to clip. Fix them before you ship the email.

## What happens to your HTML at send time

1. **It's sanitized.** Scripts, forms, inputs, iframes, video, SVG, event handlers, `javascript:` links
   and `data:` images are removed.
2. **Rules in any `<style>` block are inlined** into your markup only, so a rule like `td { padding: 8px }`
   never touches the frame around it. `@media` rules stay in the head.
3. **`<a class="button" href="...">Label</a>` becomes a button** that keeps its padding and colour in
   Outlook.
4. **It's framed according to `layout`:**
   * `'formatted'` (the default): a content card on a tinted background, under the logo, in the app's brand
     kit colours, font and button radius. Without a brand kit the frame is neutral. This is the right choice
     for nearly every app email.
   * `'plain'`: no card and no logo, like a note typed by a person. Good for internal notifications and
     personal follow-ups.
5. **A plain-text part is generated** from it, with links written out. Pass `text` only when the plain
   version needs different wording.

Because the frame carries the brand, don't hardcode the brand's colours or font for the card, background or
buttons: they follow the brand kit when it changes. Use colour inside the content for meaning (a status
badge, a total row), not to restate the brand.

For a different background or card colour, pass it to `Email.send` rather than painting it in your HTML.
`background` is the colour around the card (or behind a plain email's text, as a sheet the width of the
column), and `cardBackground` is the card's. Both are hex, both default to the brand kit, and text on them
is kept readable. A coloured box drawn inside the card instead leaves the brand's colours around it, so the
email shows three backgrounds.

## Rules, and why

1. **Lay out with tables.** Outlook on Windows renders email with Word: no flexbox, grid, float or
   positioning, and `max-width` on a `<div>` is ignored. Columns are `<td>`s in a
   `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">`. Plain `<p>`,
   `<h1>` to `<h3>`, `<ul>` and `<div>` are fine for text.
2. **Space with padding on `<td>`**, not margins on `<div>`s, which Outlook drops. Reset text margins
   inline, for example `<p style="margin:0 0 16px;">`. A paragraph you leave without one gets 16px below
   it.
3. **Your HTML is the content, not the page.** Don't wrap it in an outer table, padding, a fixed or
   centred width, or a background: the frame sets the width and spacing for each layout. A plain email has
   none, so it reads like one someone typed. A plain email with a `background` gets the sheet's padding,
   and a formatted one gets the card's. A wrapper of your own adds a second margin, which makes a plain note
   look generated and puts a box inside the card. Inside, the content is about 560px wide in the card and up
   to 640px in a plain email, so size images and columns as fractions of `width="100%"`.
4. **Colours are hex** (`#0f766e`). Gmail drops CSS variables, and Outlook ignores `rgba()`, `hsl()` and
   `oklch()`. On a coloured table cell, set both `bgcolor="#f1f5f9"` and `background-color`: the attribute
   is what Outlook reads.
5. **Text.** Use font sizes in px (body 16px, 14px at the smallest for fine print, headings 20 to 28px),
   and `line-height` in px or unitless. Leave `font-family` and the text colour to the frame: it picks a
   colour that reads on the brand kit's card, light or dark, and a hardcoded dark grey disappears on a dark
   brand. Where you do colour text, also set the background behind it (a badge, a panel), so it reads on any
   card.
6. **Images** take absolute `https://` URLs, a `width` attribute, `alt` text, and
   `style="display:block;max-width:100%;height:auto;border:0;"`. Many clients block images until the reader
   allows them, so nothing important may live only in an image: no text baked into pictures, and no
   image-only emails (spam filters score those badly too). Use an `<img>` rather than `background-image`,
   which Outlook ignores.
7. **Buttons** are `<a class="button" href="https://...">Label</a>`, on their own line rather than inside a
   `<p>`. Don't build your own from a padded link: `class="button"` is what gives it the Outlook version
   and the brand's colour. A `class="button"` link takes the brand's primary colour. An inline
   `background-color`, `color` or `border-radius` overrides it, and other inline styles on it are dropped.
   Align it with `text-align` on the element around it. A link you pad and fill yourself is sent as written,
   so Outlook desktop shows it as a thin coloured strip, and `Email.send` returns a warning naming it. Give
   an email one primary action.
8. **Links** are absolute: `https://`, `mailto:` or `tel:`. Build app links from
   `process.env.ZITE_APP_URL`. Link text says where it goes ("View your booking"), never "click here", and
   a link inside a sentence keeps its underline so it doesn't rely on colour alone.
9. **Escape every interpolated value** with a small `escapeHtml` helper that encodes `&`, `<`, `>`, `"`
   and `'`. That includes names, notes, and anything a user typed. Unescaped input breaks the layout and
   lets a user inject links into an email sent from the app. URLs from data go through `escapeHtml` too.
10. **Recipients come from your data.** Anyone who can reach a server function can call it with any input.
    A function that sends to an address, or with wording, taken straight from its input lets them use the
    app to email anyone anything. Take an id, load the record, and send to the address stored on it, or to
    the signed-in user.
11. **Replies.** Zite's sender sends from a no-reply address, so replies go nowhere unless a reply-to is
    set. With Gmail, Outlook or SMTP, replies come back to that mailbox. When an email invites a reply (a
    booking, an order, a support question) and the app uses Zite's sender, decide where replies should go.
    An address for every email from the app goes in the email integration's `replyTo` setting (the
    **Reply-to** field beside **From name** in its settings). Pass `replyTo` to `Email.send` when it differs
    per email, such as the staff member who owns a booking.
12. **Numbers and dates.** Coerce with `Number(...)` and check `Number.isFinite` before formatting. Format
    money with `Intl.NumberFormat` and dates with `Intl.DateTimeFormat`, passing the `timeZone`
    explicitly. Server code runs in UTC, so a bare `toLocaleString()` shows the wrong day near midnight.
13. **Mobile.** Most email is read on phones, and narrow clients shrink a 600px table to fit. Keep to two
    columns at most. To stack columns on small screens, give each column `<td>` a class and add
    `@media only screen and (max-width: 600px) { .stack { display: block !important; width: 100% !important; } }`
    in a `<style>` block. Outlook desktop ignores `@media` and keeps the columns, so they must read well side
    by side too.
14. **Preview text.** The inbox shows the first text of the email next to the subject. To choose it, start
    the HTML with `<div style="display:none;max-height:0;overflow:hidden;">One line summary</div>`. It's
    left out of the plain-text part.
15. **Dark mode.** Gmail's iPhone and Android apps and Outlook (Windows, Outlook.com and its phone apps)
    may invert light backgrounds and dark text. Prefer clear contrast over subtle greys, and don't put dark
    text directly on a transparent image.
16. **Size.** Gmail clips emails over 102 KB behind "View entire message". `Email.send` returns a warning
    from about 90 KB, since Gmail measures after encoding. For long lists (hundreds of rows), show a summary
    and the first few items, and link to the app for the rest.
17. **Subject.** Keep it specific and under about 60 characters, for example "Order #1042 shipped" rather
    than "Update". Write in plain words: ALL CAPS and many exclamation marks read as spam.
18. **Language.** Pass `lang` on every send with the language the email is written in (`'en'`, `'es'`,
    `'pt-BR'`). Without it, Gmail and other webmail give the content no language, so screen readers and
    translation have to guess.

## Example: booking confirmation

The server function takes only an id. The recipient and every value in the email come from the database.

```typescript theme={"system"}
// apps/<app>/src/lib/bookings.functions.ts
import { signedInFn } from 'zitejs/start';
import { zite } from 'zitejs/db';
import { Email } from 'zitejs/email';
import { z } from 'zod';

export const sendBookingConfirmation = signedInFn({
  method: 'POST',
  description: 'Emails the customer a confirmation of their booking',
})
  .validator(z.object({ bookingId: z.string() }))
  .handler(async ({ data }) => {
    const booking = await zite.bookings.findOne({ id: data.bookingId });
    if (!booking) return { sent: false };

    const escapeHtml = (value: unknown) =>
      String(value ?? '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
    const price = Number(booking.price);
    const startsAt = new Date(booking.startsAt);

    const details = [
      ['Service', escapeHtml(booking.service)],
      [
        'When',
        Number.isNaN(startsAt.getTime())
          ? 'To be confirmed'
          : new Intl.DateTimeFormat('en-US', {
              dateStyle: 'full',
              timeStyle: 'short',
              timeZone: 'America/New_York',
            }).format(startsAt),
      ],
      [
        'Price',
        new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(
          Number.isFinite(price) ? price : 0,
        ),
      ],
    ];
    const rows = details
      .map(
        ([label, value]) => `<tr>
        <td style="padding:10px 0;border-bottom:1px solid #e5e7eb;font-size:14px;">${label}</td>
        <td align="right" style="padding:10px 0;border-bottom:1px solid #e5e7eb;">${value}</td>
      </tr>`,
      )
      .join('');

    const bookingUrl = `${process.env.ZITE_APP_URL}/bookings/${encodeURIComponent(booking.id)}`;

    const result = await Email.send({
      to: booking.customerEmail,
      subject: 'Your booking is confirmed',
      html: `
        <div style="display:none;max-height:0;overflow:hidden;">See you soon. Your booking details are inside.</div>
        <h1 style="margin:0 0 8px;font-size:22px;">You're booked, ${escapeHtml(booking.customerName)}</h1>
        <p style="margin:0 0 24px;">Here are the details. You can change or cancel it from your booking page.</p>
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
          ${rows}
        </table>
        <div style="text-align:center;padding:24px 0 8px;">
          <a class="button" href="${escapeHtml(bookingUrl)}">View your booking</a>
        </div>
      `,
    });

    return { sent: result.success };
  });
```

## Patterns

These building blocks follow the rules above. They draw lines rather than fill boxes, so the frame's text
colour reads on a light or a dark card.

**Stats row:** up to three figures side by side, stacked on phones with the `.stack` rule from rule 13.

```html theme={"system"}
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
  <tr>
    <td class="stack" width="33%" align="center" style="padding:16px 8px;border:1px solid #e5e7eb;">
      <div style="font-size:28px;line-height:34px;font-weight:700;">128</div>
      <div style="font-size:13px;line-height:18px;">Orders</div>
    </td>
    <!-- one <td> like it per figure -->
  </tr>
</table>
```

**Feature list:** a marker column and a text column, one row each.

```html theme={"system"}
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
  <tr>
    <td width="28" valign="top" style="padding:0 0 16px;font-size:16px;line-height:22px;font-weight:700;">✓</td>
    <td valign="top" style="padding:0 0 16px;">
      <p style="margin:0;font-weight:700;">Shared calendars</p>
      <p style="margin:4px 0 0;">Everyone sees the same schedule.</p>
    </td>
  </tr>
</table>
```

**Quote:** a rule down one side. Use `border-right` in a right-to-left email.

```html theme={"system"}
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
  <tr>
    <td style="padding:4px 0 4px 16px;border-left:3px solid #d1d5db;">
      <p style="margin:0 0 8px;font-size:16px;line-height:24px;font-style:italic;">"Setup took ten minutes."</p>
      <p style="margin:0;font-size:13px;">Dana Ruiz, Northwind</p>
    </td>
  </tr>
</table>
```

**Receipt:** line items, then a total under a heavier rule. Amounts align right and never wrap, so a long
item name can't split a price across two lines.

```html theme={"system"}
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
  <tr>
    <td style="padding:8px 0;border-bottom:1px solid #e5e7eb;">2 × Yoga class</td>
    <td align="right" style="padding:8px 0 8px 16px;border-bottom:1px solid #e5e7eb;white-space:nowrap;">$40.00</td>
  </tr>
  <tr>
    <td style="padding:12px 0 0;border-top:2px solid #9ca3af;font-weight:700;">Total</td>
    <td align="right" style="padding:12px 0 0 16px;border-top:2px solid #9ca3af;font-weight:700;white-space:nowrap;">$40.00</td>
  </tr>
</table>
```

## Older emails that use `body`

Emails written before HTML support pass `body`, an array of blocks, instead of `html`. They keep working,
so leave them as they are. To change one, rewrite its blocks as HTML following the rules above: a button
block becomes `<a class="button">`, and a spacer becomes padding.

Keep `logo`, `direction`, `attachments`, `cc`, `bcc` and `replyTo` as they were. A `logo` passed to
`Email.send` replaces the brand kit's logo, so drop it when it's the brand logo, and the email follows the
brand kit.

## Check your work

Send a test to your own address to see the email in a real inbox. Read `Email.send`'s result, and fix
anything in its `warnings` before you finish.


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