---
title: "Send transactional email"
description: "Send email from your own backend functions through setupEmail: the scaffolded backend/email.ts, email.send from an action or a mutation, idempotent sends, the transactional and marketing senders, how long records are kept, the auth emails that send themselves, and the EMAIL_* variables."
canonical_url: "https://nuxt-backend.dev/docs/build/email/sending"
---
# Send transactional email

> Send email from your own backend functions through setupEmail: the scaffolded backend/email.ts, email.send from an action or a mutation, idempotent sends, the transactional and marketing senders, how long records are kept, the auth emails that send themselves, and the EMAIL_* variables.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [Try it live in the playground](https://nuxt-backend.dev/playground/notifications)
- [API reference](https://nuxt-backend.dev/docs/reference/api/email)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/convex/integrations/email.ts)

- **You get:** `email.send` from any action or mutation, durable and retried, with a record you can track to delivery.
- **Powered by:** Resend's sending API, idempotency keys and delivery events, nested inside the `backend` component. There is no component of your own to mount.
- **The package adds:** one instance every email goes through (the package's own included), refusals for mail that cannot arrive, a separate marketing sender, record pruning, and a path for secret emails that keeps no copy.

Send an email from your own backend code, and know it was delivered. The `backend` component queues each send, retries it and keeps a record you can [track to delivery](https://nuxt-backend.dev/docs/build/email/delivery). It works as soon as the `EMAIL_*` variables are set: the [Resend](https://nuxt-backend.dev/docs/services/resend) service page has the account and key steps.

## Set up the email instance

`setupEmail(components, options?)` from `nuxt-backend/email` is your app's email instance. The scaffolded `backend/email.ts` creates it, re-exports the functions the package's composables and DevTools call, and adds one internal send:

```ts [backend/email.ts]
import { setupEmail } from 'nuxt-backend/email'
import { v } from 'convex/values'
import { components } from './_generated/api'
import { internalAction } from './_generated/server'
import { paths } from './paths.generated'

// `paths` is where an email's unsubscribe link opens: the page nuxt.config names.
export const email = setupEmail(components, { paths })

// The read behind useEmailStatus, and the DevTools Email tab's previews.
export const { getEmailStatus, previewEmails, sendEmailPreview } = email.api

export const send = internalAction({
  args: { to: v.string(), subject: v.string(), text: v.string() },
  returns: v.union(v.string(), v.null()),
  handler: async (ctx, args) => email.send(ctx, args),
})
```

Every option on these pages goes into this one `setupEmail` call, and every re-export into this one `email.api` line.

`send` is internal on purpose. A public action that takes its recipient from the browser lets anyone who can sign in send mail from your verified domain to any address. Send from your own server code instead, to an address you trust: the signed-in person's own, a workspace invitation's, an order's.

To let an administrator type an address, put the send behind the `admin` tier from [`backend/functions.ts`](https://nuxt-backend.dev/docs/build/auth/access/functions), in a file of its own: `functions.ts` reads `billing.ts`, which reads `email.ts`, so `email.ts` never imports the tiers. Plain text keeps anything typed into the form from rendering as markup:

```ts [backend/support.ts]
import { v } from 'convex/values'
import { email } from './email'
import { admin } from './functions'

export const sendAsAdmin = admin.action({
  args: { to: v.string(), subject: v.string(), text: v.string() },
  returns: v.union(v.string(), v.null()),
  handler: async (ctx, args) => email.send(ctx, args),
})
```

Every `admin` write asks for a recent sign-in. Call it through `withReauthentication` with `<ReauthenticateDialog />` mounted ([Require a recent sign-in](https://nuxt-backend.dev/docs/build/auth/access/step-up)).

## Send an email

`email.send(ctx, options)` queues a durable email and resolves to its id, or to `null` while no `EMAIL_API_KEY` is set. Call it from an action, an internal action or a mutation. In a workflow step, call the component through `step.runMutation`, which takes the same durable, tracked path. Panels, the comic-strip maker these docs build, emails a person when their strip is ready:

```ts [backend/strips.ts]
// From an action or a mutation of the `authed` tier, whose ctx.user is the caller:
const emailId = await email.send(ctx, {
  to: ctx.user.email,
  subject: 'Your strip is ready',
  text: 'Open it from your studio.',
})

// From a workflow step:
await step.runMutation(components.backend.email.send, {
  to: 'reader@example.com',
  subject: 'Your strip is ready',
  text: 'Open it from your studio.',
})
```

The options (`SendEmailOptions`):

<field-group>
<field name="to" type="string | string[]" :required="true">

The recipients.

</field>

<field name="subject / html / text" type="string">

The message. Build `html` with the `html` tag from `nuxt-backend/email`, which escapes what it interpolates, or put the message in the package's layout with [`email.compose`](https://nuxt-backend.dev/docs/build/email/templates/theme#your-own-emails-in-the-layout).

</field>

<field name="from" type="string">

The sender. `EMAIL_FROM` when you leave it out, or `EMAIL_MARKETING_FROM` for a send under a topic ([Two senders](#two-senders)).

</field>

<field name="cc / bcc" type="string | string[]">

More recipients.

</field>

<field name="replyTo" type="string[]">

Where replies go.

</field>

<field name="headers" type="{ name, value }[]">

Extra headers.

</field>

<field name="template" type="{ id, variables? }">

A template hosted by the provider, in place of `html` and `text`.

</field>

<field name="idempotencyKey" type="string">

Dedupes the send: a second send with the same key, while the first is on record, returns the first one's id and delivers nothing. The `nuxt-backend:` prefix is reserved for the package's own keys ([Sent once](https://nuxt-backend.dev/docs/build/email/templates#sent-once)).

</field>

<field name="topic" type="string">

Makes the send a marketing email: it checks the recipient's choice and the sending rules, goes out from the marketing sender, and carries a one-click unsubscribe ([Let people choose their emails](https://nuxt-backend.dev/docs/build/email/preferences)).

</field>
</field-group>

The rest of the instance:

- `email.status(ctx, emailId)` reads an email's delivery status.
- `email.cancel(ctx, emailId)` cancels an email that has not gone out yet.
- `email.sendTemplate(ctx, name, data, options?)` sends one of the package's own emails, in its recipient's language ([Customize email templates](https://nuxt-backend.dev/docs/build/email/templates)).
- `email.webhookHandler` is what [`registerBackendRoutes`](https://nuxt-backend.dev/docs/ship/security/webhooks) mounts at `/email/events`.

## Two senders

Transactional and marketing mail go out from different addresses, each on a subdomain of its own:

<table>
<thead>
  <tr>
    <th>
      Variable
    </th>
    
    <th>
      Sends
    </th>
    
    <th>
      Example
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        EMAIL_FROM
      </code>
    </td>
    
    <td>
      Sign-in codes, invitations, your own transactional email, and every send without a topic
    </td>
    
    <td>
      <code>
        Panels <hello@auth.panels.app>
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        EMAIL_MARKETING_FROM
      </code>
    </td>
    
    <td>
      Every send under a topic: lifecycle flows, announcements, newsletters
    </td>
    
    <td>
      <code>
        Panels <news@news.panels.app>
      </code>
    </td>
  </tr>
</tbody>
</table>

Mailbox providers judge each subdomain's reputation on its own, so a newsletter that draws complaints does not send your sign-in codes to spam. Without `EMAIL_MARKETING_FROM`, marketing sends use `EMAIL_FROM`, and `doctor --prod` warns. A topic's own `from` wins over both ([Declare the topics](https://nuxt-backend.dev/docs/build/email/preferences#declare-the-topics)). [Separate your senders](https://nuxt-backend.dev/docs/build/email/delivery/deliverability#separate-your-senders) verifies both subdomains.

## Check it works

On your dev deployment, with `EMAIL_API_KEY` set, send one to a Resend test address and read it back from the [dev inbox](https://nuxt-backend.dev/docs/develop/dev-inbox):

```bash
npx convex run email:send '{"to":"delivered@resend.dev","subject":"Hello","text":"It works."}'
npx nuxt-backend inbox
```

The first command prints the email's id, which [`useEmailStatus`](https://nuxt-backend.dev/docs/build/email/delivery) follows to `delivered`. Without a key it prints `null`, and the deployment logs `email.skipped_no_api_key`.

## Auth emails go through your instance

`setupAuth` takes your `email` instance, and every auth email goes out through it on the same component path: the sign-in codes, the welcome, the email-change notice and workspace invitations. `setupBilling` sends the gift notification the same way. Restyle any of them with `setupEmail(components, { templates })` ([Customize email templates](https://nuxt-backend.dev/docs/build/email/templates)).

To deliver sign-in codes yourself, pass your own `emailOTP` plugin in `authOptions.plugins`. It replaces the package's sender for codes, and the refusals in [Get email into inboxes](https://nuxt-backend.dev/docs/build/email/delivery/deliverability#emails-that-would-not-arrive) no longer apply to them.

## How long records are kept

The component's maintenance prunes email records every hour. A record with a final status (delivered, bounced, cancelled, failed) goes after 7 days, and one that never got one after 30 days ([Limits and retention](https://nuxt-backend.dev/docs/reference/backend/limits#windows-and-lifetimes)). Set your own windows in milliseconds:

```ts [backend/email.ts]
const DAY = 24 * 60 * 60 * 1000

export const email = setupEmail(components, {
  retention: { finalizedMs: 90 * DAY, abandonedMs: 120 * DAY },
})
```

Every email carries the setting to the component, so a change applies from the next email sent. A record that `email.status` should still read must be younger than the window. To prune once, now, call `email.cleanup(ctx, { olderThanMs })` or `email.cleanupAbandoned(ctx, { olderThanMs })`.

## Secret emails leave no record

A sign-in code is a credential while it is valid, so its email takes its own path. The message waits only until the provider answers, then the component deletes it and keeps no email record. `sendTemplate` resolves with `null` for it, and it has no status to read. A failed send is retried while the code is valid, never after it expires. It leaves a log line, `email.secret_failed`, with no address in it.

What this does not cover:

- **The provider's copy.** Resend keeps the emails it sent, HTML included, in its logs for as long as your plan keeps them. The packaged templates keep the code out of the subject. An override that puts it there puts it in the provider's email list too.
- **The dev inbox.** Outside production, the [dev inbox](https://nuxt-backend.dev/docs/develop/dev-inbox) reads codes sent to test addresses back from the provider's copy. That is how a demo or an end-to-end run signs in.
- **An idempotency key on a code.** With no record kept, an `idempotencyKey` on a secret email dedupes only while an earlier one with the same key is still waiting. Once that one is sent, the same key sends again.

## Environment

The component reads these variables. The scaffolded `convex.config.ts` forwards them to it, and `npx nuxt-backend env push` sets them on the deployment from `.env.local`:

<table>
<thead>
  <tr>
    <th>
      Variable
    </th>
    
    <th>
      Effect
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        EMAIL_API_KEY
      </code>
    </td>
    
    <td>
      The Resend API key. Unset, sends do nothing, and sign-in codes and invitations to real addresses are <a href="https://nuxt-backend.dev/docs/build/email/delivery/deliverability#emails-that-would-not-arrive">
        refused
      </a>
      
      . Topics, segments and broadcasts need a full-access key.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        EMAIL_FROM
      </code>
    </td>
    
    <td>
      The transactional sender, such as <code>
        Panels <hello@auth.panels.app>
      </code>
      
      , on a domain you verified. Unset, Resend's onboarding address.
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        EMAIL_MARKETING_FROM
      </code>
    </td>
    
    <td>
      The marketing sender, for every send under a topic. Unset, <code>
        EMAIL_FROM
      </code>
      
      .
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        EMAIL_REGION
      </code>
    </td>
    
    <td>
      The region your sending domains send from: <code>
        us-east-1
      </code>
      
      , <code>
        eu-west-1
      </code>
      
      , <code>
        sa-east-1
      </code>
      
       or <code>
        ap-northeast-1
      </code>
      
       (<a href="https://nuxt-backend.dev/docs/build/email/delivery/deliverability#send-from-a-region">
        Send from a region
      </a>
      
      ).
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        EMAIL_WEBHOOK_SECRET
      </code>
    </td>
    
    <td>
      Verifies the delivery events on <code>
        /email/events
      </code>
      
       (<a href="https://nuxt-backend.dev/docs/build/email/delivery">
        Track delivery
      </a>
      
      ).
    </td>
  </tr>
</tbody>
</table>

`BACKEND_ENVIRONMENT` decides whether mail reaches real people. Outside `production`, email runs in test mode, and only Resend's test addresses receive it. On `development`, every sign-in code also prints in the terminal running `npx nuxt-backend dev`, so sign-in works before you have a key ([Environments](https://nuxt-backend.dev/docs/start/concepts/environments#backend_environment)).

## What happens when…

<table>
<thead>
  <tr>
    <th>
      The send
    </th>
    
    <th>
      What happens
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Finds no <code>
        EMAIL_API_KEY
      </code>
    </td>
    
    <td>
      Resolves to <code>
        null
      </code>
      
       and logs <code>
        email.skipped_no_api_key
      </code>
      
      . On <code>
        development
      </code>
      
      , sign-in codes print in the terminal
    </td>
  </tr>
  
  <tr>
    <td>
      Is a code or an invitation that could not arrive
    </td>
    
    <td>
      Refused with <code>
        unavailable
      </code>
      
      , reason <code>
        test_mode
      </code>
      
       or <code>
        unconfigured
      </code>
      
      , before anything is stored (<a href="https://nuxt-backend.dev/docs/reference/backend/errors">
        Errors
      </a>
      
      )
    </td>
  </tr>
  
  <tr>
    <td>
      Carries an <code>
        idempotencyKey
      </code>
      
       already on record
    </td>
    
    <td>
      Returns the first email's id and delivers nothing
    </td>
  </tr>
  
  <tr>
    <td>
      Has a <code>
        topic
      </code>
      
       the recipient is not in
    </td>
    
    <td>
      Resolves to <code>
        null
      </code>
      
       and logs <code>
        email.skipped_unsubscribed
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Is refused by the provider
    </td>
    
    <td>
      Retried with backoff, then recorded as <code>
        failed
      </code>
      
      , which <code>
        useEmailStatus
      </code>
      
       shows
    </td>
  </tr>
</tbody>
</table>

## Limits

- **The provider's quota and rate.** Your Resend plan sets a daily and a monthly quota, and a request rate. Sends past the rate wait in the component's queue; sends past the quota fail until it resets. `doctor --prod` reads the quota (`email-quota`).
- **Test sends count.** Mail to Resend's test addresses counts against the same quota as real mail.
- **Account data stays in the US.** The sending region moves where mail leaves from, not where Resend keeps its logs ([Resend's data and compliance](https://nuxt-backend.dev/docs/services/resend#data-and-compliance)).

## Test it

Under Vitest, `nuxt-backend/test` runs your functions on an in-memory deployment, with no provider call. With no `EMAIL_API_KEY` there, a send resolves to `null` without throwing, so the function around it runs to the end:

```ts [backend/strips.test.ts]
import { defineBackendTestApp } from 'nuxt-backend/test'
import { expect, test } from 'vitest'
import { internal } from './_generated/api'
import schema from './schema'

const testApp = defineBackendTestApp(schema, import.meta.glob('./**/*.ts'))

test('the ready email never blocks the strip', async () => {
  const emailId = await testApp().action(internal.email.send, {
    to: 'delivered@resend.dev',
    subject: 'Your strip is ready',
    text: 'Open it from your studio.',
  })
  expect(emailId).toBeNull()
})
```

[Test backend functions](https://nuxt-backend.dev/docs/develop/testing/functions) covers the test app, and [Run end-to-end tests](https://nuxt-backend.dev/docs/develop/testing/e2e) reads real mail back from the dev inbox.

## Related

- [Resend](https://nuxt-backend.dev/docs/services/resend): the account, the key and the sending domains.
- [Customize email templates](https://nuxt-backend.dev/docs/build/email/templates): the emails the package sends for you.
- [Track delivery](https://nuxt-backend.dev/docs/build/email/delivery): follow a send to delivered, bounced or complained.
- [Get email into inboxes](https://nuxt-backend.dev/docs/build/email/delivery/deliverability): leave test mode and send from your own domains.
- [`nuxt-backend/email`](https://nuxt-backend.dev/docs/reference/api/email): every option and method.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
