---
title: "Self-hosting reference"
description: "OneSend can be self-hosted with a license key (see License key); it is proprietary software under the OneSend License."
url: https://onesend.email/docs/self-hosting/
---
# Self-hosting reference

OneSend can be self-hosted with a license key (see [License key](#license-key)); it is proprietary software under the OneSend License. The self-hosted edition is the sending platform and the whole workspace: the team inbox, calendar, booking pages and drive (see [The workspace](#the-workspace-inbox-calendar-booking-pages-and-drive)). One Node.js process serves the API, background worker, SMTP ingress, inbound SMTP receiver, the IMAP and POP servers for mail apps, tracking endpoints and dashboard. The [Cloudflare edition](https://onesend.email/docs/cloudflare/) runs the same code on Workers.

## Requirements

- Node.js 22.13 or later, or Docker. The default SQLite driver is Node's built-in `node:sqlite`, so nothing needs to be compiled.
- A database. With nothing configured, OneSend uses a SQLite file in `ONESEND_DATA_DIR`. See [Bring your own database](#bring-your-own-database).
- No Redis. Jobs, quota counters and idempotency keys are stored in the database.

## Running

From a checkout (see [Getting started](https://onesend.email/docs/getting-started/) for the full steps):

```bash
npm install
npm run setup      # writes .env (database, public URL, ports, sign-up, ONESEND_SECRET) and creates the tables
npm run build:web  # the dashboard, served at /
npm start          # reads .env from the current folder
npm run doctor     # checks settings, database, migrations, ports and the public URL
```

`npm start` runs `node apps/server/bin/onesend-server.mjs`. The same file runs the tools: `onesend-server setup`, `onesend-server doctor` and `onesend-server db:copy` (each prints its options with `--help`).

With Docker, build the image from the repository: `docker compose up -d --build`. The image sets `NODE_ENV=production`, `PORT=3000` and `ONESEND_DATA_DIR=/data`, and exposes ports 3000 (HTTP), 2587 (SMTP sending), 2525 (SMTP receiving, the MX target), 1143 and 1993 (IMAP, IMAPS) and 1110 and 1995 (POP3, POP3S). Only 3000 is needed; the mail ports are optional and listed under [Ports for the workspace](#ports-for-the-workspace). The slim image has no `curl` or `wget`; use `node -e` for one-off requests inside the container.

<a id="docker-closed-signup"></a>
With `ONESEND_SIGNUP=closed` in Docker, create the owner account from inside the container (the Compose service is called `openemail`, its name from before the rename):

```bash
docker compose exec -e OWNER_PASSWORD='<a long password>' openemail node -e "fetch('http://localhost:3000/v1/auth/signup',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({email:'you@example.com',password:process.env.OWNER_PASSWORD})}).then(r=>r.text()).then(console.log)"
```

The server reads configuration from environment variables, from a `.env` file in its working directory, and, for non-secret settings only, from `onesend.config.json`. Precedence, highest first: environment variables (shell, Docker `env_file`, systemd, your platform), then `.env`, then `onesend.config.json`, then defaults. `.env` never overrides a variable that is already set. Set `ONESEND_ENV_FILE=<path>` to read another file, or `ONESEND_ENV_FILE=off` to read none. The Docker image does not contain `.env`; Compose passes it with `env_file`.

<a id="startup-checks"></a>
At startup the server stops with a plain explanation when it cannot run: a missing `ONESEND_SECRET` in production, a setting with a wrong value, a database it cannot open (which driver and host failed, with the password removed, and what to check), or an HTTP port that is in use. It logs a hint when the dashboard is not built, when no account exists yet (`No account yet: open <url>/signup. The first account becomes the owner.`), and when it runs on SQLite with `NODE_ENV=production`. `npm run doctor` runs the same checks and more without starting the server.

<a id="environment-variables"></a>
## Environment variables

Every variable marked **Secret** can also be read from a file: set `<NAME>_FILE` to the path of a mounted secret (for example `ONESEND_SECRET_FILE=/run/secrets/onesend_secret`). Secrets are never accepted in `onesend.config.json`; putting one there stops the server at startup.

### Server

| Variable | Default | Purpose |
|---|---|---|
| `NODE_ENV` | `development` | `production` makes `ONESEND_SECRET` required and replaces internal error messages in API responses with "Something went wrong". The Docker image sets `production`. |
| `PORT` | `3000` | HTTP port for the API, dashboard, `/docs`, webhooks and tracking. |
| `HOST` | `0.0.0.0` | Interface the HTTP server listens on. Set `127.0.0.1` to accept only local connections, for example behind a reverse proxy on the same host. |
| `ONESEND_PUBLIC_URL` | `http://localhost:$PORT` | Public base URL, without a trailing slash. Used in tracking links, unsubscribe links, view-in-browser links, provider webhook registration, the OpenAPI `servers` entry and the `/docs` canonical link. Set it in production. |
| `ONESEND_ENV_FILE` | `.env` | File of `KEY=value` lines read at startup (and by `npm run doctor` and `npm run db:copy`). Values already set in the environment win. `off` reads no file. Must be set in the real environment, not in the file. |
| `ONESEND_DATA_DIR` | `./.data` | SQLite and PGlite data, the generated secret and local attachments. Relative to the working directory. `npm run dev` and `npm start` both run from the repository root and use `./.data` (earlier versions of `npm run dev` used `apps/server/.data`). |
| `ONESEND_WEB_DIST` | `<install dir>/apps/web/dist` | Folder of the built dashboard. If it has no `index.html`, `/` shows a short page explaining how to build the dashboard. |
| `ONESEND_TEMPLATES_DIR` | `<install dir>/templates` | The bundled starter templates, served by `/v1/gallery` when the hosted gallery cannot be reached. A value you set is resolved against the working directory. `ONESEND_GALLERY_DIR` is accepted as an older name. |
| `ONESEND_GALLERY` | `on` | `off`: no hosted template gallery; only the bundled starter templates. See [Templates](https://onesend.email/docs/templates/#gallery). |
| `ONESEND_GALLERY_URL` | the cloud's public URL | The hosted template gallery this server reads. |
| `ONESEND_GALLERY_API_KEY` | none | Secret. A full-access API key of your cloud workspace, to share templates to the hosted gallery from this server. |
| `ONESEND_GALLERY_TIMEOUT_MS` | `4000` | Timeout of one request to the hosted gallery. |
| `ONESEND_CORS_ORIGINS` | development: `http://localhost:5173`, `http://127.0.0.1:5173`, `http://localhost:5199`, `http://127.0.0.1:5199`; production: none | Comma-separated browser origins allowed to call `/v1` with CORS. Outside production the default allows the development dashboard. `*` allows any origin. The dashboard served by the server itself needs no entry. |
| `ONESEND_TRUST_PROXY` | `false` | Number of reverse proxies in front of the server whose `X-Forwarded-For`, `X-Forwarded-Proto` and `X-Forwarded-Host` are trusted, for client IPs (rate limits, local-request checks) and HTTPS detection. `true` means 1; use `2` for a CDN in front of your proxy, for example. The client address is taken that many entries from the right of `X-Forwarded-For`, so values a client adds itself are ignored. Set it only when every request reaches the server through your proxies. |
| `ONESEND_ALLOW_PRIVATE_NETWORK` | `false` | `true` lets webhook URLs, attachment URLs and provider base URLs point to private, loopback and link-local addresses. By default these are blocked to prevent server-side request forgery. |
| `ONESEND_SIGNUP` | `first-user` (`closed` with `ONESEND_EDITION=cloud`) | `open`: anyone can sign up, and each account gets its own workspace. `first-user`: only the first account; whoever reaches a fresh instance first becomes the owner, so create the owner account before you expose it. `invite`: like `first-user`, and states the intent: after the owner, accounts are created only by accepting an [invitation](https://onesend.email/docs/team/#invitations) (which works in every mode). `closed`: nobody can sign up over the network; on a fresh instance the owner account can be created only from the server itself, for example through an SSH tunnel (`ssh -L 3000:localhost:3000 <server>`, then open http://localhost:3000). Behind a proxy on the same host this needs `ONESEND_TRUST_PROXY`. In Docker, requests arrive from the bridge network, not loopback: use `first-user` for the first start, or sign up from inside the container (see [Docker and `closed` sign-up](#docker-closed-signup)). |
| `ONESEND_SETUP_CODE` | none | Secret (also `ONESEND_SETUP_CODE_FILE`). While the instance has no account, signing up needs this code, so whoever reaches a fresh public instance first cannot become the owner. The installer (`install.sh`, `npm run cf:setup`) generates one and prints it; the sign-up page asks for it. Ignored once the owner exists. Spaces, dashes and upper or lower case do not matter. |
| `ONESEND_EDITION` | `self_hosted` | Leave it unset. Self-hosted servers have no plan limits and no billing. `cloud` is for the hosted service: it has no inbox, sign-up is closed unless `ONESEND_SIGNUP` is set, and its plans are switched off unless `ONESEND_CLOUD_PLANS=on`. `desktop` is set only by the Mac app for its built-in server (sign-up closes after the owner, no billing); the app also sets `ONESEND_DESKTOP_APP=1`, and a `desktop` server without that marker needs a [license key](#license-key) like any self-hosted one. The marker is a deterrent, not a lock: whoever controls the server's environment can set it. With `NODE_ENV=production` the edition is read from the environment only; an `edition` in `onesend.config.json` is ignored with a warning. See Cloud edition. |
| `ONESEND_ALERT_SMTP_URL` | none | **Secret.** The server's own SMTP server for [security alerts](#security-alerts) a workspace cannot deliver itself, and for sign-in links to operator addresses (`ONESEND_ADMIN_EMAILS`): `smtp://user:password@host:587` or `smtps://user:password@host:465`. Node only. |
| `ONESEND_ALERT_FROM` | `OneSend <no-reply@<server host>>` | Sender of the alert mailer. |
| `ONESEND_ALLOW_OPEN_SIGNUP_WITHOUT_LIMITS` | unset | Cloud edition only. `ONESEND_SIGNUP=open` with the cloud plans off means anyone can sign up and send with no plan limits and no usage limits: the server refuses to start in production (and warns otherwise) unless this is `true`. |
| `ONESEND_PLAN` | `self_hosted` (cloud edition: `none`) | Plan stored on new workspaces. Self-hosted installs have no plan limits, and neither does the cloud edition while `ONESEND_CLOUD_PLANS` is `off`. See Cloud edition. |
| `ONESEND_LEGACY_TOKENS_UNTIL` | `2027-02-01` | View-in-browser, open and click links signed by earlier builds, before link tokens carried a purpose, keep working until this date. `never` keeps accepting them. Unsubscribe links always work. |
| `ONESEND_DNS_OVERRIDES` | none | **Development only**; the server refuses to start with it when `NODE_ENV=production`. DNS answers used instead of public DNS for domain verification, so a local domain such as `acme.test` can be verified and receive mail. Inline JSON or a path to a JSON file. See [Testing domains locally](https://onesend.email/docs/domains-and-dns/#testing-locally). |
| `LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error`. `debug` logs provider requests (credentials are redacted). |

### Secrets and database

| Variable | Default | Purpose |
|---|---|---|
| `ONESEND_SECRET` | generated into `$ONESEND_DATA_DIR/secret` | **Secret.** At least 32 characters. Encrypts provider credentials (AES-256-GCM) and signs tracking, unsubscribe and view links. **Required** when `NODE_ENV=production`. Generate one with `openssl rand -base64 32`. Back it up: if it is lost, every provider key must be entered again and links in sent email stop working. |
| `ONESEND_SECRET_PREVIOUS` | none | **Secret.** The previous master secret, set only while rotating. See [Rotating ONESEND_SECRET](#rotating-onesend_secret). |
| `DATABASE_URL` | none (SQLite at `$ONESEND_DATA_DIR/onesend.db`) | **Secret.** Database connection string. See [Bring your own database](#bring-your-own-database). |
| `DATABASE_AUTH_TOKEN` | none | **Secret.** libSQL or Turso auth token. |
| `DATABASE_DRIVER` | from the URL scheme | `sqlite`, `postgres`, `pglite`, `libsql` or `d1`. Use it when the URL is ambiguous, for example `libsql` to open a `file:` URL with libSQL. |
| `DATABASE_POOL` | `10` | PostgreSQL connection pool size. |
| `ONESEND_INGEST_SECRET` | none | **Secret.** Shared secret for the standalone Cloudflare Email Worker (the `@onesend/inbound-cf` workspace of the self-hosted edition, see [Receiving mail](#receiving-mail)). It is not generated: while it is unset, `/ingest/cloudflare` returns 503 `ingest_disabled`. Generate one with `openssl rand -hex 24`. Not needed on the Cloudflare edition, whose own Worker receives the mail. |


### SMTP

| Variable | Default | Purpose |
|---|---|---|
| `ONESEND_SMTP_PORT` | `2587` | SMTP ingress: apps send through OneSend with an API key as the password. `0` or `off` disables it. See [SMTP](https://onesend.email/docs/smtp/). |
| `ONESEND_SMTP_IN_PORT` | `2525` | Built-in inbound receiver (an MX target, see [Receiving mail](#receiving-mail)). `0` or `off` disables it. |
| `ONESEND_SMTP_TLS_KEY` | none | Path to a PEM private key for SMTP. Set it together with `ONESEND_SMTP_TLS_CERT`. |
| `ONESEND_SMTP_TLS_CERT` | none | Path to the matching PEM certificate (full chain). |
| `ONESEND_SMTP_ALLOW_INSECURE_AUTH` | `false` (the bundled `docker-compose.yml` defaults to `true`) | `true` accepts SMTP AUTH without TLS from non-loopback clients. Use it only on a trusted private network. The Compose file publishes 2587 on loopback only for that reason; set `ONESEND_SMTP_ALLOW_INSECURE_AUTH=false` in `.env` to turn it off. See [SMTP](https://onesend.email/docs/smtp/#tls). |
| `ONESEND_LOCAL_AI_URL` | none | Set by the Mac app only: `http://127.0.0.1:<port>/v1` of its on-device model (Apple Intelligence). An AI connection may use exactly this loopback address; other private addresses stay blocked. |
| `ONESEND_ALLOW_PRIVATE_SMTP` | `false` | `true` lets SMTP provider connections, and the IMAP and SMTP servers of [connected accounts](https://onesend.email/docs/unified-inbox/), reach private or loopback hosts, for example a local Postfix relay or Proton Mail Bridge. |

When both TLS variables are set, the SMTP servers offer STARTTLS and SMTP ingress accepts AUTH only after STARTTLS. When they are not set, STARTTLS is not offered, and AUTH (which carries the API key) is accepted only from loopback clients unless `ONESEND_SMTP_ALLOW_INSECURE_AUTH=true`. See [SMTP](https://onesend.email/docs/smtp/#tls).

### Worker

| Variable | Default | Purpose |
|---|---|---|
| `ONESEND_WORKER` | `on` | `off` stops this process from running background jobs (sending, webhooks, imports, campaigns, domain checks). Use it to run API-only processes next to a separate worker process. At least one process must run the worker. |
| `ONESEND_WORKER_CONCURRENCY` | `8` | Number of jobs the worker runs at the same time. |

### Data retention

| Variable | Default | Purpose |
|---|---|---|
| `ONESEND_RETENTION_DAYS` | `90` | Events, send attempts and message bodies (HTML and attachments) older than this are deleted. Message rows, their status and statistics are kept. `0` keeps everything. |
| `ONESEND_JOB_RETENTION_DAYS` | `7` | Finished background jobs older than this are deleted. Minimum 1. |
| `ONESEND_ENCRYPT_MAIL` | `on` | `on` or `off`. Encrypts stored mail bodies, attachment content and message sources with a per-workspace key (AES-256-GCM). Turning it on encrypts new writes at once and existing mail in a background job; turning it off stores new mail unencrypted and keeps reading encrypted mail. Non-secret (`encryptMail` in `onesend.config.json`). See [Mail encryption](#mail-encryption). |
| `ONESEND_STATUS_PAGE` | off | `on` serves a public status page at `/status` and `/status.json`. See [Status page](https://onesend.email/docs/status-page/). |
| `ONESEND_ADMIN_EMAILS` | none | Comma-separated emails of instance admins: they post status page incidents (and are the operators on the cloud edition). A listed account must also have a verified email address (a link from **POST /v1/account/email-verification**, a confirmed email change, or `npm run admin -- verify-email <email>` on the server) and two-factor authentication, passed in the session; otherwise 403 `email_verification_required`, `two_factor_setup_required` or `two_factor_required`. |
| `ONESEND_RATE_LIMITER` | `memory` (`database` with `ONESEND_EDITION=cloud` and on Cloudflare Workers) | Where login, sign-up, form, conversion and other rate limits are counted. `memory`: per process. `database`: the `rate_limits` table, shared by every process, in fixed windows (one database write per check; old windows are pruned automatically). Per-key send limits (`limits.perHour`, `limits.perDay`) are always counted in the database. |
| `ONESEND_SECURITY_ALERTS` | `on` (`off` when `NODE_ENV=test`) | Email the workspace owners when an API key is created, rotated, revoked or reported as leaked, when a key changes configuration, when a key is used from a new address, and when an inbox rule or automation starts sending data outside the workspace. Sent through the workspace's own sending providers when one can deliver, else through `ONESEND_ALERT_SMTP_URL`, and always shown in the dashboard; throttled alerts go out as an hourly digest. See [Security alerts](#security-alerts). Non-secret (`securityAlerts` in `onesend.config.json`). |
| `ONESEND_MAX_KEYS_PER_KEY` | `100` | API keys one API key may have created that are not revoked, expired ones included (keys created in the dashboard are not limited); making an expired one live again with a key counts too. Over it: 400 `too_many_keys`. Bounds the keys one leaked key holds at a time (keys made by a key cannot create keys). Minimum 1. |
| `ONESEND_LEAK_REPORT_SECRET` | none | **Secret.** Shared secret of the leaked key report endpoint (`POST /v1/security/key-leak-report`, see [SECURITY.md](https://onesend.email/security/policy/#leaked-api-keys)). Without it (and without public keys) the endpoint answers 401. Use at least 32 random characters: a shorter one is warned about at startup. |
| `ONESEND_LEAK_REPORT_PUBLIC_KEYS` | none | PEM ECDSA P-256 public keys (one or more, concatenated; `\n` escapes are accepted) whose signatures (`Github-Public-Key-Signature`) the leak report endpoint accepts. Copy them from the scanning service; the server never fetches them. |

See [Data retention](#data-retention).

### Variables read by other components

| Variable | Read by | Purpose |
|---|---|---|
| `ONESEND_API_KEY`, `ONESEND_BASE_URL` | SDK, `onesend` CLI, MCP server | Client credentials and server URL. See [SDK and CLI](https://onesend.email/docs/sdk-and-cli/) and [MCP](https://onesend.email/docs/mcp/). |
| `ONESEND_MCP_PORT`, `ONESEND_MCP_HOST`, `ONESEND_MCP_ALLOWED_HOSTS`, `ONESEND_MCP_ALLOW_ENV_KEY`, `ONESEND_MCP_CORS_ORIGIN` | MCP server (`apps/mcp`) | HTTP mode settings. See [MCP](https://onesend.email/docs/mcp/#environment). |

<a id="dashboard-build-variables"></a>
### Dashboard build and development variables

These are read by Vite when the dashboard is built (`npm run build:web`) or served in development (`npm run dev:web`), not by the server. Values are fixed into the build, so rebuild after changing them.

| Variable | Default | Purpose |
|---|---|---|
| `VITE_REPO_URL` | none | Repository URL, for example `https://github.com/<owner>/onesend`. The dashboard uses it for links to guides in `docs/`. Without it, the dashboard shows the file path in the repository (for example `docs/mcp.md`) with a copy button instead of a link. |
| `VITE_REPO_BRANCH` | `main` | Branch used in those links. |
| `VITE_DEMO` | none | `1` or `true` builds a demo dashboard with sample data and no server. |
| `ONESEND_API` | `http://localhost:3000` | Development only: the server that `npm run dev:web` proxies `/v1`, `/docs` and the other API paths to. |
| `ONESEND_WEB_PORT` | `5199` | Development only: the port `npm run dev:web` listens on. Vite exits if the port is in use. The generic `PORT` is not read, so it can stay set for the server. |

### Configuration file

`onesend.config.json` in the working directory may hold non-secret settings using camelCase keys (`port`, `host`, `publicUrl`, `dataDir`, `smtpPort`, `smtpInPort`, `smtpTlsKey`, `smtpTlsCert`, `signup`, `plan`, `corsOrigins`, `worker`, `workerConcurrency`, `logLevel`, `templatesDir`, `webDist`, `allowPrivateNetwork`, `allowPrivateSmtp`, `smtpAllowInsecureAuth`, `trustProxy`, `retentionDays`, `jobRetentionDays`, `legacyTokensUntil`, `dnsOverrides`, `connectedAccounts`, `encryptMail`, `inbox`, `siteUrl`, `dodoDesktopProductId`, `dodoDesktopRenewalProductId`, `desktopPriceLabel`, `desktopDownloadUrl`) and the non-secret database settings:

```json
{ "port": 3000, "publicUrl": "https://mail.example.com", "database": { "driver": "libsql", "poolSize": 10 } }
```

Environment variables take precedence over the file.

<a id="bring-your-own-database"></a>
## Bring your own database

The driver is chosen from the scheme of `DATABASE_URL`. Every dialect runs the same migrations, applied automatically at startup, and the same test suite.

| You have | `DATABASE_URL` (placeholders; never commit real values) | Notes |
|---|---|---|
| Nothing (default) | unset, or `sqlite:./.data/onesend.db` | Single file in WAL mode. Suitable for one server. |
| PostgreSQL 13 or later | `postgres://<user>:<password>@<host>:5432/<db>` | Recommended for several processes. |
| Neon | `postgres://<user>:<password>@<ep-xxx>.<region>.aws.neon.tech/<db>?sslmode=require` | Use the pooled host for serverless. |
| Supabase | `postgres://postgres.<ref>:<password>@<region>.pooler.supabase.com:6543/postgres` | The transaction pooler works. |
| Turso or libSQL | `libsql://<db>-<org>.turso.io` with `DATABASE_AUTH_TOKEN=<token>` | Or a local `file:` database with `DATABASE_DRIVER=libsql`. |
| Embedded PostgreSQL | `pglite:./.data/pg` | PostgreSQL semantics without a server (development, tests). |
| Cloudflare D1 | no URL; bind the database as `DB` | Only on the [Cloudflare edition](https://onesend.email/docs/cloudflare/): the Worker in `apps/worker-cf`, set up with `npm run cf:setup` (it creates the database and writes `"d1_databases": [{ "binding": "DB", … }]` into `wrangler.jsonc`). Needs Workers Paid. A D1 database holds at most 10 GB. |

**Secrets stay out of files.** `DATABASE_URL` and `DATABASE_AUTH_TOKEN` are read only from the environment, from `DATABASE_URL_FILE` and `DATABASE_AUTH_TOKEN_FILE` (Docker or Kubernetes secrets), or from your platform's secret store. Both are redacted from every log line.

**Portability.** All data access goes through a repository layer (`@onesend/core/data`) built on Kysely. Storage uses only portable types: text ids, ISO 8601 UTC timestamps stored as text, JSON stored as text, and 0/1 integers for booleans. The job queue claims work atomically (`FOR UPDATE SKIP LOCKED` on PostgreSQL; a single atomic `UPDATE … RETURNING` on SQLite, libSQL and D1). Quota reservation is a guarded `UPDATE` that cannot overshoot under concurrency.

**Switching databases.** The database is chosen when the server starts, from `DATABASE_URL`. Changing `DATABASE_URL` does not move data: the server starts with an empty database at the new URL. To bring your data, copy it first with `npm run db:copy` (see [Moving to another database](#moving-to-another-database)).

<a id="moving-to-another-database"></a>
### Moving to another database

`npm run db:copy` copies every OneSend table from one database to another, for any pair of SQLite, PostgreSQL (including Neon, Supabase, RDS), PGlite and libSQL/Turso:

```bash
# stop the server first, so nothing is written to the source during the copy
DB_COPY_FROM=sqlite:./.data/onesend.db \
DB_COPY_TO='postgres://<user>:<password>@<host>:5432/<db>' \
npm run db:copy -- --dry-run     # shows the tables and row counts; writes nothing
npm run db:copy -- --from sqlite:./.data/onesend.db --to "$DATABASE_URL"
```

- It runs the migrations on the target, then copies the tables in foreign-key order, in pages of 500 rows (`--batch`).
- Values are copied as stored: ids, timestamps, JSON and encrypted provider credentials are unchanged. Use the same `ONESEND_SECRET` for the server that uses the target. When `ONESEND_SECRET` is set (or in `.env`), the tool checks that a copied credential decrypts with it.
- It refuses a target that already has OneSend data. `--force` deletes the target's rows first, then copies.
- The source must be on the current schema: start the current version once with the source database (migrations run at startup), stop it, then copy.
- It compares the row count of every table at the end and exits with code 1 when one differs.
- URLs can come from `--from`/`--to` or from `DB_COPY_FROM`/`DB_COPY_TO` (keeps passwords out of shell history); Turso tokens from `--from-token`/`--to-token` or `DB_COPY_FROM_TOKEN`/`DB_COPY_TO_TOKEN`. URLs are printed with the password removed.
- Cloudflare D1 is not supported; use `wrangler d1 export`.

Then set `DATABASE_URL` to the target (`npm run setup`, or your platform's secret store), start the server, and check **Sending providers** in the dashboard. Keep the old database until you have checked the new one.

<a id="ports-and-tls"></a>
## Ports and TLS

- **HTTP.** Put a reverse proxy (Caddy, nginx, Traefik) in front of `PORT` for HTTPS, set `ONESEND_PUBLIC_URL` to the public HTTPS URL, and set `ONESEND_TRUST_PROXY=true` (one proxy) or the number of proxies, for example `2` for a CDN in front of nginx. With nginx, the default `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;` works with `ONESEND_TRUST_PROXY=true`. With the proxy on the same host, also set `HOST=127.0.0.1`.
- **SMTP ingress.** Set `ONESEND_SMTP_TLS_KEY` and `ONESEND_SMTP_TLS_CERT` before exposing the port beyond a private network. See [SMTP](https://onesend.email/docs/smtp/#tls).

## Rotating ONESEND_SECRET

`ONESEND_SECRET` encrypts provider credentials and signs values that leave the server: links in sent email (open and click tracking, unsubscribe, view in browser), the token in each provider webhook URL, and the `_onesend-verify` TXT value that proves domain ownership. To replace it:

1. Generate a new secret: `openssl rand -base64 32`.
2. Set `ONESEND_SECRET_PREVIOUS` to the current secret and `ONESEND_SECRET` to the new one.
3. Restart. At startup OneSend re-encrypts every stored provider credential and signing secret (webhook endpoints, mailbox webhooks and inbox rule webhooks) with the new secret and logs, for example, `re-encrypted N connection secret(s) with the current ONESEND_SECRET`, `re-encrypted N webhook signing secret(s) …` and `re-encrypted N mailbox webhook secret(s) …`. Webhook signatures stay valid for your receivers. The mail encryption key of each workspace is re-wrapped with the new secret too (`re-wrapped N mail encryption key(s)`); the stored mail itself is not re-encrypted, because it is encrypted with those keys, not with the secret.
4. While `ONESEND_SECRET_PREVIOUS` is set, values signed with either secret are accepted. Before removing it:
   - update each domain's `_onesend-verify` TXT record to the new value shown under **Senders & domains**, then verify the domain;
   - provider webhook URLs carry a token signed by the old secret. After the previous secret is removed, events sent to those URLs are rejected. To keep provider events (deliveries, bounces, complaints), call `POST /v1/connections/{id}/rotate-webhook-url` for each connection (OneSend re-registers the URL with providers that support it; for others, paste the new `webhookUrl` into the provider's dashboard), or reconnect the provider, before removing the previous secret;
   - mailbox webhook secrets are stored encrypted and re-encrypted at startup, so they do not change. Older mailboxes used a secret derived from `ONESEND_SECRET`; that value is stored the first time the server starts after the upgrade (from `ONESEND_SECRET_PREVIOUS` when you rotate at the same time), so it keeps working. To replace a mailbox secret, call `POST /v1/inbox/mailboxes/{id}/rotate-secret`;
   - decide how long links in email sent before the rotation must keep working. Unsubscribe links in old campaigns are the main reason to keep the previous secret, often for several months.
   - **API keys** are stored as a hash made with `ONESEND_SECRET`, and the server never has the keys themselves, so it cannot re-hash them at startup. A key moves to the new secret the first time it is used while `ONESEND_SECRET_PREVIOUS` is set. A key that is not used in that window (a CI key, a backup key, a monthly job, an idle SMTP relay) stops working with 401 `invalid_api_key` once the previous secret is removed. The server says how many keys still need the previous secret: at each start it logs `N API keys still use the previous secret; they stop working when ONESEND_SECRET_PREVIOUS is removed` (keys created before this was tracked, and not used since, are counted separately). Use each such key once (any authenticated request), or replace it, before you remove the previous secret. After the removal, the start log says how many keys were lost (`N API keys were hashed with a secret this server no longer has`); setting `ONESEND_SECRET_PREVIOUS` again brings them back.
5. Remove `ONESEND_SECRET_PREVIOUS` and restart. Values signed with the old secret stop working after this.

If the server reports `Could not decrypt provider credentials`, or logs that connection or webhook signing secrets cannot be decrypted, the secret changed without `ONESEND_SECRET_PREVIOUS`. Restore the old value, or set it as `ONESEND_SECRET_PREVIOUS`, and restart. A webhook endpoint whose secret cannot be decrypted is marked `secret_unreadable` and receives nothing meanwhile. It becomes `active` again at the next start where its secret decrypts (the old value restored), or when you rotate its secret (`POST /v1/webhooks/{id}/rotate-secret`).

<a id="backups"></a>
## Backups

Back up the database and `ONESEND_SECRET` together. A database backup without the secret cannot decrypt provider credentials, nor any stored mail encrypted at rest (see [Mail encryption](#mail-encryption)).

- **SQLite (default):** `sqlite3 "$ONESEND_DATA_DIR/onesend.db" ".backup backup.db"` is safe while the server runs. Alternatively, stop the server and copy the whole `ONESEND_DATA_DIR` folder, including the `-wal` and `-shm` files and the generated `secret` file.
- **Docker with SQLite:** `docker compose exec openemail node -e "new (require('node:sqlite').DatabaseSync)('/data/onesend.db').exec(\"VACUUM INTO '/data/backup.db'\")"`, then `docker compose cp openemail:/data/backup.db ./backup.db` (the Compose service is still called `openemail`, see [Upgrading from OneSend](#upgrading-from-openemail)).
- **PostgreSQL:** `pg_dump --format=custom --file=onesend.dump "$DATABASE_URL"`. Restore with `pg_restore --clean --dbname="$DATABASE_URL" onesend.dump`. With the bundled Compose file: `docker compose -f docker-compose.yml -f docker-compose.postgres.yml exec -T postgres sh -c 'pg_dump -U "$POSTGRES_USER" --format=custom "$POSTGRES_DB"' > onesend.dump`. Neon, Supabase and RDS also offer managed backups.
- **Turso and D1:** use the provider's backups or point-in-time restore.
- **PGlite:** stop the server and copy `ONESEND_DATA_DIR`.

Test a restore before you rely on it: start a second instance with the restored database and the same `ONESEND_SECRET`, and check that **Sending providers** shows your connections without errors.

<a id="data-retention"></a>
## Data retention

The worker runs a maintenance job that deletes, in small batches:

- events and send attempts older than `ONESEND_RETENTION_DAYS` (default 90);
- message bodies (HTML and attachments) older than the same limit, keeping the message row, its status and counters so statistics stay correct;
- finished jobs older than `ONESEND_JOB_RETENTION_DAYS` (default 7), expired sessions, and the uploaded CSV data of finished imports;
- workspace data exports 7 days after they were created (`ONESEND_DATA_DIR/exports`). See [Privacy](https://onesend.email/docs/privacy/).

Pruning works the same on encrypted mail (see [Mail encryption](#mail-encryption)). Connected accounts in index-only storage never store bodies or sources, so there is nothing to prune for them beyond the message rows (see [Unified inbox](https://onesend.email/docs/unified-inbox/#storage-full-or-index-only)).

After the bodies are removed, the logs still show each email's recipients, status and route, but not its content. Set `ONESEND_RETENTION_DAYS=0` to keep everything.

Retention also limits reports that are built from events:

- **Analytics** (`GET /v1/analytics/summary`: deliverability by provider, failovers and error codes) and the event log (`GET /v1/events`) cover only the retention period. A date range older than `ONESEND_RETENTION_DAYS` shows zeros.
- The timeline of an individual email (events and send attempts) is empty once they are pruned, and `POST /v1/emails/{id}/resend` returns 409 `body_unavailable` once its body is pruned.
- Campaign reports and **Statistics** (`GET /v1/statistics/overview`) use counters kept on message and campaign rows, so they are not affected.

<a id="mail-encryption"></a>
## Mail encryption

With `ONESEND_ENCRYPT_MAIL=on` (the default), stored mail is encrypted at rest in the database, on every database (SQLite, PostgreSQL, PGlite, libSQL and D1):

- **Keys.** Each workspace has its own data key: 32 random bytes, stored in `workspace_keys` wrapped (AES-256-GCM) with `ONESEND_SECRET`. Rotating the secret re-wraps the keys at startup (see [Rotating ONESEND_SECRET](#rotating-onesend_secret)). Without the secret, a database backup cannot be read.
- **What is encrypted.** Received mail: text and HTML bodies, the snippet, attachment content and the raw source kept for mail apps. Sent mail: HTML and text bodies, attachment content and the stored source. Values are AES-256-GCM with a random nonce, bound to their workspace, table and column, and carry the prefix `oe1:` (or `oe1b:` for source chunks). Rows written before encryption was on stay readable and are encrypted by a background job (`mail_seal`) in small batches; it respects the per-invocation query limit of Cloudflare D1 and yields between rows.
- **What stays in plaintext**, because threading, suppression, rules, filters and lists need it: sender and recipient addresses, subjects, dates, statuses, folders, flags, labels, `Message-ID`, `In-Reply-To` and `References`, other header fields stored as columns, attachment names, types and sizes, and all counters and events. Drafts, scheduled messages waiting in the outbox, templates and campaign content are not encrypted by this setting. On the Cloudflare edition with R2 attachment storage (`FILES`), attachments larger than the inline limit are kept in R2 as uploaded (R2 encrypts objects at rest); the inline content in D1 is encrypted.
- **Search.** Inbox search, the AI assistant's "ask your inbox" and MCP search keep working through a blind keyword index: each message stores keyed hashes (HMAC-SHA256 with a per-workspace search key) of the distinct normalized words of its subject, sender, snippet and body, at most 2,000 words. A search term matches **whole words** in encrypted mail; partial words (`invo` for `invoice`) do not match encrypted bodies (subjects and addresses are still matched as before). Chinese and Japanese text is indexed per character. Campaign mail gets no index.
- **Cost.** Bodies are decrypted only when they are read; message lists decrypt snippets only. Writing a message takes about a millisecond longer (most of it building the index).
- **Turning it off** stores new mail unencrypted; mail already encrypted stays encrypted and readable. Turning it on again encrypts what was written in the meantime.

Workspace data exports contain the bodies decrypted. Retention pruning works the same on encrypted rows.

<a id="security-alerts"></a>
## Security alerts

The owners of a workspace get an email when an API key is created, rotated, revoked or reported as leaked, changes configuration, or is used from a new address, and when an inbox rule or an automation starts sending data outside the workspace (`ONESEND_SECURITY_ALERTS`, on by default). A leaked key must not be able to hide what it does, so:

- **Delivery.** An alert goes through the workspace's own providers when it can really deliver. When it cannot (only the Sandbox, Sandbox mode, paused providers), it goes through the server's alert mailer (`ONESEND_ALERT_SMTP_URL`) when one is set. Every alert is also shown to the owners in the dashboard, as a banner until they mark it read (`GET /v1/security/alerts`, `POST /v1/security/alerts/acknowledge`: owners, signed in), and recorded in the audit log as `security.alert`.
- **What keys cannot do.** Sandbox mode and pausing a sending provider need a signed-in admin (API keys: 403 `session_required`; resuming works with an admin key). System email ignores suppressions added by hand, by import or through the API; only a hard bounce or a complaint reported by a provider stops it. API keys cannot cancel system email (403 `system_email`). An invitation's link is returned only to a signed-in admin, never to an API key.
- **Throttling.** At most one "new address" and one "configuration change" email per key per hour, at most 20 "key created" alerts and 30 alerts in all per workspace per hour. What is held back is never dropped: it is counted, and one digest email with the counts goes out when the hour ends.

<a id="request-limits"></a>
## Request limits

- Request bodies are limited to 1 MB by default; 15 MB for `POST /v1/emails`, `/v1/emails/batch` and inbox replies (attachments), 50 MB for CSV imports, 30 MB for `/ingest`, and 5 MB for templates, campaigns and provider webhooks. Larger requests get 413 `payload_too_large`.
- Login is rate limited per client IP, and failed logins per account and client IP (10 attempts, then 1 every 90 seconds) and loosely per account (100 per hour). A successful login clears that client's limit, and a client that has signed in to the account before is not held back by the per-account limit, so someone guessing passwords cannot lock the owner out. Sign-up is limited per client IP, and `POST /t/conversion` per key and IP. Limited requests get 429 with a `Retry-After` header. Behind a reverse proxy, set `ONESEND_TRUST_PROXY=true` so limits apply per client rather than to the proxy's address. With several processes, set `ONESEND_RATE_LIMITER=database` so they share the counts.
- API keys with `limits.perHour` or `limits.perDay` are limited per clock hour and UTC day in every edition (429 `key_rate_limited` with `Retry-After`), and keys with a `recipientAllowlist` can only send to those domains and addresses (403 `recipient_not_allowed`). A send refused for any other reason (a missing subject, an attachment that cannot be fetched) does not use a slot.
- With `ONESEND_RATE_LIMITER=database`, a database error does not lift the limits: that process falls back to its own in-memory limiter until the database answers again.
- The client address is the TCP peer, or `X-Forwarded-For` with `ONESEND_TRUST_PROXY`. `CF-Connecting-IP` is used only on the Cloudflare edition, where Cloudflare sets it; anywhere else a client could send it.
- Sending providers, routing policies and domains are read from a short cache (5 seconds) per process or Workers isolate. A provider you pause or delete stops being used at once by the process that handled the change; other processes or isolates can still use it for up to 5 seconds.

<a id="upgrading"></a>
## Upgrading

1. Read the release notes for the version you are moving to.
2. Back up the database and `ONESEND_SECRET` (see [Backups](#backups)).
3. Get the new version and rebuild:
   - From a download (the self-hosted license): download the new release with your license key on the website's self-host page ([onesend.email/self-host/#download](https://onesend.email/self-host/#download)), check its SHA-256 (`shasum -a 256 <file>`), and unpack it next to the old folder. Copy your `.env` across (and the data folder, when it is inside the old one). Then:
     - Node.js: `npm install` and `npm run build:web`, then restart the server from the new folder.
     - Docker: `docker compose up -d --build` in the new folder. The data stays in its volume.
   - From a clone of the repository: `git pull`, then `npm install` and `npm run build:web` and restart (Docker: `git pull`, then `docker compose up -d --build`).
4. Migrations run automatically at startup. The log lists the migrations it applied, for example `applied 0003_…`.
5. Check `GET /healthz` and send a test email.

Downgrades are not supported: migrations are not reversible. To go back, restore the backup taken in step 2 and run the previous version.

With several processes on one database, stop all of them before starting the new version, so that only one process runs migrations.

<a id="upgrading-from-openemail"></a>
### Upgrading from OneSend

OneSend was called OneSend before. Most of what an older install has keeps working, for a while; a few things need to be renamed by you. Do these before 2027-03-01, when the compatibility below ends.

- **Settings.** `OPENEMAIL_*` variables are not read any more: each one has a new name with `ONESEND_` (`OPENEMAIL_SECRET` → `ONESEND_SECRET`, `OPENEMAIL_PUBLIC_URL` → `ONESEND_PUBLIC_URL`, `OPENEMAIL_SECRET_FILE` → `ONESEND_SECRET_FILE`, and so on), in `.env`, `docker-compose.yml` or your secret manager. So that an upgraded server never runs without its settings, it refuses to start with `NODE_ENV=production` while an `OPENEMAIL_*` setting is set and its `ONESEND_*` name is not, and the message lists each one with its new name; in development it starts and warns. Once the new name is set too, the server starts, uses the new name and warns about the old one. So there is no downtime if you upgrade in this order: add the `ONESEND_*` names next to the old ones (same values), deploy, then remove the `OPENEMAIL_*` names. Variables that are not settings are ignored, such as those Kubernetes and Docker add for a Service or container named `openemail` (`OPENEMAIL_SERVICE_HOST`, `OPENEMAIL_PORT_3000_TCP_ADDR`…). Rename `openemail.config.json` to `onesend.config.json` too (the server warns when it finds only the old file).
- **Docker Compose.** The Compose service is still called `openemail`, as is the volume, so `docker compose up -d --build` replaces the old container instead of starting a second one next to it. Keep that name in your own Compose files and commands (`docker compose exec openemail …`). If you ran a Compose file in which the service was called `onesend`, `docker compose up -d --build --remove-orphans` removes the container left over from it. With the Postgres overlay, add `POSTGRES_USER=openemail` and `POSTGRES_DB=openemail` to `.env` (or the names your database has): the database keeps the role and database it was created with, and the healthcheck uses these names.
- **Data.** The SQLite file `openemail.db` is adopted as `onesend.db` (with its WAL files), and the migrations table `_openemail_migrations` becomes `_onesend_migrations`, on the first start. Docker: the volume is still called `openemail-data` on purpose; do not rename it, or the server starts on an empty volume. With the Postgres overlay, keep your `secrets/database_url` (user and database `openemail`).
- **Domain ownership.** The TXT record is now `_onesend-verify.<domain>` with the value `os-verify=…` (the token is the same). Domains verified with the old `_openemail-verify.<domain>` / `oe-verify=…` record stay verified: DNS checks accept the old record until 2027-03-01, and the domain page shows the new record to publish. Publish it, then remove the old one once it is found. A DNS host connection writes it for you.
- **Inbound Email Worker.** A worker deployed before the rename sends `X-OpenEmail-Ingest-Secret`, `X-OpenEmail-Envelope-To` and other `X-OpenEmail-*` headers; the server accepts them until 2027-03-01. Redeploy the Email Worker and rename its vars `OPENEMAIL_URL` and `OPENEMAIL_INGEST_SECRET` to `ONESEND_URL` and `ONESEND_INGEST_SECRET` (the new worker still reads the old names, and logs a warning, until then).
- **Webhooks.** Deliveries carry both `X-OneSend-Signature` / `X-OneSend-Timestamp` (and `-Event`, `-Delivery`) and the same values as `X-OpenEmail-*`, until 2027-03-01. Change your receivers to read `X-OneSend-*` (see [Webhooks](https://onesend.email/docs/webhooks/#verify-signatures)).
- **Sign-in.** The dashboard cookie is `onesend_session`; the old `oe_session` is still read until 2027-03-01 and is removed at the next sign-in or sign-out.
- **Conversion script.** `/t/oe.js` is still served and defines `window.openemail` as well as `window.onesend`; switch your pages to `/t/onesend.js` and `onesend.convert()`.

<a id="the-workspace"></a>
## The workspace: inbox, calendar, booking pages and drive

The self-hosted edition includes the whole workspace: workspace mailboxes (addresses, catch-all, plus addressing, several domains per mailbox), [mailbox access](https://onesend.email/docs/inbox/#who-can-read-a-mailbox), inbox rules, the [spam filter](https://onesend.email/docs/inbox/#spam-filter), Trash and Spam retention, [mail import](https://onesend.email/docs/inbox/#importing-mail), the [unified inbox](https://onesend.email/docs/unified-inbox/) with connected accounts (IMAP, Gmail, Microsoft 365 and Outlook.com, Zoho), [mail apps](https://onesend.email/docs/mail-clients/) over IMAP, POP3 and SMTP, the [agent inbox](https://onesend.email/docs/agent-inbox/), inbox AI, the MCP inbox tools, the [calendar](https://onesend.email/docs/calendar/) with invitations by email, [booking pages](https://onesend.email/docs/booking/) and the [drive](https://onesend.email/docs/drive/). It is on by default (`ONESEND_INBOX=on`); sending works the same with it off.

What each part needs:

| Part | Needs |
|---|---|
| Receiving mail | A domain with inbound turned on and its ownership TXT record verified, and its MX pointed at one of the [receivers](#receiving-mail) |
| Attachments, mail import, drive | File storage: the data folder (`ONESEND_DATA_DIR`) on Node, an R2 bucket bound as `FILES` on Cloudflare. Back it up with the database |
| Booking pages, drive links, calendar feeds and invitation answers | A public HTTPS `ONESEND_PUBLIC_URL`: links are `<public URL>/book/<handle>`, `/share/<token>`, `/calendar/feed/<token>.ics` and `/calendar/rsvp` |
| Invitations, reminders, booking confirmations, replies | A sending provider (live email needs the [license key](#license-key)) |
| Mail apps | The IMAP/POP ports on Node, with a TLS certificate before they are exposed ([Ports for the workspace](#ports-for-the-workspace)) |
| Connected Gmail, Microsoft and Zoho mailboxes | Your own [OAuth apps](https://onesend.email/docs/oauth-apps/) (IMAP accounts with an app password need nothing) |

<a id="workspace-without-a-license-key"></a>
### Without a license key

On a server that needs a [license key](#license-key), the workspace behaves like live sending: without an active key it is locked, and adding a key under **Settings → License** unlocks it at once.

- The dashboard's inbox, calendar, drive and connected accounts pages show one card that says so and links to Settings → License. The API (`/v1/inbox`, `/v1/agent`, `/v1/accounts`, `/v1/inbound-endpoints`, `/v1/calendar`, `/v1/booking`, `/v1/drive`, the inbox AI endpoints) answers signed-in callers **402** `license_required` with `buyUrl`; callers without credentials get the usual 401. The MCP inbox tools get the same 402.
- Public pages (booking pages, drive links, calendar feeds, forward confirmations) answer 404, like a page that does not exist.
- Mail apps cannot sign in with an app password (IMAP, POP3 and SMTP say why), open sessions end, connected accounts are not synced (their mail stays at the provider and is synced once a key is added), calendar reminders do not fire, and the assistant reads no received mail.
- **Nothing is lost.** Receiving goes on: the SMTP receiver, Cloudflare Email Routing, the standalone Email Worker and provider inbound webhooks keep storing mail, and invitation answers are recorded. The lock deletes nothing; retention you set (Trash and Spam, expiring mailboxes, the drive's Trash) keeps applying, as retention does for sent mail.

There is no trial of the workspace on a self-hosted server: evaluate it on a development build or a server without a license public key, where nothing is locked.

<a id="receiving-mail"></a>
### Receiving mail

Add the domain under **Senders & domains** with inbound mail turned on (`inbound`: `builtin` or `cloudflare`) and publish its `_onesend-verify` TXT record: mail is delivered only for domains whose ownership is verified. Then create mailboxes under **Inbox → Addresses**: an address, a catch-all `*`, or plus addressing. Mail for an address that no mailbox takes (and no catch-all) is still kept in the workspace's inbox, as mail without a mailbox. The receivers:

1. **Built-in receiver (Node, Docker).** Point the domain's MX record at this server (`mail.example.com`, priority 10) and forward port 25 to `ONESEND_SMTP_IN_PORT` (default 2525; Compose publishes `2525:2525`, map `25:2525` on a public server). Many hosting providers block port 25 until you ask; check before you rely on it.
2. **Cloudflare Email Routing.** No inbound port needed. On the [Cloudflare edition](https://onesend.email/docs/cloudflare/#receiving-mail-with-email-routing) the Worker itself receives the mail. With OneSend on Node, deploy the standalone Email Worker that ships with the self-hosted edition (the `@onesend/inbound-cf` workspace; its README has the steps): it posts each message to `/ingest/cloudflare` with `ONESEND_INGEST_SECRET`, so set the same secret on the server and as the Worker's secret, and point the Worker's `ONESEND_URL` at your server's public URL. A 503 `ingest_disabled` means the server has no `ONESEND_INGEST_SECRET`; a 401 means the two values differ.
3. **Provider inbound.** Resend, Mailgun routes, Amazon SES receipt rules, Postmark and SendGrid Inbound Parse post received mail to a per-connection webhook URL. See [Unified inbox](https://onesend.email/docs/unified-inbox/#provider-inbound).

A mailbox can forward received mail to at most 10 addresses. Mail marked as spam, mail that fails both SPF and DKIM, mail over 10 MB and mail that OneSend has already forwarded is stored in the inbox but not forwarded.

<a id="connected-accounts"></a>
### Connected accounts

The settings of connected accounts and of the rest of the workspace:

| Variable | Default | Purpose |
|---|---|---|
| `ONESEND_INBOX` | `on` (`off` when `ONESEND_EDITION=cloud`) | `on` or `off`. Every workspace feature: inbox routes and workspace mailboxes, calendar, booking pages and drive, provider inbound connections and their webhooks (`/ingest`), the SMTP receiver (`ONESEND_SMTP_IN_PORT`), the IMAP and POP servers, sign-in to SMTP submission with mailbox app passwords, the agent inbox, the inbox AI features and the MCP inbox tools. With `off` those routes answer 403 `inbox_unavailable` and lists answer `{ "data": [], "available": false }`; connected accounts are off too. Sending (including SMTP submission with an API key) is not affected. Non-secret (`inbox` in `onesend.config.json`). |
| `ONESEND_CONNECTED_ACCOUNTS` | `on` (`off` when `ONESEND_EDITION=cloud`) | `on` or `off`. Whether members can connect personal mailboxes (Gmail, Outlook, Zoho, any IMAP server). With `off`, every `/v1/accounts` endpoint except the list answers 403 `connected_accounts_unavailable`, mailbox OAuth and push notifications are off, no sync or IMAP IDLE runs, personal-mailbox sending providers (`gmail_api`, `microsoft_graph`, `zoho_mail_api`, `mailbox`) cannot be created or resumed, and existing accounts and those providers are paused at startup (nothing is deleted). Provider inbound for your own domains, the agent inbox and the IMAP/POP servers for workspace mailboxes are not affected. Non-secret (`connectedAccounts`). See [Unified inbox](https://onesend.email/docs/unified-inbox/#availability). |
| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | none | OAuth client for "Connect Google" (Gmail API sync and sending). See [OAuth apps](https://onesend.email/docs/oauth-apps/#google). |
| `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET` | none | OAuth client for "Connect Microsoft" (Outlook.com and Microsoft 365 through Microsoft Graph). See [OAuth apps](https://onesend.email/docs/oauth-apps/#microsoft). |
| `MICROSOFT_CLIENT_PUBLIC` | `false` | `true` for a public client (Microsoft "Mobile and desktop applications"): no `MICROSOFT_CLIENT_SECRET`, PKCE only. Not together with a secret. See [OAuth apps](https://onesend.email/docs/oauth-apps/). |
| `MICROSOFT_TENANT` | `common` | `common`, `consumers`, `organizations`, a tenant ID or a tenant domain. |
| `ZOHO_CLIENT_ID`, `ZOHO_CLIENT_SECRET` | none | OAuth client for "Connect Zoho" (Zoho Mail API). See [OAuth apps](https://onesend.email/docs/oauth-apps/#zoho). |
| `ZOHO_CLIENT_PUBLIC` | `false` | `true` for a public Zoho client (mobile or desktop app): no `ZOHO_CLIENT_SECRET`, PKCE only. |
| `ZOHO_ACCOUNTS_SERVER` | `https://accounts.zoho.com` | Where Zoho sign-in starts, for example `https://accounts.zoho.eu`. |
| `ONESEND_ACCOUNTS_IDLE_MAX` | `100` | Most IMAP IDLE connections one worker process keeps open for near-real-time sync. Accounts over the limit are polled. `0` turns IDLE off. |
| `ONESEND_INBOX_ATTACHMENTS_MAX_MB` | `25` | Largest total size of the files on one message written in the inbox (compose, reply, outbox), 1 to 25. From a mailbox address each file is also at most 10 MB, as with `POST /v1/emails`. Non-secret (`inboxAttachmentsMaxMb`). |
| `ONESEND_INBOX_IMPORT_MAX_MB` | `10240` | Largest upload of one [mail import](https://onesend.email/docs/inbox/#importing-mail) (.eml and .mbox files together), 1 to 102400. Each message in it is at most 25 MB. Non-secret (`inboxImportMaxMb`). |
| `ONESEND_INBOX_IMPORT_MEMBER_MAX_MB` | `1024` | Largest mail import a member who is not a workspace owner or admin may start, 1 to 102400. Non-secret (`inboxImportMemberMaxMb`). |
| `ONESEND_INBOX_IMPORT_DAILY_MB` | `20480` | Bytes one workspace may upload for mail imports in 24 hours, 1 to 1048576. Non-secret (`inboxImportDailyMb`). |
| `ONESEND_INBOX_IMPORT_MAX_MESSAGES` | `200000` | Messages read from one mail import; past it the import fails `too_many_messages` (what was imported stays), 1 to 10000000. Non-secret (`inboxImportMaxMessages`). |
| `ONESEND_DRIVE_MAX_FILE_MB` | `5120` | Largest file in the [drive](https://onesend.email/docs/drive/), 1 to 102400. Larger uploads are refused at the start (413 `file_too_large`). Non-secret (`driveMaxFileMb`). |
| `ONESEND_DRIVE_QUOTA_GB` | `100` | Storage of one workspace's drives, every kept version included, 1 to 100000. An upload reserves its size before the first chunk (413 `drive_quota_exceeded`). Non-secret (`driveQuotaGb`). |
| `ONESEND_DRIVE_VERSIONS` | `10` | Versions kept of each drive file (uploading the same name again adds one; the oldest go), 1 to 100. Non-secret (`driveVersions`). |
| `ONESEND_BOOKING_DAILY_EMAILS` | `500` | Booking mails (invitations, host notices, cancellations) one workspace's [booking pages](https://onesend.email/docs/booking/#abuse-protection) send a day, 1 to 1000000. Past it, the pages take no bookings until the next day (429 `too_many_bookings`). Non-secret (`bookingDailyEmails`). |

IMAP accounts with an app password need no variables. Several processes can share one PostgreSQL database: the job queue claims work with `FOR UPDATE SKIP LOCKED`, so each job runs once, and IMAP IDLE runs only in processes with the worker. With SQLite, run a single process.

<a id="ports-for-the-workspace"></a>
### Ports for the workspace

All optional; the dashboard and the API need only `PORT`.

| Port (default) | Variable | What | Expose it |
|---|---|---|---|
| 2525 | `ONESEND_SMTP_IN_PORT` | Inbound SMTP, the MX target | As 25 on a public address when the domain's MX points here; not needed with Cloudflare Email Routing or provider inbound |
| 2587 | `ONESEND_SMTP_PORT` | SMTP submission: API keys, and mail apps with an app password | With `ONESEND_SMTP_TLS_KEY`/`CERT` set (as 587) |
| 1143, 1993 | `ONESEND_IMAP_PORT`, `ONESEND_IMAPS_PORT` | IMAP with STARTTLS, IMAP over TLS | With a certificate (as 143 and 993). IMAPS opens only with one |
| 1110, 1995 | `ONESEND_POP3_PORT`, `ONESEND_POP3S_PORT` | POP3 with STLS, POP3 over TLS | With a certificate (as 110 and 995) |

The IMAP and POP servers use `ONESEND_IMAP_TLS_KEY`/`CERT`, or the SMTP certificate. Without TLS they accept sign-in only from loopback. In `docker-compose.yml` the IMAPS and POP3S mappings are commented out: uncomment them once the certificate is set. See [Mail apps](https://onesend.email/docs/mail-clients/) for the settings people enter and `ONESEND_MAIL_PUBLIC_PORTS` behind a proxy or NAT.

<a id="running-as-a-hosted-service-saas"></a>
## License key

Self-hosted OneSend is sold with a license key: one payment, one installation, every update included. Without a key the server runs for evaluation and development: the dashboard, test API keys and workspaces in Sandbox mode all work, and live sends answer **402** with code `license_required` (with `buyUrl`, the website's pricing page). Campaigns and automations are refused with the same 402 before they start, a form's double opt-in email is not sent (the form's submissions show why), and a scheduled email is not delivered once the key is gone. The workspace (inbox, calendar, booking pages, drive) is locked meanwhile, and receiving goes on: see [Without a license key](#workspace-without-a-license-key).

- **Who manages the key.** The license belongs to the server, not to a workspace: on a server with several workspaces, a workspace's owner or admin must not be able to remove or replace it. With `ONESEND_ADMIN_EMAILS` set, only those instance admins can add, check, remove or move the key (signed in, with a verified address and two-factor authentication); without it, only the owner of the server's first workspace (the person who set it up). Always signed in: API keys cannot change the license. Others see the status, without the licensee's email. `GET /v1/license` says `canManage`.
- **Add the key** in the dashboard under **Settings → License**, or set `ONESEND_LICENSE_KEY` before you deploy: the server activates it on first use. Either way the key is stored encrypted.
- **One installation per key.** An installation is one deployment with one database (one Cloudflare account, one server or one cluster). Activating the key on a second installation answers `seat_limit`. To move it, choose **Remove from this server** on the old one (`DELETE /v1/license`), then add it on the new one.
- **Removing needs the license server.** While the old server cannot reach the license server, removing the key is refused (`409 license_server_unreachable`), because its seat would stay taken. `DELETE /v1/license?force=true` removes it anyway; the seat then stays taken until you free it from the new server.
- **A lost installation.** If the old server is gone (or removed its key while offline), the new server's `seat_limit` error lists the installation that uses the key (`details.activations`). Free that seat under **Settings → License** (`POST /v1/license/free-other` with `{ key, activationId }`), then activate the key.
- **Removing a key is remembered.** After an owner removed the key, `ONESEND_LICENSE_KEY` is not activated again on its own; add the key in the dashboard to use it again.
- **Offline.** The server checks its license with the license server every few days. If it cannot reach it, it keeps working for up to 30 days. A refunded key stops live email at the next check.
- **Mac app keys** do not activate a server, and self-hosted keys do not activate the Mac app (`wrong_product`).

| Variable | Default | |
|---|---|---|
| `ONESEND_LICENSE_KEY` | none | **Secret.** Activated on first use when no key was added in the dashboard. |
| `ONESEND_LICENSE_SERVER` | the cloud's URL | Where keys are activated and checked. |
| `ONESEND_LICENSE_PUBLIC_KEY` | the build's key | The license server's Ed25519 public key. Builds without one do not check. |
| `ONESEND_SITE_URL` | `https://onesend.email` | The website: the dashboard's and the 402 error's link to buy a key is `<site>/pricing/#self-hosted`. |


The API: `GET /v1/license` (status, every member; the licensee's email and `canManage` for whoever manages the key), and, for whoever manages it (above): `POST /v1/license` `{ key }`, `POST /v1/license/refresh`, `DELETE /v1/license` and `POST /v1/license/free-other` `{ key, activationId }`.

## Sending from the Mac app through your server

The Mac app can send through your self-hosted server instead of the providers set up on the Mac. Create a live API key with full access on the server (Settings, API keys), then in the Mac app open Settings, Cloud and server, Your own server, and enter the server's address and the key. Mail from the Mac then uses the server's domains, providers, routing, templates and logs; manage them on the server. The server must be reachable over HTTPS at a public address.

## Running as a hosted service (SaaS)

To offer OneSend to other people, with accounts you do not create yourself:

- **Use PostgreSQL.** SQLite and PGlite support one server process and one machine. PostgreSQL (your own, Neon, Supabase, RDS) is required for several processes and gives you managed backups. In `npm run setup`, choose production and PostgreSQL, or set `DATABASE_URL` in your platform's secret store.
- **Run several instances.** Every process can serve HTTP and run the worker: the job queue claims jobs with `FOR UPDATE SKIP LOCKED`, so each job runs once. Use `ONESEND_WORKER=off` for API-only processes and run the worker in others when you want to scale them separately. All instances need the same `ONESEND_SECRET`, `ONESEND_PUBLIC_URL` and `DATABASE_URL`. Put a load balancer or reverse proxy in front and set `ONESEND_TRUST_PROXY`.
- **Open sign-up.** Set `ONESEND_SIGNUP=open`: anyone can create an account, and each account gets its own workspace with its own providers, domains, contacts and logs. Create your own owner account first. On the cloud edition (`ONESEND_EDITION=cloud`) with the cloud plans off (`ONESEND_CLOUD_PLANS`, the default), open sign-up has no plan limits and no usage limits, so the server refuses to start in production with `ONESEND_SIGNUP=open` (and warns elsewhere) unless you set `ONESEND_ALLOW_OPEN_SIGNUP_WITHOUT_LIMITS=true`. Use `invite` or `closed` until then.
- **Rate limits.** Set `ONESEND_RATE_LIMITER=database` (the default with `ONESEND_EDITION=cloud`) so login, sign-up and other limits are shared by every instance. With `memory`, each process counts separately, so also limit `/v1/auth/*` at your proxy.
- **Back up the database and `ONESEND_SECRET` together**, and test a restore (see [Backups](#backups)). Keep the secret in a secret manager; every instance reads it from `ONESEND_SECRET` or `ONESEND_SECRET_FILE`.
- **Scaling.** Increase `DATABASE_POOL` (per process) within your database's connection limit; with a serverless PostgreSQL use its pooled connection string. Raise `ONESEND_WORKER_CONCURRENCY` for more parallel sends per worker. Inbound mail through the Cloudflare Worker avoids running port 25 yourself.
- **Moving from SQLite.** Stop the server, copy the data with `npm run db:copy -- --from sqlite:./.data/onesend.db --to "$DATABASE_URL"` (see [Moving to another database](#moving-to-another-database)), point `DATABASE_URL` at PostgreSQL and start the instances.
- **Upgrades.** Stop all instances before starting a new version, so only one process runs the migrations (see [Upgrading](#upgrading)).

With `NODE_ENV=production` and SQLite, the server logs a warning at startup that SQLite supports a single process.
