This is the multi-page printable view of this section.
Documentation
- 1: Quick Start
- 2: Features
- 3: Tokens & Auth
- 4: CLI
- 5: Backup & Restore
- 6: REST API Basics
- 7: Supported Providers
- 8: Accounts & Autodetection
- 9: Mailboxes & Sync
- 10: Messages & Flags
- 11: Search
- 12: Sending Mail
- 13: Settings
- 14: MCP Server
- 15: Security & Deployment
- 16: Architecture
Pigeon is a local-first email client in a single Go binary. It syncs IMAP accounts into SQLite and exposes them through a REST API, an MCP server and a command-line digest.
Start with the quick start, then jump to the guide for the feature you need. The REST API guides are split by business area.
- Quick Start — Install, run and add your first account
- Tokens & Auth — Manage API tokens for remote access
- CLI —
pigeon digestand other commands - Backup & Restore — Back up the database and secret key, and restore safely
- Supported Providers — Mailbox providers recognised out of the box
- REST API Basics — Base URL, authentication, errors and conventions
- Accounts & Autodetection — Create accounts and detect provider settings
- Mailboxes & Sync — Mailbox listing, counts and IMAP synchronization
- Messages & Flags — Read mail, fetch bodies and change flags
- Search — Search the local cache across accounts
- Sending Mail — Send over SMTP and archive to the Sent mailbox
- MCP Server — Connect AI clients over stdio or HTTP
- Security & Deployment — Encryption, tokens and running remotely
- Architecture — Components, data flow and storage layout
1 - Quick Start
Get Pigeon running and pull your first messages in a few minutes.
Install and run
One-line install on Linux (detects x86_64 / aarch64, downloads the latest
release into /usr/local/bin or ~/.local/bin):
Pin a version or directory with bash -s -- --version v0.1.0 --prefix ~/.local/bin.
Or build from source: make build && sudo install -m 0755 pigeon /usr/local/bin/.
Start the server:
API Token
On first start Pigeon creates ~/.pigeon, generates an encryption key
and prints an initial API token once:
Keep the token — the web UI and remote clients ask for it (requests from the loopback address are exempt).
Open the browser
Visit http://127.0.0.1:8787, paste the API token when prompted, then add your email account with its password (an app-specific password for Gmail, QQ Mail and 163). Pigeon detects the provider settings and loads the most recent week of mail.
2 - Features
Pigeon is a simple, beautiful, practical email client, with a REST API and MCP for AI agents. Everything below ships in one Go binary.
One binary, zero setup
- Single static binary. The web UI, REST API, MCP server and CLI live in one Go executable — no external database, no frontend build chain.
- One command to run.
pigeon serveopens the web UI athttp://127.0.0.1:8787; data lives in~/.pigeon. - One-line install. An install script downloads the latest release for Linux amd64/arm64 — see Quick Start.
Local-first
- Mail stays close. IMAP messages are cached in a local SQLite database, so cached mail can be browsed and searched offline.
- No middleman. Mail is fetched directly from your IMAP servers — no cloud relay and no telemetry.
- Live sync. Mailboxes auto-sync while the page is open; the interval is configurable from 30 seconds to 15 minutes, or off.
- Full history. The first sync pulls the most recent week; “Load more” then walks back day by day to older mail.
Three ways to use it
| Interface | Best for |
|---|---|
| Web UI | Browsing and reading mail in the browser |
| REST API | Scripts and integrations — curl-friendly JSON |
| MCP server | Claude Code, Claude Desktop and other MCP clients (stdio and Streamable HTTP, 8 mail tools) |
| CLI | pigeon digest prints an unread summary, with JSON output |
Web UI highlights
- Works out of the box. Sign in with just your email and password — the provider (Gmail, Outlook, QQ, 163 and more) is detected automatically.
- Configurable sender grouping. Turn on “Group messages by sender” in Settings to collapse the list into one row per sender; open a sender to see their messages in the reader pane and expand any of them in place. The switch is stored server-side and shared by every browser.
- Cross-account search. The search box above the message list searches
every account’s cached mail at once. Metadata (subject, sender, recipients)
is matched by default for speed; an advanced panel adds sender, subject and
date filters plus an opt-in body search. Results carry a per-account chip.
Press
/anywhere to jump to the search box. - Remote-image privacy. Remote images are blocked by default; a banner offers one-click reveal, and a setting can auto-load them instead.
- Attachments on demand. Attachment names and sizes render under the message body; click one to download it. Files are cached locally during sync (up to 25 MB each, larger ones skipped), so message detail stays fast and downloads never re-fetch from the provider.
- Account display names. The Settings → Accounts tab sets a display name per account; it appears in the sidebar and as the sender name of outgoing mail.
- Bilingual and themed. English and Chinese UI, light and dark themes and a mobile-friendly layout.
- Keyboard navigation. Browse with the arrow keys instead of the mouse: ↑/↓ move through the message list (or sender groups when grouping is on) and the reader follows; Enter/Space opens a focused sender group; Esc closes the settings and add-account dialogs or exits search.
- Shared settings. Language, sync interval, image policy and sender grouping are stored server-side and shared by every browser.
Security
- Account passwords are encrypted with AES-256-GCM; API tokens are stored as SHA-256 hashes only.
- Loopback requests need no token; remote access requires a Bearer token.
- Message HTML renders in a sandboxed iframe with a strict CSP.
See Security & Deployment for the details.
3 - Tokens & Auth
API tokens authenticate clients that do not connect from the loopback address. They are shown once at creation; only a SHA-256 hash is stored.
The token object
| Field | Description |
|---|---|
id |
Opaque string used to revoke the token |
name |
Label of 1–64 characters drawn from letters, digits, - and _, such as agent or ci |
createdAt |
Unix seconds |
lastUsedAt |
Unix seconds of the last successful authentication, 0 if never used |
Tokens themselves always start with pigeon_ and are only returned by the
creation call.
Create a token
pigeon serve also creates an initial token on first start and prints it in
the log exactly once. This only happens while the tokens table is empty —
later starts never re-create it. If every token is deleted, the next start
generates a fresh initial token.
The REST API is equivalent — POST /api/tokens:
Store the token value now — it cannot be retrieved again. If it is lost,
revoke the token and create a new one.
List tokens
The plaintext token is never shown: the database stores only its SHA-256
hash, so the secret cannot be recovered after creation. Use the id column
to revoke a token; if a secret is lost, delete the token and create a new
one.
GET /api/tokens returns the same metadata as an array of token objects
(never the secrets):
Revoke a token
The argument is matched against ids first; when no id matches it is treated as a name and every token with that name is revoked.
DELETE /api/tokens/{id} returns 204. Revocation is immediate; clients
using that token start receiving 401.
Using a token
Send it as a bearer token on every request:
The MCP HTTP endpoint uses the same header:
Authentication rules
| Source | Requirement |
|---|---|
Loopback (127.0.0.1, ::1) |
No token needed |
| Any other address | Valid Authorization: Bearer pigeon_… header |
/api/health |
Always public |
The loopback exemption is based on the TCP remote address, not on
X-Forwarded-For. When Pigeon runs behind a reverse proxy on the same host,
the proxy’s loopback connection is trusted — protect the site at the proxy
layer or run Pigeon in a network namespace/container where remote addresses
are not loopback. See Security & Deployment.
4 - CLI
The pigeon binary is both the server and a small mail client.
Running pigeon without a subcommand is the same as pigeon serve.
digest
Prints a mailbox summary from the local cache — no server required, it opens the data directory directly.
| Flag | Default | Description |
|---|---|---|
--account |
the only account | Account ID, email or name |
--mailbox |
INBOX |
Mailbox path or display name |
--limit |
10 |
Number of messages to show |
--unread |
— | Only unread messages |
--sync |
— | Sync before printing; falls back to cached mail if sync fails |
--json |
— | Emit JSON instead of a table |
--data |
~/.pigeon |
Data directory |
Sample output:
● marks unread and ★ marks starred messages. With --json the output is:
backup
pigeon backup writes a gzip-compressed tar archive containing a consistent
pigeon.db snapshot, the secret.key used to decrypt account passwords, and a
manifest.json. See Backup & Restore for flags, restore steps
and security notes.
restore
pigeon restore -f FILE verifies a backup archive and installs its database
and secret key into the data directory. See Backup & Restore
for details and restrictions.
token
The same operations are available over the REST API; see Tokens & Auth.
Environment variables
| Variable | Default | Description |
|---|---|---|
PIGEON_ADDR |
127.0.0.1:8787 |
Listen address for serve |
PIGEON_DATA |
OS config dir + /pigeon |
Data directory |
PIGEON_DEBUG |
— | Any non-empty value enables debug logging |
Flags take precedence over environment variables, which take precedence over defaults.
serve, mcp and digest --sync also write their logs to
<data-dir>/logs/pigeon-YYYY-MM-DD.log — one file per local date, alongside
stderr output.
To run a second instance alongside the default one, override the address (and optionally the data directory):
5 - Backup & Restore
pigeon backup writes a gzip-compressed tar archive with everything needed to
restore an instance. It is a CLI-only command — no server or API is involved;
like pigeon digest, it opens the data directory directly.
What’s inside
| File | Contents |
|---|---|
pigeon.db |
Consistent SQLite snapshot: accounts, cached mail, attachments, settings and tokens |
secret.key |
The AES-256-GCM key that decrypts account passwords |
manifest.json |
Archive format version, app version, creation time and a SHA-256 checksum per file |
Run logs under <data-dir>/logs are not included.
The snapshot uses SQLite’s VACUUM INTO, so the server can keep running during
the backup. Prefer quiet periods for large mailboxes — a long snapshot delays
WAL checkpoints.
Flags
| Flag | Default | Description |
|---|---|---|
-o |
./pigeon-backup-<timestamp>.tar.gz |
Output file; must not exist |
--data |
~/.pigeon |
Data directory |
The command refuses to run when pigeon.db or secret.key is missing: creating
a fresh key for an existing database would produce an archive whose passwords
can never be decrypted again. The output file is created with 0600
permissions, an existing file is never overwritten, and a failed run removes
its partial output.
Security
The archive contains the key that decrypts your mail passwords — treat it
like a password. Encrypt it (for example with age or gpg) before storing
it off-site, and check the checksums in manifest.json after moving it:
Restoring a backup
Use pigeon restore to unpack a backup back into a data directory:
It verifies every file against the SHA-256 checksums in manifest.json,
checks that secret.key is 32 bytes and that the database passes SQLite’s
integrity_check, and only then installs the files. The target directory must
not already contain pigeon.db, secret.key or leftover -wal/-shm files —
the command refuses rather than overwrite. A missing data directory is created
with 0700.
A typical restore over an existing instance:
-
Stop the running server (
pigeon serve/pigeon mcp). -
Move or delete the old state files:
-
Restore and start again:
The archive keeps each file’s 0600 mode; run the restore as the same user
that runs Pigeon. If you prefer, the archive is a plain tar.gz and can still
be unpacked by hand.
6 - REST API Basics
Everything the web UI and the CLI can do is available over JSON HTTP. The API is designed to be called by scripts, terminal users and AI agents.
Base URL
pigeon serve listens on http://127.0.0.1:8787 by default. Change it with
--addr or the PIGEON_ADDR environment variable:
To call the API from other machines, bind an address they can reach:
Remote requests must then carry a bearer token; see Authentication below and Security & Deployment for the deployment trade-offs.
| Path | Purpose |
|---|---|
/api/* |
REST API (this guide) |
/mcp |
MCP over Streamable HTTP |
/ |
Embedded web UI (mailbox login and message reader) |
Conventions
- Request and response bodies are UTF-8 JSON. Send
Content-Type: application/json. - Timestamps are Unix seconds (integers), not strings.
- Addresses are objects:
{"name": "Ada", "address": "ada@example.com"}. - Resource IDs are integers except token IDs, which are opaque strings.
- List endpoints return arrays, never
null.
Authentication
Local requests from a loopback address (127.0.0.1, ::1) are allowed without
credentials — convenient for development and for agents running on the same
machine. Every other request must carry a bearer token:
Create tokens with the CLI or the API:
See Tokens & Auth for the token endpoints and Security & Deployment for reverse-proxy caveats.
Errors
Errors always use the same shape:
| Status | Meaning |
|---|---|
400 |
Invalid JSON, missing or invalid parameters |
401 |
Missing or invalid bearer token (non-loopback request) |
404 |
Unknown account, mailbox, message or token |
405 |
Wrong HTTP method for the route |
500 |
Internal failure (database, encryption) |
502 |
Upstream IMAP/SMTP failure (connection, login, network) |
502 responses mean Pigeon could not reach or authenticate with the mail
server; the request may succeed later once connectivity is restored.
CORS
The server answers OPTIONS preflight requests with 204 and allows any
origin, the Authorization and Content-Type headers, and the methods GET,
POST, PUT, PATCH, DELETE. Authentication is still enforced on
non-loopback requests.
Endpoint map
| Area | Endpoints | Guide |
|---|---|---|
| Health & meta | GET /api/health, GET /api/meta |
this page |
| Accounts | GET/POST /api/accounts, PUT/PATCH/DELETE /api/accounts/{id} |
Accounts |
| Provider detection | GET /api/detect?email= |
Accounts |
| Mailboxes & sync | GET /api/accounts/{id}/mailboxes, POST /api/accounts/{id}/sync, POST /api/mailboxes/{id}/fetch-older |
Mailboxes & Sync |
| Messages | GET /api/mailboxes/{id}/messages, GET /api/messages/{id}, POST /api/messages/{id}/flags, GET /api/attachments/{id} |
Messages & Flags |
| Search | GET /api/search?q= (also from, subject, since, until, body, account, limit, offset) |
Search |
| Sending | POST /api/accounts/{id}/send |
Sending Mail |
| Tokens | GET/POST /api/tokens, DELETE /api/tokens/{id} |
Tokens & Auth |
| Settings | GET/PUT /api/settings |
Settings |
Health and meta
GET /api/health is public and reports liveness:
GET /api/meta requires authentication and tells a client how it was seen:
loopback is false when the request arrived over the network; a web client
can use it to decide whether to show a token login screen.
7 - Supported Providers
Pigeon works with any standard IMAP/SMTP provider. These are recognised out of the box via the bundled Thunderbird ISPDB database and MX lookup:
| Provider | Example domains |
|---|---|
| Gmail | gmail.com, googlemail.com |
| Outlook.com / Microsoft 365 | outlook.com, hotmail.com, live.com, msn.com |
| Yahoo Mail | yahoo.com, ymail.com, rocketmail.com |
| iCloud Mail | icloud.com, me.com, mac.com |
| AOL Mail | aol.com |
| GMX | gmx.com, gmx.net |
| mail.com | mail.com |
| Mail.ru | mail.ru, inbox.ru, bk.ru, list.ru |
| Yandex Mail | yandex.ru, yandex.com, ya.ru |
| Zoho Mail | zoho.com, zoho.eu, zoho.com.cn |
| Fastmail | fastmail.com |
| Posteo | posteo.de |
| WEB.DE | web.de |
| Naver Mail | naver.com |
| Seznam Mail | seznam.cz, email.cz |
| QQ Mail | qq.com |
| NetEase Mail | 163.com, 126.com, yeah.net |
Enterprise mail on your own domain is detected through MX records (Microsoft
365, NetEase Exmail, Alibaba Mail, Coremail, Sina Exmail, Zoho, Fastmail). Any
other domain falls back to imap.<domain> / smtp.<domain> on port 993/465,
and server settings can always be entered manually. See
Accounts & Autodetection for how detection works.
Gmail
Google no longer accepts your regular account password for IMAP/SMTP. Use an App Password instead:
- Turn on 2-Step Verification at myaccount.google.com/security. App Passwords are only available once it is enabled.
- Open myaccount.google.com/apppasswords (or Security → 2-Step Verification → App passwords).
- Name it
Pigeonand create it; Google shows a 16-character password likeabcd efgh ijkl mnop. - Sign in to Pigeon with your Gmail address and that 16-character password (the spaces are optional).
The same App Password covers both IMAP and SMTP, so receiving and sending work alike. On a Google Workspace (work or school) account the administrator may need to allow App Passwords first, and accounts enrolled in the Advanced Protection Program cannot create them. OAuth sign-in is not supported yet.
NetEase Mail (163.com, 126.com, yeah.net)
NetEase does not accept your account login password; it requires an authorization code (shown as an “app password”):
- Sign in to the NetEase webmail (mail.163.com, mail.126.com or the matching site for your domain).
- Open Settings → IMAP/SMTP and enable the IMAP/SMTP service. NetEase may ask you to verify with the Mail Master app first.
- Generate the authorization code and copy it.
- Paste that code into the password field when adding the account in Pigeon; the same code covers both receiving and sending.
If you regenerate or delete the code in webmail later, update the account password in Pigeon to match.
Other providers
Policies differ between providers and are not tested exhaustively here, but the pattern is usually the same: if sign-in fails with an authentication error, look for an app password / authorization code / third-party login option in the provider’s account security settings and use that instead of your login password. Enterprise domains managed by an administrator may also need IMAP enabled server-side (or an exception for app passwords) — ask the administrator if in doubt.
8 - Accounts & Autodetection
An account stores the IMAP and SMTP settings plus the encrypted password. Pigeon supports any standard IMAP/SMTP provider.
The account object
| Field | Description |
|---|---|
id |
Account ID used in other endpoints |
name |
Display name (defaults to the part of the email before @) |
email |
Mail address |
username |
IMAP/SMTP login (defaults to the email address) |
imapHost, imapPort, imapSecurity |
Incoming server; security is tls, starttls or none |
smtpHost, smtpPort, smtpSecurity |
Outgoing server; same security values |
sentMailbox |
Mailbox that receives sent copies (default Sent) |
createdAt |
Unix seconds |
unread |
Total unread messages across cached mailboxes |
Passwords are never returned by any endpoint. They are encrypted at rest with AES-256-GCM; see Security.
List accounts
Returns an array of account objects, each including the aggregated unread
count.
Create an account
POST /api/accounts
Required fields are email and password plus imapHost and smtpHost.
Defaults fill in the rest:
namedefaults to the part of the email before@,usernamedefaults toemailimapPort/smtpPortdefault to993/465imapSecurity/smtpSecuritydefault totlssentMailboxdefaults toSent(it is updated automatically when sync finds a mailbox flagged\Sent)
On success the response is 201 with the stored account (no password).
Validation rejects malformed email addresses, missing hosts, ports outside
1–65535 and security values other than tls, starttls, none.
Creating an account does not contact the mail server. Call sync to verify the credentials and fetch mailboxes.
Update an account
PUT /api/accounts/{id} replaces the account settings using the same body as
creation. Omit password to keep the existing one:
Returns the saved account. Sending a non-empty password re-encrypts and
replaces it.
Update the display name or password
PATCH /api/accounts/{id} updates the display name name and/or the stored
password and leaves every other field untouched:
Send at least one of name and password. Both are trimmed and must not be
empty; an unknown account returns 404. In the web UI under Settings →
Accounts you can edit each account’s display name; rotate its password in the
Security tab under Settings — the app syncs right after saving to verify the
new credential.
Delete an account
DELETE /api/accounts/{id} returns 204. Mailboxes and cached messages of the
account are deleted with it; the mail on the server is untouched.
Detect provider settings
GET /api/detect?email={address} finds IMAP/SMTP settings before you create
the account:
| Field | Description |
|---|---|
provider |
Provider name from the database, or the domain |
imap, smtp |
Host, port, security and login username |
helpUrl |
Provider help page, when known |
enableUrl |
Page explaining how to enable IMAP, when known |
source |
How the result was found: domain, mx or guess |
Detection resolves in three steps:
- Thunderbird ISPDB — a provider entry for the email domain
- MX records — map known mail exchangers to provider entries
- Guess —
imap.<domain>/smtp.<domain>on ports 993/465 with TLS
The endpoint performs DNS lookups for the MX step and can take a moment for
unknown domains. An invalid address returns 400.
Gmail requires two-step verification and an app-specific password. QQ Mail, 163 and several other Chinese providers require enabling IMAP in the provider’s web settings and using an app-specific password instead of the login password.
9 - Mailboxes & Sync
The mailbox object
| Field | Description |
|---|---|
id |
Mailbox ID used by the messages endpoints |
accountId |
Owning account |
name |
Display name (last path segment) |
path |
Full IMAP path, e.g. INBOX, Archive/2026 |
delimiter |
Hierarchy delimiter reported by the server |
attrs |
IMAP attributes such as \Inbox, \Sent, \Drafts, \Junk, \Trash |
uidValidity, uidNext |
IMAP UID bookkeeping from the last sync |
total, unread |
Message and unseen counts from the last sync |
lastSyncAt |
Unix seconds of the last sync; 0 if never synced |
Mailboxes appear after the account’s first sync. New accounts have none until sync runs.
List mailboxes
GET /api/accounts/{id}/mailboxes
Returns an array of mailbox objects, ordered with INBOX first. The unread
values are aggregated into the account’s unread field.
Synchronizing
POST /api/accounts/{id}/sync
Each sync does the following over a fresh IMAP connection:
- Refreshes the mailbox list, creating or updating every selectable
mailbox and its counts (
STATUS), and picks up the server’s\Sentmailbox. - Selects the target mailbox (
INBOXwhen the body is empty ormailboxis omitted). - Resets the local cache if
UIDVALIDITYchanged, because UIDs are no longer comparable. - Fetches new messages with UID-based incremental sync — only UIDs above the highest one stored locally.
Response:
| Field | Description |
|---|---|
mailbox |
Path that was synchronized |
mailboxes |
Selectable mailboxes seen on the server |
newMessages |
Messages stored locally by this sync |
total, unread |
Fresh counts for the target mailbox |
What gets cached
- The first sync of a mailbox stores every message received in the last 7 days, bodies included.
- Later syncs fetch up to 200 new messages per run. Bodies are stored when the batch is at most 200 messages; larger backlogs are stored newest-first and bodies are fetched on demand when a message is opened.
- Fetching uses
BODY.PEEK, so syncing never marks mail as read. - Older messages beyond the cache are not deleted from the server and are not listed locally. Opening a cached message that lacks a body triggers a single-message body fetch.
Sync runs only when requested — there is no background scheduler yet, so call
this endpoint (or pigeon digest --sync, or the MCP sync_mailbox tool) when
you want fresh mail.
Errors contacting or authenticating with the IMAP server return 502; cached
mail remains readable.
Fetching older mail
POST /api/mailboxes/{id}/fetch-older
The web UI calls this when you click Load more and the local cache is exhausted. It backfills mail older than the oldest cached message:
- The mailbox is searched day by day, walking backwards from the oldest
cached message, collecting at most 200 uncached messages per call (override
with
{"limit": N}, clamped to 200). - A quiet week does not mean the mailbox start. The walk keeps going
further back until it finds mail again, and only a history that is empty all
the way down reports
hasOlder: false— hide the button then. - Only envelopes are stored; bodies are fetched lazily when a message is opened.
- Repeat calls keep rewinding day by day; each response reports whether older mail remains.
Response:
| Field | Description |
|---|---|
mailbox |
Path that was backfilled |
newMessages |
Messages stored locally by this call |
hasOlder |
Whether more mail remains beyond what has been walked |
total, unread |
Fresh counts for the mailbox |
If the server reset the mailbox UIDVALIDITY, the call returns 409 — run a
regular sync first, which rebuilds the cache.
10 - Messages & Flags
The message object
List endpoints return summaries (no bodies). Opening a message adds:
| Field | Description |
|---|---|
bodyText |
Plain-text body; derived from HTML when the mail has no text part |
bodyHtml |
HTML body, when present |
bodyError |
Transient message set when a body fetch failed |
attachments |
Stored attachment metadata (id, filename, contentType, size); present when the message has attachments and they are cached locally |
Passwords aside, bodyText/bodyHtml are omitted when empty. Attachment
payloads are never inlined into the message object — download them through
GET /api/attachments/{id}.
List messages in a mailbox
GET /api/mailboxes/{id}/messages
| Query | Default | Description |
|---|---|---|
limit |
50 |
Page size, maximum 200 |
offset |
0 |
Skip this many messages |
q |
— | Case-insensitive substring match on subject, snippet or body text |
unseen |
— | 1 or true returns only unread messages |
since |
— | Unix seconds; only messages dated at or after this value |
Messages are ordered newest first (date DESC, id DESC). The list reads only
the local cache — it does not contact IMAP and does not mark anything as read.
Read one message
GET /api/messages/{id}
If the body was not cached during sync, Pigeon selects the mailbox read-only,
fetches the single message with BODY.PEEK (so it stays unread) and stores the
body before responding. If that fetch fails, the response still contains the
message with bodyError set and bodyLoaded: false.
Attachments travel with the raw MIME message and are stored locally in the same
fetch. Each file is capped at 25 MB — larger attachments are skipped (they
do not appear in the attachments array and cannot be downloaded), while the
rest of the mail, including its other attachments, is stored normally. Mail
cached before attachment storage existed is backfilled on first open: Pigeon
refetches the raw message once, extracts the attachments and serves them on
every later request without touching the network. A failed backfill is logged
and does not block the message itself.
Error codes: 404 when the message does not exist, 400 for an invalid ID.
Download an attachment
GET /api/attachments/{id}
Responds with the raw file bytes and Content-Disposition: attachment carrying
the attachment’s original filename, so clients save it under that name —
curl -OJ and browsers both honor it. Non-ASCII names use RFC 5987
(filename*=). Attachments that arrived without a filename are served as
attachment. Downloads are served from the local SQLite cache — no IMAP
round-trip — and support Range requests.
| Status | Meaning |
|---|---|
400 |
Invalid attachment ID |
404 |
Attachment not found (or not cached yet — open its message first) |
Change flags
POST /api/messages/{id}/flags
| Field | Description |
|---|---|
seen |
Read/unread (\Seen) |
flagged |
Starred (\Flagged) |
Pass at least one field; both are optional pointers, so omitted fields are left untouched. Pigeon applies the change on the IMAP server first (selecting the mailbox read-write), then updates the local cache and mailbox counts, and returns the updated message.
| Status | Meaning |
|---|---|
400 |
Neither seen nor flagged provided |
404 |
Message not found |
502 |
IMAP update failed; nothing changed locally |
Reading mail through the API never marks it as read automatically — clients should call this endpoint explicitly (the built-in web UI does so when a message is opened). MCP read tools follow the same rule.
11 - Search
GET /api/search searches the local cache across every account. By default it
matches metadata only — subject, sender and recipient fields — so even a
large mailbox answers quickly. Set body=1 to extend the query to message
bodies.
| Query | Default | Description |
|---|---|---|
q |
— | Text to look for in the subject, sender and recipient fields (plus snippet and body text when body=1) |
from |
— | Only messages whose sender name or address contains this text |
subject |
— | Only messages whose subject contains this text |
since |
— | Only messages dated on or after this Unix timestamp (seconds) |
until |
— | Only messages dated on or before this Unix timestamp (seconds) |
body |
0 |
1/true also matches the snippet and body text of cached bodies |
account |
0 (all) |
Restrict results to one account ID |
limit |
50 |
Maximum results, capped at 200 |
offset |
0 |
Skip this many results, for paging |
At least one of q, from, subject, since or until is required;
otherwise the endpoint returns 400. An inverted range (since > until) is
also rejected with 400.
Results are message summaries ordered newest first (date descending, ties
broken by id descending), and include the account and mailbox path so you
can tell where each hit lives:
Use read message with a result id to fetch
the full body.
Web interface
- Type in the search box above the message list and press Enter to search all
accounts. Press
/anywhere in the app to jump to the search box. - Each hit carries a chip naming its source account; opening a hit works across accounts.
- Expand Advanced search for sender, subject, date range, and the Also search message body checkbox.
- Press Esc or click the × button to leave the results and return to the previous mailbox.
Scope and limits
- Search covers only locally cached messages. Run a sync first if the mailbox was never fetched.
- Matching is a case-insensitive
LIKEsubstring;%and_in the query are escaped, so they match literally. Sender matching runs over the stored address JSON, so the literal wordsnameandaddresscan also match. body=1only searches bodies that are already cached — Pigeon fetches bodies lazily, so opening messages populates the searchable set over time. Body searches are slower on large mailboxes.- There is no dedicated full-text index yet — predicates run over SQLite’s
LIKE. The date index keeps newest-first paging over the whole cache cheap.
MCP clients can call the equivalent search_messages tool; see
MCP Server.
12 - Sending Mail
POST /api/accounts/{id}/send delivers a message over SMTP and appends a copy
to the account’s Sent mailbox.
Request
| Field | Description |
|---|---|
to, cc, bcc |
Arrays of plain email address strings; at least one recipient in total is required |
subject |
Subject line |
text |
Plain-text body |
html |
Optional HTML alternative |
inReplyTo |
Optional Message-ID of the message being replied to |
attachments |
Optional array of files, see below |
Recipients are strings ("ops@example.com"), not address objects. Provide
text, or html (or both); Pigeon always sends a plain-text part, adding the
HTML version as an alternative when present.
Each attachment is an object:
| Field | Description |
|---|---|
filename |
Required file name |
contentType |
Optional MIME type; inferred from the file extension when omitted |
content |
File bytes, standard base64 |
The whole request body is limited to 36 MB (attachments count base64-encoded).
Decoded attachments are additionally capped at 25 MB total per message;
exceeding either limit returns 400 before any SMTP connection is opened.
Most mail providers also reject messages beyond roughly 25 MB at delivery
time, in which case the result is a 502.
Response
| Field | Description |
|---|---|
messageId |
Generated Message-ID of the sent mail |
appended |
Whether a copy was appended to the Sent mailbox via IMAP |
warning |
Present when sending succeeded but archiving failed |
The copy goes to sentMailbox, updated automatically to the server’s \Sent
mailbox when one exists. If the append fails, the send still succeeds and the
result carries a warning instead of an error.
Errors
| Status | Meaning |
|---|---|
400 |
Invalid request body: malformed JSON, an attachment without filename, content that is not valid base64, or decoded attachments totalling more than 25 MB |
404 |
Account not found |
502 |
SMTP delivery failed, or addresses/configuration were rejected |
502 covers connection and authentication failures as well as invalid
recipient addresses — Pigeon could not hand the message to the mail server.
Check the error string; it includes the SMTP host and the cause.
Notes
- Delivery is synchronous; the request returns after the SMTP conversation finishes (30-second timeout).
- The SMTP client enforces TLS:
tlsmode uses implicit TLS (SMTPS),starttlsupgrades the plain connection, andnonestill attempts STARTTLS but allows plain text. - SMTP authentication uses
PLAIN. Accounts with an empty username skip auth (useful for local relays). - Sent mail is not written to the local message cache directly; sync the Sent mailbox to list it through the API.
13 - Settings
Client settings live in the server’s SQLite database, so every browser pointing at the same Pigeon instance shares the same language, auto-sync interval and reader preferences. A new database is created and seeded with the defaults on first start.
The settings object
| Field | Type | Description |
|---|---|---|
lang |
string | Web UI language: en or zh. Default en. |
refreshIntervalMs |
integer | How often the web UI auto-syncs mailboxes while the page is open. 0 turns auto-sync off. Default 60000 (one minute). |
imagesBanner |
boolean | Automatically load remote images when a message opens. When off, remote images are blocked and a banner with a “Show images” button appears above the message body. Default false. |
groupBySender |
boolean | Collapse the message list into one row per sender. Clicking a row shows that sender’s messages in the reader pane, and clicking one expands it in place. Default false. |
Allowed refreshIntervalMs values: 0 (off), 30000, 60000, 120000,
300000, 900000.
Get settings
GET /api/settings
Update settings
PUT /api/settings — send any subset of the fields; omitted ones keep their
current values. Returns the full settings object.
An invalid language or an unsupported interval returns 400 Bad Request.
14 - MCP Server
Pigeon ships an MCP server exposing eight mail tools. Run it over stdio for
local clients, or use the /mcp HTTP endpoint of pigeon serve.
stdio
The process reads MCP JSON-RPC on stdin/stdout and logs to stderr. It opens the
same data directory as pigeon serve (~/.pigeon by default); pass
--data DIR in args if you use a custom location.
Streamable HTTP
pigeon serve mounts the MCP endpoint at /mcp. It is stateless and replies
with JSON (application/json, not SSE). Authenticate exactly like the REST
API — bearer token required for non-loopback clients:
Tools
| Tool | Parameters | Description |
|---|---|---|
list_accounts |
— | Accounts with unread counts |
list_mailboxes |
account? |
Mailboxes with unread/total counts and attributes |
list_messages |
account?, mailbox?, limit?, query?, unseenOnly? |
Message summaries, newest first |
read_message |
id, includeHtml? |
Full message; fetches the body if uncached |
search_messages |
query?, from?, subject?, body?, since?, until?, account?, limit? |
Search cached mail; metadata by default |
sync_mailbox |
account?, mailbox? |
Fetch new mail over IMAP |
set_message_flags |
id, seen?, flagged? |
Change read/starred state on server and locally |
send_email |
account?, to, cc?, bcc?, subject, text, html?, inReplyTo?, attachments? |
Send over SMTP and archive to Sent |
Parameter notes:
accountaccepts an account ID, email address or name. It may be omitted when exactly one account is configured.mailboxaccepts a path or display name and defaults toINBOX.list_messagesdefaults to 20 results, maximum 100;search_messagesthe same for hits.search_messagesrequires at least one ofquery,from,subject,sinceoruntil, and searches all accounts unlessaccountis given.querymatches subject and sender/recipient metadata; setbody=trueto also match snippet and cached body text (bodies are fetched lazily, and body searches are slower).since/untilacceptYYYY-MM-DD(local time,untilinclusive through end of day) or RFC3339 timestamps.read_messagereturns text truncated to 64 KiB and, withincludeHtml, HTML up to 256 KiB. It does not mark the message as read. When the message has attachments, anattachmentsarray of{id, filename, contentType, size}metadata is included — bytes download through the REST endpointGET /api/attachments/{id}. Stored attachments are capped at 25 MB each; larger files are skipped and do not appear in the array.send_emailaccepts anattachmentsarray of{filename, contentType?, content}objects, wherecontentis standard base64. It requires explicit user intent. It is annotated as non-idempotent and OpenWorld, so MCP clients that surface confirmations will ask first.
Output shapes
MCP outputs are JSON-friendly variants of the REST objects. Dates are ISO-8601
UTC strings (e.g. 2026-12-01T08:30:00Z) rather than Unix seconds. Examples:
Recommended flow
The server’s built-in instructions suggest this pattern to agents:
list_accounts→list_mailboxesto learn what exists.- If a mailbox looks empty or stale,
sync_mailbox. list_messages/search_messagesto find mail,read_messagefor the body.- Use
set_message_flagsonly when the user wants read/starred state changed. - Call
send_emailonly with clear user intent, after confirming recipients and content.
15 - Security & Deployment
Pigeon is local-first: mail is fetched directly from your IMAP servers, stored in a local SQLite database and served from the same process. There is no cloud middleman and no telemetry.
Credentials at rest
- Account passwords are encrypted with AES-256-GCM.
- The 256-bit key lives in
secret.keyin the data directory, created with mode0600on first start. - Endpoints never return passwords; responses include only non-secret account fields.
- Back up
secret.keywith the database. Without it, stored passwords cannot be decrypted and accounts must be re-added with their passwords.
Mail bodies, subjects and addresses in SQLite are not encrypted — protect
the host with disk encryption if that matters to you. All secret material is
in the data directory; chmod 700 on it is a sensible baseline.
API tokens
- Tokens look like
pigeon_<random>and are returned once, at creation. - Only a SHA-256 hash is stored; a stolen database does not reveal usable tokens.
lastUsedAtrecords the most recent successful authentication.- Revoking a token (
DELETE /api/tokens/{id}orpigeon token delete) takes effect immediately. - The initial token printed by
pigeon serveon first start appears in the log once — treat log files as sensitive.
Authentication model
| Request source | Access |
|---|---|
Loopback (127.0.0.1, ::1) |
Allowed without credentials |
| Anything else | Requires Authorization: Bearer pigeon_… |
GET /api/health |
Public |
The loopback test uses the TCP remote address. Consequences:
- Same-host reverse proxy: a proxy connecting from
127.0.0.1is trusted, so the API is effectively unauthenticated behind it. Either authenticate at the proxy or run Pigeon somewhere its clients are not loopback (for example in a container on a bridge network). - Docker
-p 8787:8787: connections arrive from the bridge gateway, not loopback, so the token is required. This is the intended remote setup. - SSH tunnel / VPN: traffic to
127.0.0.1stays loopback and skips tokens; the tunnel itself provides the access control.
CORS allows any origin by design (the API targets local tools and agents). Authentication still applies to non-loopback requests; do not expose the service to the internet without TLS and a token.
Transport security
- IMAP: implicit TLS, STARTTLS or plain, with a minimum of TLS 1.2 for TLS modes.
- SMTP: TLS is mandatory by default;
tlsuses implicit TLS (SMTPS),starttlsupgrades,nonestill attempts STARTTLS but permits plaintext. - Body fetches use
BODY.PEEK, so reading and syncing never change read state on the server.
Running remotely
By default Pigeon listens on 127.0.0.1:8787, which only this machine can
reach. To let other machines call the REST API (and the /mcp endpoint), bind
a reachable address with --addr or PIGEON_ADDR:
--addr takes precedence over PIGEON_ADDR. Once the service is reachable
from other hosts, every request from them must carry a Bearer token:
This is plain HTTP: the token crosses the network unencrypted. Use it inside a trusted network, or put a TLS-terminating proxy in front before exposing it beyond one.
Recommended patterns, most to least conservative:
- SSH tunnel — keep Pigeon on
127.0.0.1, forward the port over SSH; no public listener at all. - Private network / VPN — bind to a trusted interface with a token.
- Container with port mapping — the Dockerfile runs as a non-root user; non-loopback requests require a token.
- Reverse proxy with TLS — terminate TLS at the proxy and also do authentication there, because Pigeon will trust the proxy’s loopback connection.
What is not encrypted or sandboxed
- HTML mail in the web UI is rendered in a sandboxed iframe (no scripts, no same-origin access) and remote images are blocked until you click “show images” for that message.
- When the web UI talks to a remote server it keeps the API token in browser
localStorage; anyone with access to that browser profile can read it. Prefer dedicated tokens and revoke them when done. - There is no built-in rate limiting; rely on the proxy or network boundary for internet-facing deployments.
16 - Architecture
Pigeon is one process and one binary. The web UI assets, REST API, MCP server and CLI all read the same local SQLite store. Every interface — the built-in web UI today and a desktop GUI later — is a pure REST API client, exactly like scripts and AI agents; the server has no UI-only endpoints or side channels.
Request paths
pigeon serve builds the API handler, mounts the embedded assets at / and
runs the HTTP server. pigeon mcp runs the same tool set over stdio without an
HTTP listener. Both open the same data directory; SQLite serializes writes so
running several processes against one directory is safe but not optimized for
high concurrency.
Synchronization flow
- Connect to IMAP using the account’s host, port and security mode, then log in.
LISTall mailboxes; skip\Noselectand non-existent entries; upsert each mailbox and read fresh counts withSTATUS.- Remember the server’s
\Sentmailbox so sent copies are archived in the right place. - Select the target mailbox read-only.
- Compare
UIDVALIDITYwith the stored value. If it changed, discard cached messages for that mailbox — old UIDs are meaningless. - Fetch messages:
- First sync: search for messages received in the last 7 days (IMAP
SEARCH SINCE); bodies are included when the batch is at most 200. - Incremental: search for UIDs above the stored maximum; at most 200 per run, newest-first if there is a backlog. Bodies are included when the batch is at most 200.
- First sync: search for messages received in the last 7 days (IMAP
- Parse envelopes and MIME, store messages, then update counts and
lastSyncAt.
Older mail beyond the cached window is backfilled on demand: “Load more” calls
POST /api/mailboxes/{id}/fetch-older, which walks backwards day by day from
the oldest cached message (envelopes only) and, when a silent week turns up
nothing, probes everything earlier before declaring the mailbox exhausted. See
Mailboxes & Sync for the details.
Body parsing extracts text/plain, text/html, a snippet and attachment
parts; attachment bytes are stored in the local attachments table (each file
up to 25 MB, larger ones skipped) so downloads never hit IMAP again. When a
mail has only HTML, a plain-text version is derived so search and readers have
text. Fetching always uses BODY.PEEK; opening an uncached body later performs
a single-message read-only fetch, and a message cached before attachment
storage existed gets its attachments backfilled the first time it is opened.
Storage layout
The data directory contains:
| File | Purpose |
|---|---|
pigeon.db (+ -wal, -shm) |
SQLite database in WAL mode |
secret.key |
AES-256-GCM key for account passwords, mode 0600 |
logs/pigeon-YYYY-MM-DD.log |
Daily log files, one per local date; logs are also mirrored to stderr |
| Table | Contents |
|---|---|
accounts |
Account settings; password_enc holds the encrypted password |
mailboxes |
Mailbox metadata, UID state and counts; cascades from accounts |
messages |
Cached message metadata and bodies; cascades from mailboxes |
attachments |
Attachment bytes and metadata; cascades from messages |
tokens |
Token ID, name, SHA-256 hash and timestamps |
settings |
Client preferences shared by all clients: language, refresh interval, the remote-image auto-load toggle and sender grouping |
Deleting an account cascades to its mailboxes and messages, but never touches the IMAP server.
Design decisions
- Cache, don’t mirror. Pigeon keeps a recent window for offline reading and search and leaves the server as the source of truth. Anything not cached is fetched on demand.
- Lazy bodies. Metadata sync is cheap; bodies are fetched during sync only within the batches above, and on first open otherwise.
- Local-first auth. Loopback clients skip tokens; remote clients never see mail without one. No third-party service sits in the path.
- One tool set, two transports. The MCP tools are transport-agnostic; stdio and HTTP share the same handlers and storage.
- UI as an API client. The web UI and any GUI manage accounts and mail through the same REST endpoints documented here. Nothing in the UI gets privileged access, so the API stays the single contract to test and secure.
- Stateless MCP HTTP. The HTTP endpoint answers each request independently with JSON, which keeps deployments simple behind any load balancer.
Limits
| Limit | Value |
|---|---|
| Initial sync window per mailbox | last 7 days |
| Messages per incremental sync | 200 |
| Messages per backfill call | 200 |
| Message list page size | default 50, max 200 |
| Search results | default 20, max 100 |
| Text body stored | 256 KiB |
| HTML body stored | 1 MiB |
| Snippet length | 180 characters |