# Email configuration

## Configure Vite

Email is off until you turn it on:

### Nuxt

```ts [nuxt.config.ts]
import { env } from 'vite-hub/env'

export default defineNuxtConfig({
  modules: ['vite-hub/nuxt'],
  vitehub: {
    email: {
      driver: 'resend',
      options: { apiKey: env({ secret: true, source: env.source('RESEND_API_KEY') }) },
    },
  },
})
```

### Nitro

```ts [vite.config.ts]
import { vitehub } from 'vite-hub'
import { env } from 'vite-hub/env'
import { defineConfig } from 'vite'
import { nitro } from 'nitro/vite'

export default defineConfig({
  plugins: [vitehub({
    email: {
      driver: 'resend',
      options: { apiKey: env({ secret: true, source: env.source('RESEND_API_KEY') }) },
    },
  }), nitro()],
})
```

### Vite

```ts [vite.config.ts]
import { vitehub } from 'vite-hub'
import { env } from 'vite-hub/env'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [vitehub({
    email: {
      driver: 'resend',
      options: { apiKey: env({ secret: true, source: env.source('RESEND_API_KEY') }) },
    },
  })],
})
```

| Option | Type | Default | Behavior |
| --- | --- | --- | --- |
| `driver` | `'resend' \| 'smtp' \| 'cloudflare' \| 'log' \| './path'` | Required | Picks a built-in Email driver, or a [driver module](https://vitehub.dev/docs/email/configure#configure-another-provider) that starts with `./` or `../`. `log` prints each message and sends nothing. |
| `options` | `EnvRuntimeConfigOptions` | `{}` | Plain non-secret values and `env()` declarations. The server reads `env()` sources on every send. Plain values and non-secret defaults go into the build output. A default on a secret is rejected. |
| `remote` | `boolean` | `false` | `true` makes `vite dev` send real email through the provider. Else a dev send stays in the [development outbox](https://vitehub.dev/docs/email/hosts#development-outbox). Builds ignore it. |
| `outbox` | `false \| { limit?: number }` | `{ limit: 50 }` | Sets up the [development outbox](https://vitehub.dev/docs/email/hosts#development-outbox) in `vite dev`. `false` needs `remote: true`, except with `log`. Never in build output. |

No `email`, or `email: false`, keeps Email off.

## Start with `email: true`

`email: true` works on every host. It picks the default driver of the host:

| Host | `vite dev` | Production build |
| --- | --- | --- |
| `cloudflare` | `cloudflare` | `cloudflare`, with an `EMAIL` `send_email` Worker binding |
| Every other host | `log`, in the [development outbox](https://vitehub.dev/docs/email/hosts#development-outbox) | Fails with [`VITE_HUB_R0089`](https://vitehub.dev/docs/development/diagnostics/vite_hub_r0089) |

Only Cloudflare has an Email provider of its own. On other hosts, set `driver` before you build, such as `driver: 'resend'` or [`driver: 'smtp'`](https://vitehub.dev/docs/email/configure#send-over-smtp). Set `driver: 'log'` to build an app that sends no email.

## Run without a provider

Set `driver: 'log'` when a build has no Email provider, for example a self-hosted copy of your app. It works on every host and in production. `email.send()` prints each message with `console.info` and returns `{ driver: 'log', id }`. It sends nothing. The log keeps the message body, so links in it, such as sign-in links, are in the server log.

### Nuxt

```ts [nuxt.config.ts]
import { env } from 'vite-hub/env'

const resend = {
  driver: 'resend' as const,
  options: { apiKey: env({ secret: true, source: env.source('RESEND_API_KEY') }) },
}

export default defineNuxtConfig({
  modules: ['vite-hub/nuxt'],
  vitehub: {
    // Pick the driver when you build. The API key stays a runtime secret.
    email: process.env.EMAIL_PROVIDER === 'resend' ? resend : { driver: 'log' },
  },
})
```

### Nitro

```ts [vite.config.ts]
import { vitehub } from 'vite-hub'
import { env } from 'vite-hub/env'
import { defineConfig } from 'vite'
import { nitro } from 'nitro/vite'

const resend = {
  driver: 'resend' as const,
  options: { apiKey: env({ secret: true, source: env.source('RESEND_API_KEY') }) },
}

export default defineConfig({
  plugins: [vitehub({ email: process.env.EMAIL_PROVIDER === 'resend' ? resend : { driver: 'log' } }), nitro()],
})
```

### Vite

```ts [vite.config.ts]
import { vitehub } from 'vite-hub'
import { env } from 'vite-hub/env'
import { defineConfig } from 'vite'

const resend = {
  driver: 'resend' as const,
  options: { apiKey: env({ secret: true, source: env.source('RESEND_API_KEY') }) },
}

export default defineConfig({
  plugins: [vitehub({ email: process.env.EMAIL_PROVIDER === 'resend' ? resend : { driver: 'log' } })],
})
```

Read `email.canSend` in server code to tell if a message reaches a mailbox. It is `false` with the `log` driver and without `email`. Use it to skip email verification, or to show a link on the page:

```ts [server/api/invite.post.ts]
import { defineEventHandler } from 'h3'
import { email } from 'vite-hub/email'

export default defineEventHandler(async () => {
  const link = 'https://example.com/invite/123'
  if (!email.canSend) return { link }
  const [error] = await email.send({ from: 'team@example.com', to: 'ada@example.com', subject: 'Join the team', text: link })
  if (error) throw error
  return { sent: true }
})
```

`email.canSend` follows the configured driver. The [development outbox](https://vitehub.dev/docs/email/hosts#development-outbox) of `vite dev` does not change it.

ViteHub writes the driver name, plain options, and `env()` declarations into a generated server-only module. A credential from an `env()` source without a default stays in the runtime environment.

## Send over SMTP

The `smtp` driver sends each message to an SMTP server with [Nodemailer](https://nodemailer.com). Install `nodemailer` in your app. ViteHub does not install it for you, and it imports it only when it sends:

```bash [Terminal]
pnpm add nodemailer
```

### Nuxt

```ts [nuxt.config.ts]
import { env } from 'vite-hub/env'

export default defineNuxtConfig({
  modules: ['vite-hub/nuxt'],
  vitehub: {
    email: {
      driver: 'smtp',
      options: {
        host: env({ source: env.source('SMTP_HOST') }),
        port: env({ source: env.source('SMTP_PORT') }),
        user: env({ source: env.source('SMTP_USER') }),
        pass: env({ secret: true, source: env.source('SMTP_PASS') }),
      },
    },
  },
})
```

### Nitro

```ts [vite.config.ts]
import { vitehub } from 'vite-hub'
import { env } from 'vite-hub/env'
import { defineConfig } from 'vite'
import { nitro } from 'nitro/vite'

export default defineConfig({
  plugins: [vitehub({
    email: {
      driver: 'smtp',
      options: {
        host: env({ source: env.source('SMTP_HOST') }),
        port: env({ source: env.source('SMTP_PORT') }),
        user: env({ source: env.source('SMTP_USER') }),
        pass: env({ secret: true, source: env.source('SMTP_PASS') }),
      },
    },
  }), nitro()],
})
```

### Vite

```ts [vite.config.ts]
import { vitehub } from 'vite-hub'
import { env } from 'vite-hub/env'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [vitehub({
    email: {
      driver: 'smtp',
      options: {
        host: env({ source: env.source('SMTP_HOST') }),
        port: env({ source: env.source('SMTP_PORT') }),
        user: env({ source: env.source('SMTP_USER') }),
        pass: env({ secret: true, source: env.source('SMTP_PASS') }),
      },
    },
  })],
})
```

| Option | Default | Behavior |
| --- | --- | --- |
| `host` | Required | The SMTP server, such as `smtp.example.com`. |
| `port` | `465` when `secure` is true, else `587` | A number, or a string from `env()`. |
| `secure` | `true` on port 465, else `false` | `true` opens a TLS connection. `false` uses STARTTLS when available and requires it when you set login credentials. Also accepts the strings `'true'` and `'false'`. |
| `user`, `pass` | No login | Set both or neither. If the connection cannot be encrypted, the driver does not log in or send the message. |

The driver opens a new connection for each send. A successful result has `driver: 'smtp'` and the `Message-ID` as `id`. SMTP has no tags, metadata, scheduled delivery, or idempotency keys, so a message with one of them fails with `EMAIL_PROVIDER_FAILED`. A rejected login is `EMAIL_AUTHENTICATION`, and a server that answers `421`, `450`, `451`, or `452` is `EMAIL_RATE_LIMITED`.

If the server accepts only some recipients, `email.send()` returns `EMAIL_PROVIDER_FAILED`. The provider error at `error.cause` sets `retryable` to `false` and carries `{ accepted, rejected, messageId }` in its own `cause`. Do not retry the original message: the accepted recipients can already have received it. Check the relay logs before resending to any rejected recipients.

The `smtp` driver runs on Node hosts. Cloudflare Workers cannot open SMTP connections, so a Cloudflare build fails with [`EMAIL_HOST_UNSUPPORTED`](https://vitehub.dev/docs/email/limits-and-errors#email_host_unsupported). A build without `nodemailer` fails with [`EMAIL_SMTP_NODEMAILER_MISSING`](https://vitehub.dev/docs/email/diagnostics/email_smtp_nodemailer_missing).

## Configure another provider

For a provider other than `resend`, `smtp`, or `cloudflare`, write a driver module and set `driver` to its path. The path is relative to the project root. The module default-exports a function that gets `email.options`, with each `env()` value read, and returns an `EmailDriver`. `email.send()`, Forms, and the Agent `email()` Capability then send through it.

### Nuxt

```ts [nuxt.config.ts]
import { env } from 'vite-hub/env'

export default defineNuxtConfig({
  modules: ['vite-hub/nuxt'],
  vitehub: {
    email: {
      driver: './server/email-driver.ts',
      options: {
        apiKey: env({ secret: true, source: env.source('POSTMARK_TOKEN') }),
      },
    },
  },
})
```

### Nitro

```ts [vite.config.ts]
import { vitehub } from 'vite-hub'
import { env } from 'vite-hub/env'
import { defineConfig } from 'vite'
import { nitro } from 'nitro/vite'

export default defineConfig({
  plugins: [vitehub({
    email: {
      driver: './server/email-driver.ts',
      options: {
        apiKey: env({ secret: true, source: env.source('POSTMARK_TOKEN') }),
      },
    },
  }), nitro()],
})
```

### Vite

```ts [vite.config.ts]
import { vitehub } from 'vite-hub'
import { env } from 'vite-hub/env'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [vitehub({
    email: {
      driver: './server/email-driver.ts',
      options: {
        apiKey: env({ secret: true, source: env.source('POSTMARK_TOKEN') }),
      },
    },
  })],
})
```

This example sends the message body and addresses, including `replyTo` from Forms. It does not forward headers, attachments, tags, metadata, scheduling, unsubscribe settings, or idempotency keys.

```ts [server/email-driver.ts]
import type { EmailAddress, EmailAddressList, EmailDriver } from 'vite-hub/email'

function formatAddress(address: EmailAddress): string {
  if (typeof address === 'string') return address
  if (!address.name) return address.email
  const name = address.name.replaceAll('\\', '\\\\').replaceAll('"', '\\"')
  return `"${name}" <${address.email}>`
}

function formatAddresses(value: EmailAddressList | undefined): string | undefined {
  if (value === undefined) return undefined
  const addresses = typeof value === 'string' || 'email' in value ? [value] : value
  return addresses.map(formatAddress).join(', ')
}

export default function postmarkDriver(options: { apiKey: string }): EmailDriver {
  return {
    name: 'postmark',
    async send(message) {
      const response = await fetch('https://api.postmarkapp.com/email', {
        method: 'POST',
        headers: { 'accept': 'application/json', 'content-type': 'application/json', 'x-postmark-server-token': options.apiKey },
        body: JSON.stringify({
          From: formatAddress(message.from),
          To: formatAddresses(message.to),
          Cc: formatAddresses(message.cc),
          Bcc: formatAddresses(message.bcc),
          ReplyTo: formatAddresses(message.replyTo),
          Subject: message.subject,
          HtmlBody: message.html,
          TextBody: message.text,
        }),
      })
      if (!response.ok) {
        const error = Object.assign(new Error(`Postmark answered ${response.status}`), { code: 'PROVIDER' as const, driver: 'postmark', status: response.status })
        return [error, undefined]
      }
      const { MessageID } = await response.json() as { MessageID: string }
      return [undefined, { at: new Date(), driver: 'postmark', id: MessageID }]
    },
  }
}
```

The host compiles the module with your app, so it can import any package. ViteHub calls the function for each send. In `vite dev`, the [development outbox](https://vitehub.dev/docs/email/hosts#development-outbox) wraps it like a built-in driver. A path to a file that does not exist fails the build with [`EMAIL_DRIVER_MODULE_NOT_FOUND`](https://vitehub.dev/docs/email/diagnostics/email_driver_module_not_found).

To send without the `email` helper, pass the driver to `createEmail()`.

Keep credentials in Server Env or your host's secret store, and pass them as `env()` declarations without defaults. A driver's `send()` returns `[error, data]`, the same order as `email.send()`: `[undefined, { id, driver, at }]` on success, or `[error, undefined]` with an error that has a `code` such as `PROVIDER` and the `driver` name.

- A driver object starts once per client. Sends at the same time share the pending start. After a failed start, the next send tries again.
- A driver factory creates and starts a driver for each send.
- The development outbox follows the same rules.

<!-- vitehub-docs:section-links -->
## In this section

- [Overview](https://vitehub.dev/raw/docs/email.md)
- [Get started](https://vitehub.dev/raw/docs/email/get-started.md)
- [Configure](https://vitehub.dev/raw/docs/email/configure.md) (this page)
- [Server API](https://vitehub.dev/raw/docs/email/server-api.md)
- [Agent capability](https://vitehub.dev/raw/docs/email/agent-capability.md)
- [Hosts](https://vitehub.dev/raw/docs/email/hosts.md)
- [Limits and errors](https://vitehub.dev/raw/docs/email/limits-and-errors.md)

Next: [EMAIL_NETWORK](https://vitehub.dev/raw/docs/email/diagnostics/email_network.md)

All pages: [llms.txt](https://vitehub.dev/llms.txt)
