Skip to main content
Glama
exmail-mcp

exmail-mcp

README.md
# exmail-mcp

An [MCP](https://modelcontextprotocol.io) server for **Tencent Exmail (腾讯企业邮箱)** mailboxes.
It lets an AI agent search and read your mail safely, and send mail only through an explicit
two-step draft → send flow that is easy to put behind human approval.

- **Read-only by default.** Folders are opened with `EXAMINE` and messages are fetched with
  `BODY.PEEK`, so nothing gets marked read. There are no delete / move / flag tools at all.
- **Chinese works:** RFC 2047 headers, raw GBK/GB2312/GB18030 headers and bodies, RFC 2231
  filenames, and modified-UTF-7 folder names (e.g. `其他文件夹/客户`).
- **Incremental sync:** `fetch_since` returns everything newer than a UID in one IMAP session with
  batched fetches, plus `uidvalidity`/`uidnext` so a digest job can resume exactly where it stopped.
- **Two-step sending:** `create_draft` (stored locally, returns a full preview) and `send_draft`
  (sends that exact draft once) are separate tools. Every send is logged without its body.
- **Runs anywhere:** macOS, Windows and Linux, either natively with Python 3.11+ or in Docker
  (Docker Desktop on macOS/Windows). Two transports: stdio, and streamable HTTP with a bearer token.

> Independent, unofficial project. Not affiliated with or endorsed by Tencent.
> Tencent Exmail only; it relies on Exmail-specific IMAP behaviour (see *Known limits*).

**Contents:** [Choose an install](#choose-an-install) · [macOS](#macos) · [Windows](#windows-powershell) ·
[Linux](#linux) · [Configuration](#configuration) · [Connecting a client](#connecting-a-client) ·
[Tools](#tools) · [Safety model](#safety-model) · [Is it faster than plain IMAP/SMTP?](#is-it-faster-than-plain-imapsmtp) ·
[Known limits](#known-limits)

## Requirements

- An Exmail account with IMAP/SMTP enabled. If your account uses a client-specific password
  (客户端专用密码), use that.
- Outbound access to `imap.exmail.qq.com:993` and `smtp.exmail.qq.com:465`.
- **Either** Python 3.11 or newer (native install) **or** Docker (Docker Desktop on macOS and Windows,
  Docker Engine + Compose v2 on Linux).

## Choose an install

| | Native Python | Docker |
|---|---|---|
| Best for | One person, MCP client on the same computer (Claude Desktop, Cursor, Claude Code) | An always-on machine serving several agents over a private network |
| Transport | stdio (the client starts the server) or HTTP | HTTP (stdio via `docker exec`) |
| Secrets | Password + token files in your per-user config folder | Files on the host, mounted read-only |

**Per-user default locations (native install).** You can override every one of them, see [Configuration](#configuration).

| OS | Config (password, token, contacts) | Data (drafts, logs, header cache, downloads, attachments) |
|---|---|---|
| macOS | `~/Library/Application Support/exmail-mcp/` | `~/Library/Application Support/exmail-mcp/` |
| Windows | `%APPDATA%\exmail-mcp\` | `%LOCALAPPDATA%\exmail-mcp\` |
| Linux | `~/.config/exmail-mcp/` (`$XDG_CONFIG_HOME`) | `~/.local/share/exmail-mcp/` (`$XDG_DATA_HOME`) |

Files in the config folder: `exmail.pass` (one line, the mailbox password only), `mcp_token`
(bearer token, only needed for HTTP), optional `contacts.json`.

---

## macOS

### Native Python (macOS)

```bash
# 1. Get the code and create a virtual environment (python.org or Homebrew Python 3.11+)
git clone https://github.com/wealllovegithub/exmail-mcp.git ~/exmail-mcp
cd ~/exmail-mcp
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt

# 2. Password file, readable only by you
CFG="$HOME/Library/Application Support/exmail-mcp"
mkdir -p "$CFG" && chmod 700 "$CFG"
install -m 600 /dev/null "$CFG/exmail.pass"
open -e "$CFG/exmail.pass"          # paste the password on one line, save, close

# 3. (HTTP only) bearer token
.venv/bin/python -c "import secrets;print(secrets.token_urlsafe(40))" > "$CFG/mcp_token"
chmod 600 "$CFG/mcp_token"

# 4. Try it
export EXMAIL_USER=you@example.com
.venv/bin/python server.py --stdio            # stdio: waits for an MCP client on stdin; Ctrl+C to quit
.venv/bin/python server.py --port 8765        # HTTP on 127.0.0.1:8765
curl http://127.0.0.1:8765/healthz            # -> ok
```

For stdio you normally don't run it yourself: the MCP client starts it (see
[Connecting a client](#connecting-a-client)).

**Run the HTTP server at login (optional, launchd).** Save as
`~/Library/LaunchAgents/com.example.exmail-mcp.plist`, replacing `YOU` and the address:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>com.example.exmail-mcp</string>
  <key>ProgramArguments</key><array>
    <string>/Users/YOU/exmail-mcp/.venv/bin/python</string>
    <string>/Users/YOU/exmail-mcp/server.py</string>
  </array>
  <key>EnvironmentVariables</key><dict>
    <key>EXMAIL_USER</key><string>you@example.com</string>
  </dict>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardErrorPath</key><string>/Users/YOU/Library/Logs/exmail-mcp.log</string>
</dict></plist>
```

```bash
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.example.exmail-mcp.plist
launchctl bootout gui/$(id -u)/com.example.exmail-mcp      # to stop and unload
```

### Docker Desktop (macOS)

```bash
git clone https://github.com/wealllovegithub/exmail-mcp.git ~/exmail-mcp && cd ~/exmail-mcp
cp .env.example .env                    # edit: EXMAIL_USER, EXMAIL_PASS_FILE, MCP_BIND_IP=127.0.0.1
mkdir -p secrets data downloads attachments config && chmod 700 secrets data
install -m 600 /dev/null ~/.exmail.pass && open -e ~/.exmail.pass   # then EXMAIL_PASS_FILE=/Users/YOU/.exmail.pass
python3 -c "import secrets;print(secrets.token_urlsafe(40))" > secrets/mcp_token && chmod 600 secrets/mcp_token
docker compose up -d --build
curl http://127.0.0.1:8765/healthz      # -> ok
```

`restart: unless-stopped` brings it back whenever Docker Desktop starts. Enable *Start Docker
Desktop when you sign in* in Docker Desktop's settings to have it at login.
If the container can't read the password or token file, set `RUN_UID`/`RUN_GID` in `.env` to the
output of `id -u` / `id -g`.

---

## Windows (PowerShell)

### Native Python (Windows)

Install Python 3.11+ from python.org (tick *Add python.exe to PATH*) or `winget install Python.Python.3.12`.

```powershell
# 1. Get the code and create a virtual environment
git clone https://github.com/wealllovegithub/exmail-mcp.git "$HOME\exmail-mcp"
Set-Location "$HOME\exmail-mcp"
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt

# 2. Password file in %APPDATA%\exmail-mcp, readable only by you
$cfg = "$env:APPDATA\exmail-mcp"
New-Item -ItemType Directory -Force $cfg | Out-Null
notepad "$cfg\exmail.pass"            # paste the password on one line, save, close
icacls "$cfg\exmail.pass" /inheritance:r /grant:r "${env:USERNAME}:(R,W)"

# 3. (HTTP only) bearer token
.\.venv\Scripts\python.exe -c "import secrets;print(secrets.token_urlsafe(40))" |
  Out-File -Encoding ascii "$cfg\mcp_token"
icacls "$cfg\mcp_token" /inheritance:r /grant:r "${env:USERNAME}:(R,W)"

# 4. Try it
$env:EXMAIL_USER = "you@example.com"          # this session only; use setx for a permanent value
.\.venv\Scripts\python.exe server.py --stdio  # stdio: waits for an MCP client; Ctrl+C to quit
.\.venv\Scripts\python.exe server.py --port 8765
Invoke-WebRequest http://127.0.0.1:8765/healthz   # -> ok
```

Notes: Notepad may save with a UTF-8 BOM; the server ignores it. If PowerShell blocks
`Activate.ps1`, you don't need it: call `.venv\Scripts\python.exe` directly as above.

**Run the HTTP server at sign-in (optional, Task Scheduler).** `pythonw.exe` runs without a
console window:

```powershell
setx EXMAIL_USER you@example.com
$dir = "$HOME\exmail-mcp"
$action  = New-ScheduledTaskAction -Execute "$dir\.venv\Scripts\pythonw.exe" -Argument "`"$dir\server.py`"" -WorkingDirectory $dir
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
Register-ScheduledTask -TaskName "exmail-mcp" -Action $action -Trigger $trigger
# Remove later with: Unregister-ScheduledTask -TaskName exmail-mcp
```

### Docker Desktop (Windows)

```powershell
git clone https://github.com/wealllovegithub/exmail-mcp.git "$HOME\exmail-mcp"
Set-Location "$HOME\exmail-mcp"
Copy-Item .env.example .env       # edit: EXMAIL_USER, EXMAIL_PASS_FILE, MCP_BIND_IP=127.0.0.1
New-Item -ItemType Directory -Force secrets, data, downloads, attachments, config | Out-Null
notepad "$HOME\exmail.pass"       # password on one line; then in .env:
                                  # EXMAIL_PASS_FILE=C:/Users/YOU/exmail.pass   (forward slashes)
python -c "import secrets;print(secrets.token_urlsafe(40))" | Out-File -Encoding ascii secrets\mcp_token
docker compose up -d --build
Invoke-WebRequest http://127.0.0.1:8765/healthz
```

Use forward slashes (`C:/Users/...`) for paths in `.env`. Enable *Start Docker Desktop when you
sign in* to have it at login; the container restarts with Docker.

---

## Linux

### Native Python (Linux)

```bash
git clone https://github.com/wealllovegithub/exmail-mcp.git ~/exmail-mcp && cd ~/exmail-mcp
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt   # Debian/Ubuntu: apt install python3-venv
CFG="${XDG_CONFIG_HOME:-$HOME/.config}/exmail-mcp"
mkdir -p "$CFG" && chmod 700 "$CFG"
install -m 600 /dev/null "$CFG/exmail.pass" && "${EDITOR:-nano}" "$CFG/exmail.pass"
.venv/bin/python -c "import secrets;print(secrets.token_urlsafe(40))" > "$CFG/mcp_token" && chmod 600 "$CFG/mcp_token"
EXMAIL_USER=you@example.com .venv/bin/python server.py --port 8765
```

**Run at boot/login (optional, systemd user service)** – `~/.config/systemd/user/exmail-mcp.service`:

```ini
[Unit]
Description=exmail-mcp
After=network-online.target

[Service]
Environment=EXMAIL_USER=you@example.com
ExecStart=%h/exmail-mcp/.venv/bin/python %h/exmail-mcp/server.py
Restart=on-failure

[Install]
WantedBy=default.target
```

```bash
systemctl --user daemon-reload && systemctl --user enable --now exmail-mcp
loginctl enable-linger "$USER"     # optional: keep it running when you are logged out
```

### Docker (Linux)

```bash
git clone https://github.com/wealllovegithub/exmail-mcp.git exmail-mcp && cd exmail-mcp
cp .env.example .env            # then edit .env
mkdir -p secrets data downloads attachments config && chmod 700 secrets data
# optional: cp contacts.example.json config/contacts.json   (name -> addresses, git-ignored)
install -m 600 /dev/null /path/to/exmail.pass && $EDITOR /path/to/exmail.pass   # set EXMAIL_PASS_FILE to it
python3 -c "import secrets;print(secrets.token_urlsafe(40))" > secrets/mcp_token && chmod 600 secrets/mcp_token
docker compose up -d --build
curl http://<MCP_BIND_IP>:8765/healthz      # -> ok
```

The container runs as `RUN_UID:RUN_GID` (default 1000:1000), which must be able to read the
password and token files. Its root filesystem is read-only, it has no Linux capabilities, and the
password file is mounted read-only at `/run/secrets/exmail.pass`. `restart: unless-stopped`
starts it again after a reboot.

---

## Configuration

All settings are environment variables. Native: set them in your shell, the service definition or the
MCP client's `env` block. Docker: put them in `.env` (copied from `.env.example`).

| Variable | Meaning |
|---|---|
| `EXMAIL_USER` | Mailbox address (required) |
| `EXMAIL_FROM_NAME` | Optional display name for the From header |
| `EXMAIL_PASS_FILE` | Password file. Native default `<config dir>/exmail.pass`. Docker: host path of the file, mounted read-only at `/run/secrets/exmail.pass` |
| `MCP_TOKEN_FILE` | Bearer token file (HTTP only). Native default `<config dir>/mcp_token`. Docker default `./secrets/mcp_token` |
| `MCP_HOST`, `MCP_PORT` | Native HTTP listen address and port (default `127.0.0.1`, `8765`). The Docker image listens on `0.0.0.0` inside the container |
| `MCP_BIND_IP` | Docker only: host address to publish on. Use `127.0.0.1` or a private VPN/Tailscale IP. **Never `0.0.0.0` or a public IP.** |
| `SENT_COPY` | `auto` (default): after sending, look for the message in Sent and append a copy only if it is missing. `append`: always append. `off`: never. Exmail saves SMTP sends to Sent itself, so `auto` normally appends nothing. |
| `DISPLAY_TZ` | IANA timezone for `date_iso` fields (default `UTC`; e.g. `Asia/Shanghai` or `America/New_York`). `date_utc` is always UTC. |
| `IMAP_POOL_SIZE`, `IMAP_POOL_IDLE_SECONDS` | Read-only connection pool size (default 3) and idle drop time (default 240 s) |

Locations (all optional; defaults shown for a native install):

| Variable | Default |
|---|---|
| `EXMAIL_MCP_CONFIG_DIR` | per-user config folder (table above) |
| `EXMAIL_MCP_DATA_DIR` | per-user data folder (table above) |
| `CONTACTS_FILE` | `<config dir>/contacts.json` |
| `DATA_DIR` | `<data dir>` |
| `DRAFT_DIR`, `SEND_LOG`, `DRAFT_LOG`, `HEADER_CACHE_DIR` | `<DATA_DIR>/drafts`, `send_log.jsonl`, `draft_log.jsonl`, `hcache` |
| `DOWNLOAD_DIR`, `ATTACH_DIR` | `<DATA_DIR>/downloads`, `<DATA_DIR>/attachments` (outgoing attachments must be inside `ATTACH_DIR`) |
| `DOWNLOAD_DIR_HOST`, `ATTACH_DIR_HOST` | Docker only: host paths reported back to clients |

The Docker image sets `/run/secrets/...`, `/data`, `/downloads`, `/attachments` and
`/config/contacts.json`, which `docker-compose.yml` mounts from the host.

Advanced: `EXMAIL_IMAP_HOST`, `EXMAIL_IMAP_PORT`, `EXMAIL_SMTP_HOST`, `EXMAIL_SMTP_PORT`,
`SENT_WAIT_SECONDS` (20), `SEARCH_SCAN_CAP` (3000), `HEADER_CACHE_MAX` (50000),
`DISK_HEADER_CACHE` (`on`), `WARM_HEADER_CACHE` (`on`), `MAX_ATTACH_BYTES` (25 MB),
`IMAP_POOL_NOOP_SECONDS` (30).

## Connecting a client

Two ways to connect:

- **stdio:** the client starts `server.py --stdio` itself. No network port, no token. Best when
  the client runs on the same computer as a native install.
- **HTTP + bearer token:** the server runs on its own (service or Docker); clients connect to
  `http://<host>:<port>/mcp` with `Authorization: Bearer <contents of the token file>`. The server
  is stateless (JSON responses), so clients that sleep or reconnect often work fine. `GET /healthz`
  is the only unauthenticated path.

In the examples, replace the paths with yours. Python path: macOS/Linux
`/Users/YOU/exmail-mcp/.venv/bin/python` (or `/home/YOU/...`), Windows
`C:\\Users\\YOU\\exmail-mcp\\.venv\\Scripts\\python.exe` (JSON needs doubled backslashes, or use `/`).

### Claude Desktop

Config file (Settings → Developer → Edit Config opens it):

- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
- Linux: no official Claude Desktop build; use another client.

stdio (recommended):

```json
{
  "mcpServers": {
    "exmail": {
      "command": "/Users/YOU/exmail-mcp/.venv/bin/python",
      "args": ["/Users/YOU/exmail-mcp/server.py", "--stdio"],
      "env": { "EXMAIL_USER": "you@example.com" }
    }
  }
}
```

Windows:

```json
{
  "mcpServers": {
    "exmail": {
      "command": "C:\\Users\\YOU\\exmail-mcp\\.venv\\Scripts\\python.exe",
      "args": ["C:\\Users\\YOU\\exmail-mcp\\server.py", "--stdio"],
      "env": { "EXMAIL_USER": "you@example.com" }
    }
  }
}
```

HTTP + bearer: Claude Desktop's config file only launches local commands, so bridge with
[`mcp-remote`](https://www.npmjs.com/package/mcp-remote) (needs Node.js):

```json
{
  "mcpServers": {
    "exmail": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "http://127.0.0.1:8765/mcp", "--allow-http",
               "--header", "Authorization:${AUTH_HEADER}"],
      "env": { "AUTH_HEADER": "Bearer <token>" }
    }
  }
}
```

Restart Claude Desktop after editing.

### Cursor

`~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` in a project (don't commit a token):

```json
{
  "mcpServers": {
    "exmail": {
      "command": "/Users/YOU/exmail-mcp/.venv/bin/python",
      "args": ["/Users/YOU/exmail-mcp/server.py", "--stdio"],
      "env": { "EXMAIL_USER": "you@example.com" }
    },
    "exmail-http": {
      "url": "http://127.0.0.1:8765/mcp",
      "headers": { "Authorization": "Bearer <token>" }
    }
  }
}
```

(`~/.cursor` is `%USERPROFILE%\.cursor` on Windows.) Use one of the two entries.

### Claude Code

```bash
# stdio (macOS/Linux)
claude mcp add exmail -e EXMAIL_USER=you@example.com -- ~/exmail-mcp/.venv/bin/python ~/exmail-mcp/server.py --stdio
# HTTP + bearer
claude mcp add --transport http exmail http://127.0.0.1:8765/mcp --header "Authorization: Bearer <token>"
```

```powershell
# stdio (Windows PowerShell)
claude mcp add exmail -e EXMAIL_USER=you@example.com -- "$HOME\exmail-mcp\.venv\Scripts\python.exe" "$HOME\exmail-mcp\server.py" --stdio
```

Add `--scope user` to make it available in every project. Check with `claude mcp list`.

### Other MCP clients

- **stdio:** command `<venv python>`, args `["<path>/server.py", "--stdio"]`, env `EXMAIL_USER`
  (plus any [Configuration](#configuration) variables).
- **stdio into Docker:** command `docker`, args
  `["exec", "-i", "exmail-mcp", "python", "/app/server.py", "--stdio"]`. On a remote host, wrap it in SSH:
  `ssh user@your-server docker exec -i exmail-mcp python /app/server.py --stdio`. stdio needs no
  token; access is controlled by SSH and Docker permissions.
- **Streamable HTTP:** URL `http://<host>:<port>/mcp`, header `Authorization: Bearer <token>`.

### Network and TLS

The server speaks plain HTTP and the bearer token travels in a header, so protect the transport:

- Listen on `127.0.0.1` when clients are on the same computer (the native default; `MCP_BIND_IP=127.0.0.1` for Docker).
- For other machines, use an encrypted overlay network address (Tailscale, WireGuard). Avoid plain
  LAN addresses on shared networks.
- If clients must cross an untrusted network, put a TLS reverse proxy (Caddy, nginx, Traefik) in
  front and keep the server itself on `127.0.0.1`.
- Never publish it on a public interface or port-forward it to the internet.
- Treat the token like a password: keep the file private; rotate it by replacing the file and
  restarting the server.

## Tools

| Tool | What it does |
|---|---|
| `list_folders(with_counts=false)` | Folder names (decoded), flags, delimiter; optional MESSAGES/UNSEEN via `STATUS` |
| `search(folder="INBOX", since, before, from_, to, subject, unread, limit=50)` | Dates `YYYY-MM-DD` (`since` inclusive, `before` exclusive). See *Name matching*. `to` also matches Cc. Newest first; each hit has `matched_via`. |
| `fetch_since(folder="INBOX", since_uid=0, include="summary", limit, strip_quotes=false, uidvalidity, max_body_chars=20000, snippet_chars=300)` | Every message with UID > `since_uid`, oldest first, in one session. `summary`: uid, message_id, dates, from/to/cc (+ parsed `*_addrs`), subject, flags, size, attachment list, snippet. `body`: full decoded text instead of the snippet. Returns `uidvalidity`, `uidnext`, `has_more`, `next_since_uid`. Default limit 200 (summary) / 50 (body), max 500. |
| `get_message(folder, uid \| message_id, max_body_chars=20000, strip_quotes=false)` | Headers (`date_iso`/`date_utc` from the Date header, `internaldate_iso`/`internaldate_utc` = server arrival time), decoded text body (text/plain preferred, else HTML converted to text), attachment list (index, filename, size, `size_approx`, mime_type, inline). Fetches `BODYSTRUCTURE` + header first, then only the text parts; attachments are listed, not downloaded. Returns `elapsed_ms`. |
| `get_thread(folder, uid \| message_id, folders=None, include="summary", strip_quotes=false, max_body_chars=20000)` | Conversation by Message-ID / In-Reply-To / References across INBOX and Sent (or given folders), oldest first, with snippets or bodies. Bodies are fetched in batches per folder in one pooled session, text parts only. |
| `download_attachment(uid, index, folder="INBOX", dest_subdir="", filename=None)` | Saves into the downloads directory; paths cannot escape it; never overwrites |
| `create_draft(to, subject, body, cc, bcc, reply_to_message_id, attachments, add_re_prefix)` | Builds the message and stores it **locally on the server host** (`DRAFT_DIR`), not in Exmail's Drafts (草稿) folder. With `reply_to_message_id` it sets In-Reply-To/References and uses the original subject if none is given. `add_re_prefix` (default `true` with `reply_to_message_id`, otherwise `false`) prefixes `Re: `; it is never doubled (skipped when the subject already starts with `Re:`, `RE:`, `回复:`, `答复:`, half- or full-width colon). Pass `add_re_prefix=false` to keep the subject exactly as given. Attachments are paths inside `ATTACH_DIR`. Returns `draft_id` and the full preview. **Sends nothing.** |
| `get_draft(draft_id)`, `list_drafts()` | Inspect stored drafts |
| `delete_draft(draft_id)` | Deletes an unsent local draft (files only). Refuses drafts that are `sending`, `sent` or `failed`, which are kept as the send record. Logged to `DRAFT_LOG` (recipients and subject, no body). |
| `send_draft(draft_id)` | **Sends email.** Sends exactly the stored draft once, then ensures a copy is in Sent |

### Incremental sync with `fetch_since`

Store `uidvalidity` and `next_since_uid` after each call. Next time call
`fetch_since(since_uid=<stored>, uidvalidity=<stored>)`. While `has_more` is true, call again with the
new `next_since_uid`. If the server has reset UIDs, the response has `uidvalidity_changed: true`, starts
again from UID 0, and you should discard stored UIDs. Fetching uses `BODY.PEEK` and batched
`UID FETCH` ranges (headers, then `BODYSTRUCTURE`, then only the text parts plus each attachment's
small MIME header), so attachment bodies are never downloaded and messages stay unread.

Attachment names: Exmail's `BODYSTRUCTURE` re-encodes long attachment names and truncates them
(observed: cut to 30 bytes). So names are decoded from each attachment part's own MIME header
(`BODY.PEEK[n.MIME]`) with the same function `get_message` uses (Content-Disposition `filename`
first, then Content-Type `name`; RFC 2231 continuations and RFC 2047 encoded-words). Sizes from
`BODYSTRUCTURE` are estimates for base64 parts (`size_approx: true`).

### Body text cleanup

Every tool that returns body text or snippets decodes leftover HTML entities (also double-escaped ones
such as `&amp;nbsp;`), turns NBSP into a normal space, removes stray control characters and trailing
spaces, and collapses runs of blank lines into one.

### Dates and time zones

Every message carries `date` (the raw header), `date_iso` (ISO 8601 in `DISPLAY_TZ` with offset, e.g.
`2026-01-15T09:30:00+08:00` with `DISPLAY_TZ=Asia/Shanghai`) and `date_utc` (`...Z`). `fetch_since`/`get_thread` also give
`internaldate_iso` (when the server received the message); `get_message` gives `internaldate_iso` and
`internaldate_utc` in its headers. If the Date header is missing or broken,
the server's INTERNALDATE is used. Conversion uses `zoneinfo` explicitly, so the container's `TZ`
does not matter. Draft `Date` headers are written in `DISPLAY_TZ`.

### Name matching (`from_` / `to`)

A term matches an address entry when, after NFKC normalisation and case folding, it is a substring of:
1. the decoded display name (`张三 <...>`), or
2. the email address;
3. for a Chinese name of 2+ characters, when the header entry has **no display name**, the pinyin of
   the name (`zhangsan`, or given name + surname `sanzhang`) is matched against the address's local
   part (separators ignored). This needs `pypinyin` (included). Homophones can match;
4. addresses listed for that name in the optional contacts file `contacts.json` (`CONTACTS_FILE`;
   format in `contacts.example.json`; the real file is git-ignored).

`matched_via` reports which rule matched. Limit: if a header has no display name, the local part
isn't the name's pinyin, and the contacts file has no entry, a search by name cannot find it. Search
by address instead, or add a contacts entry.

### Quoted history (`strip_quotes`)

`get_message`, `get_thread` and `fetch_since` accept `strip_quotes=true`. It cuts the text at the
first reply header (`On ... wrote:`, `-----Original Message-----`, `-----原始邮件-----`, QQ-style
`------------------ 原始邮件 ------------------`, `发件人:`, `在 ... 写道:`, or a `From:` line
followed by `Sent:/Date:/To:/Subject:/发送时间:` lines) and drops lines starting with `>`.
`quotes_stripped` says whether anything was removed. It's a heuristic: unusual client formats may
not be detected.

### Connections and performance

Read tools share a small pool (`IMAP_POOL_SIZE`, default 3) of logged-in connections. Each
connection has a lock and serves one request at a time. Connections are only ever in read-only
(EXAMINE) state. Connections idle over 30 s are checked with `NOOP`, and ones idle longer than
`IMAP_POOL_IDLE_SECONDS` are closed. On a connection error the request reconnects and retries once
(reads are idempotent). Each tool call uses one session for all its work. Drafts (reply lookups) and
sending always open their own fresh connections. Headers are cached in memory per
folder + UIDVALIDITY + UID. A typical repeat call takes about 0.5–2 s instead of about 3 s, since the
~2.6 s login is skipped.

## Safety model

- **Read-only reads.** Every folder is opened with `EXAMINE`; only `BODY.PEEK[...]`, `FLAGS`,
  `RFC822.SIZE` and similar non-mutating fetch items are allowed. The IMAP wrapper raises on
  `STORE`, `COPY`, `MOVE`, `EXPUNGE`, `DELETE`, `RENAME`, `CREATE`, non-peek fetches, and `APPEND`
  (which is unlocked only inside `send_draft` for the Sent copy).
- **Gate sending by tool name.** `send_draft` is the only tool that sends. Deny or require approval
  for it in your client and allow the rest.
- **Send once.** A draft is marked `sending` before SMTP starts, then `sent` or `failed`. Any
  status other than `draft` is refused, so a draft can never be sent twice and a failed send is
  never retried automatically. Bcc recipients are used for the envelope only, never written into
  headers.
- **Send log.** `SEND_LOG` (`send_log.jsonl`) records timestamp, draft id, recipients, subject,
  Message-ID, result and Sent-copy outcome. `DRAFT_LOG` (`draft_log.jsonl`) records draft creation and
  deletion. No bodies, no secrets.
- **Drafts are local.** Drafts live in `DRAFT_DIR` on the server host. Nothing is written to the
  mailbox until `send_draft`. `delete_draft` only removes unsent local drafts.
- **Secrets.** The mailbox password is only read from its file at login time (mounted read-only in
  Docker) and is never logged or returned. The bearer token is compared in constant time. Keep both
  files private: `chmod 600` on macOS/Linux, `icacls ... /inheritance:r` on Windows.
- **Files.** Downloads are confined to `DOWNLOAD_DIR`, outgoing attachments to `ATTACH_DIR`
  (mounted read-only in Docker); `..`, absolute paths and other drives are refused.
- **Network.** The native HTTP server listens on `127.0.0.1` unless you change `MCP_HOST`; see
  [Network and TLS](#network-and-tls).

## Is it faster than plain IMAP/SMTP?

Partly, and only after warm-up. It **is** IMAP and SMTP underneath, talking to the same Exmail
servers, so a cold fetch is not faster than a good IMAP client: Exmail needs roughly 50 ms per
message for header/`BODYSTRUCTURE` fetches and a login takes a couple of seconds.

Where it helps an agent:

- **Warm connection pool.** Read tools reuse logged-in, read-only connections, so most calls skip
  the login. A typical repeat call took about 0.5–2 s instead of about 3 s in testing.
- **Header cache** (memory and disk, per folder + UIDVALIDITY + UID). Thread and Message-ID lookups
  stop refetching headers; in testing a 4-message `get_thread` with bodies went from about 24 s to
  about 5 s.
- **Search that works.** Exmail's IMAP `SEARCH` ignores text criteria, so a plain IMAP script that
  relies on it silently gets every message back. This server filters on decoded headers instead.
- **Fewer agent tokens.** Compact structured JSON, decoded Chinese headers, HTML converted to text,
  entities cleaned and, with `strip_quotes`, quoted reply history removed.

Measured in real use, including the MCP handshake: `fetch_since` took 3–5 s when there was no new
mail and 9–11 s for about 10 new messages with bodies. A first catch-up over a few hundred messages
can take tens of seconds. Numbers vary with mailbox size and network.

## Why client-side text search?

Exmail's IMAP server ignores text criteria in `SEARCH` (`FROM`, `SUBJECT`, `HEADER`, `TEXT` and
`CHARSET UTF-8` searches all return every message in the folder). Date and flag criteria
(`SINCE`, `BEFORE`, `UNSEEN`) do work. So the server narrows by date/flags on the server, then
matches from/to/subject on the decoded headers itself. Exmail also needs roughly 50 ms per message
for any header or `BODYSTRUCTURE` fetch, so headers are cached per folder + UIDVALIDITY + UID in
memory and on disk (`HEADER_CACHE_DIR`, private to the user; headers never change for a UID), and the
cache for INBOX and Sent is filled in the background after startup. Repeated searches, threads and
Message-ID lookups therefore do not refetch headers. Use `since`/`before` on large
folders; at most `SEARCH_SCAN_CAP` (default 3000) newest candidates are scanned per call.

## Known limits

- **Tencent Exmail only.** Defaults point at `imap.exmail.qq.com` / `smtp.exmail.qq.com`, and the
  search, Sent-copy and filename handling are tuned to Exmail's IMAP quirks. Other servers are untested.
- **Text search is client-side.** Exmail's IMAP `SEARCH` ignores text criteria (`FROM`, `SUBJECT`,
  `TEXT`, `CHARSET UTF-8`), so only date/flag/UID narrowing happens on the server and from/to/subject
  are matched on decoded headers by this server. Use `since`/`before` on large folders; at most
  `SEARCH_SCAN_CAP` newest candidates are scanned per call. Body text is not searchable.
- **First-run cache warm-up.** Exmail answers header/`BODYSTRUCTURE` fetches at roughly 50 ms per
  message. On first start the server fills the header cache for INBOX and Sent in the background,
  which can take minutes on a large mailbox; the first `fetch_since` from UID 0 over a few hundred
  messages can take tens of seconds. Later calls hit the cache (`HEADER_CACHE_DIR`, can be disabled with
  `DISK_HEADER_CACHE=off` / `WARM_HEADER_CACHE=off`).
- **Truncated filenames in `BODYSTRUCTURE`.** Exmail cuts long attachment names inside
  `BODYSTRUCTURE` (observed at 30 bytes), so the server reads names from each part's MIME header
  instead. Sizes for base64 parts are estimates (`size_approx: true`).
- **Name search without display name.** See *Name matching*: pinyin matching can hit homophones,
  and names whose address isn't their pinyin need a contacts entry.
- **Drafts are local**, not in the mailbox Drafts (草稿) folder, so they don't appear in webmail.
- **No TLS in the server itself**; see [Network and TLS](#network-and-tls).
- **Platform testing.** CI runs the offline tests on Linux, macOS and Windows. Live mailbox use has
  been exercised on Linux (Docker); native macOS/Windows service setups above are standard recipes
  but less battle-tested.

## Tests

Offline tests need no network or mailbox and run on Linux, macOS and Windows (see
`.github/workflows/ci.yml`):

```bash
python -m venv .venv
.venv/bin/pip install -r requirements.txt                 # Windows: .venv\Scripts\pip ...
.venv/bin/python -m unittest discover -s tests -v         # Windows: .venv\Scripts\python ...
.venv/bin/python tests/smoke_transports.py                # starts stdio + HTTP (token) and lists tools
```

Live, read-only check against your mailbox (prints counts only, never sends, verifies the unread
count is unchanged):

```bash
docker compose exec -T exmail-mcp python - < tests/live_readonly_check.py   # Docker
EXMAIL_USER=you@example.com .venv/bin/python tests/live_readonly_check.py     # native
```

## License

MIT. See [LICENSE](LICENSE). Runtime dependencies are MIT (mcp, pydantic, anyio, pypinyin,
platformdirs, ...), BSD-3-Clause (uvicorn, starlette, httpx, ...), Apache-2.0 (python-multipart,
tzdata on Windows), PSF-2.0 and MPL-2.0 (certifi, used unmodified), all compatible with MIT.