mail-mcp
# mail-mcp
A local MCP server that lets Claude Code manage one mailbox over IMAP and SMTP.
Built for Namecheap Private Email; nothing in it is specific to that provider except the default host name.
- The app password lives in the system keyring, never in a file.
- Delete means "move to Trash". Nothing here can erase mail.
- Every change and every send is written to a local action log.
- Email content is treated as untrusted: hidden text is stripped, and everything that came from an email is fenced off in tool results.
- Sending is four separate tools, so Claude Code can require approval for those and nothing else.
## Install
```bash
cd ~/Claude/mail-mcp
python3 -m venv .venv
.venv/bin/pip install -e .
```
Add `'.[dev]'` instead of `.` if you want to run the tests.
## Set up the account
Run these in a terminal. The password prompt needs a real terminal and hides what you type.
Give each mailbox a name of your own. The name is what you and Claude call it.
```bash
.venv/bin/mail-mcp setup --profile "Work Mail"
```
`setup` asks for the address and the app password, tries one IMAP login, and only then stores the password in the keyring (GNOME Keyring or KWallet, service name `mail-mcp`). It writes `~/.config/mail-mcp/profiles/work-mail.toml`, which holds no secret. It then shows the server entry and permission rules it wants to add to Claude Code and adds them if you agree.
```bash
.venv/bin/mail-mcp doctor --profile work-mail
```
`doctor` logs in and reports what the server supports and which folders it identified as Sent, Drafts and Trash. It changes nothing.
```bash
.venv/bin/mail-mcp doctor --profile work-mail --probe-sent
```
The probe sends one short message from you to yourself (it asks first), then looks for it in Sent. That tells it whether the server saves sent mail by itself, and it offers to set `save_sent` in the config to match.
### No keyring
On a machine with no Secret Service (a headless box, an SSH session), `setup` stops and says so. The alternative is a command that prints the password, set in the config:
```toml
[account]
password_command = ["pass", "show", "mail/app-password"]
```
The config then names a command and still holds no secret. There is deliberately no plaintext-file or environment-variable option.
## Several mailboxes
One installed program serves any number of mailboxes. Each mailbox is a profile: its own settings file and its own server in Claude Code, named `mail-<profile>`. A running server only ever reaches its one mailbox.
| Command | What it does |
|---|---|
| `mail-mcp help` | List the commands with a short description of each |
| `mail-mcp setup --profile "Name"` | Set up a mailbox and offer to connect it to Claude Code |
| `mail-mcp profiles` | List the mailboxes, and whether each is registered with its rules in place |
| `mail-mcp doctor --profile name` | Check one mailbox |
| `mail-mcp register --profile name` | Add (or re-add) its server entry and permission rules |
| `mail-mcp remove --profile name` | Remove its settings, stored password and Claude Code entries, after confirming |
Every server tells Claude which mailbox it is and which others exist. When more than one is available and you have not said which mailbox you mean, Claude is instructed to ask and never to pick one, including for searching and reading. With a single mailbox there is nothing to ask.
The hourly send limit is counted per mailbox. All mailboxes share one action log, and every line records the account.
Without `--profile`, the commands use an unnamed default mailbox at `~/.config/mail-mcp/config.toml`, registered as `mail`.
## Register with Claude Code
`setup --profile` and `register --profile` do this for you. The manual steps, for a profile named `work-mail`:
With the CLI:
```bash
claude mcp add --transport stdio --scope user mail-work-mail -- /path/to/mail-mcp/.venv/bin/mail-mcp serve --profile work-mail
```
Without the CLI, add the same entry by hand to `~/.claude.json`, inside the top-level `"mcpServers"` object (the desktop app's Code tab reads user-scope servers from there):
```json
"mail-work-mail": {
"type": "stdio",
"command": "/path/to/mail-mcp/.venv/bin/mail-mcp",
"args": ["serve", "--profile", "work-mail"]
}
```
Start a new session afterwards. `/mcp` should list `mail-work-mail` as connected.
### Permissions
In `~/.claude/settings.json`, allow the thirteen tools that read or make reversible changes, and require approval for the four that send:
```json
{
"permissions": {
"allow": [
"mcp__mail-work-mail__list_folders",
"mcp__mail-work-mail__search_messages",
"mcp__mail-work-mail__read_message",
"mcp__mail-work-mail__get_thread",
"mcp__mail-work-mail__read_attachment",
"mcp__mail-work-mail__save_attachment",
"mcp__mail-work-mail__set_flags",
"mcp__mail-work-mail__move_messages",
"mcp__mail-work-mail__delete_messages",
"mcp__mail-work-mail__create_folder",
"mcp__mail-work-mail__rename_folder",
"mcp__mail-work-mail__delete_folder",
"mcp__mail-work-mail__save_draft"
],
"ask": [
"mcp__mail-work-mail__send_email",
"mcp__mail-work-mail__reply_email",
"mcp__mail-work-mail__forward_email",
"mcp__mail-work-mail__send_draft"
]
}
}
```
The allowed tools are listed by name on purpose. A tool added later will prompt until you decide about it. An `ask` rule wins over an `allow` rule, so the send tools prompt even if you later allow the whole server.
## Tools
A message is always addressed by `folder` + `uidvalidity` + `uid`, all taken from `search_messages`.
| Tool | What it does |
|---|---|
| `list_folders` | Folders with role, message count, unread count, uidvalidity |
| `search_messages` | Search by sender, recipient, subject, body, date range, read state, flag; one folder or `all` |
| `read_message` | Headers, sanitised body (paged), attachment list, suggested reply recipients. Does not mark as read. |
| `get_thread` | The conversation across the message's folder, Inbox, every Sent folder and Archive; `all_folders` searches the whole mailbox |
| `read_attachment` | Text of text-like attachments (paged) |
| `save_attachment` | Writes an attachment to the download folder; never overwrites |
| `set_flags` | Read/unread, flag/unflag |
| `move_messages` | Move; returns the new uids |
| `delete_messages` | Move to Trash |
| `create_folder`, `rename_folder` | Folder management; special folders cannot be renamed |
| `delete_folder` | Only an empty folder with no subfolders |
| `save_draft` | New draft, reply draft, forward draft, or a revision of an earlier draft |
| `send_email` | Send a new message |
| `reply_email` | Reply in-thread. Recipients are explicit; reply-all means passing the reply-all set that `read_message` suggested. |
| `forward_email` | Forward text and attachments |
| `send_draft` | Send a stored draft as it is |
### Why the send tools take so many inputs
Claude Code's approval prompt shows a tool's inputs and nothing else. So each send tool carries, as inputs, what you need to judge it:
- every recipient, always explicit, never worked out by the server;
- for `reply_email` and `forward_email`, an `expected_subject` that the server checks against the real message, so the prompt shows which message is involved and a wrong uid sends nothing;
- for `send_draft`, the full recipient list, subject and attachment names, all verified against the stored draft.
## What is enforced, and what is not
**Enforced in code and covered by tests**
- UIDs only, with UIDVALIDITY checked on every call that names a message. A mismatch aborts.
- UIDs that no longer exist are reported, not silently skipped.
- No `EXPUNGE` and no `CLOSE` anywhere. Without server-side MOVE, the fallback expunges only the exact UIDs it copied; with neither MOVE nor UIDPLUS it refuses.
- A folder that holds messages or subfolders cannot be deleted.
- If the action log cannot be written, the action does not run.
- A rejected login is not retried by the same process.
- Outgoing attachments must sit inside the configured folders. Hidden paths are refused, and symlinks are resolved before the check.
- Saved attachments cannot leave the download folder, whatever their filename says.
- Unencrypted or unverified connections are accepted only for a loopback host (the test server).
- Per-call limits, with ceilings the config cannot raise.
**Best effort**
The HTML sanitiser models what a desktop mail client shows and removes the rest: `display:none`, hidden visibility, near-zero opacity, type under 6px, transparent or near-background colours, zero-size clipped boxes, off-screen positioning, `<style>` rules that do any of those, comments, scripts, image alt text, and invisible Unicode. It is a heuristic. CSS offers more ways to hide text than it knows, text inside images is untouched, and files Claude opens with its own tools never pass through it. When it cannot tell, it removes. The control that actually holds is your approval on the send tools.
`aria-hidden` is not treated as hidden, because it does not hide text from a sighted reader.
**Outside this server**
An email could try to get Claude to leak mail through other tools it has, such as web requests or the shell. Those are governed by your wider Claude Code permissions.
## Configuration
`~/.config/mail-mcp/profiles/<profile>.toml` for a named mailbox, or `~/.config/mail-mcp/config.toml` for the unnamed default (override that one with `MAIL_MCP_CONFIG`):
| Section | Keys |
|---|---|
| `[account]` | `email`, `display_name`, `label` (the mailbox's name), optional `password_command` |
| `[imap]`, `[smtp]` | `host`, `port`, `security` (`ssl` or `starttls`) |
| `[folders]` | `sent`, `drafts`, `trash`, `junk`, `archive`: only when `doctor` could not identify one |
| `[sending]` | `save_sent`: `append` (save a copy to Sent, skipped if one is already there) or `server` |
| `[attachments]` | `outgoing_roots`, `download_dir` |
| `[limits]` | see below |
| `[log]` | `path` |
| Limit | Default | Ceiling |
|---|---|---|
| `search_default` / `search_max` | 25 / 100 | 100 |
| `body_chars_default` / `body_chars_max` | 12,000 / 50,000 | 50,000 |
| `thread_messages_default` / `thread_messages_max` | 20 / 50 | 50 |
| `thread_chars` | 30,000 | 60,000 |
| `attachment_chars_default` / `attachment_chars_max` | 12,000 / 50,000 | 50,000 |
| `attachment_save_bytes` | 25 MB | 25 MB |
| `bulk_uids` (messages per change call) | 50 | 200 |
| `outgoing_bytes` | 25 MB | 80 MB |
| `recipients` (per message) | 25 | 100 |
| `sends_per_hour` | 20 | 100 |
## Action log
`~/.local/state/mail-mcp/actions.jsonl`, readable only by you, rotated at 10 MB. Each action writes an `intent` line before it runs and an `outcome` line after, sharing an `id`:
```json
{"ts": "2026-11-20T15:02:11.482-05:00", "account": "you@example.com", "id": "9f2c41aa03be", "tool": "delete_messages", "kind": "change", "phase": "outcome", "ok": true, "details": {"folder": "INBOX", "uidvalidity": 1700000000, "destination": "Trash", "missing": [], "messages": [{"uid": 4312, "message_id": "<abc@example.org>", "from": ["Bob <bob@example.org>"], "subject": "Invoice 42", "date": "2026-11-19T09:14:00+00:00"}], "destination_uidvalidity": 1700000007, "new_uids": {"4312": 88}}}
```
Bodies are never logged; sends record recipients, subject, Message-ID, attachment names, size and a hash.
## Tests
```bash
.venv/bin/pip install -e '.[dev]'
.venv/bin/python -m pytest
```
The suite cannot reach a real mailbox. A fixture applied to every test refuses any connection or DNS lookup that is not loopback, replaces the keyring with an in-memory fake, and points config and state at a temporary folder.
Integration tests start a throwaway Dovecot container (`dovecot/dovecot`, the same server software Private Email runs) on a loopback port and an in-process SMTP sink. They need Docker and are skipped without it; the unit tests run regardless.
## Layout
```
src/mail_mcp/
cli.py serve | setup | doctor | profiles | register | remove
register.py Claude Code server entry and permission rules
server.py tool registration and server instructions
app.py shared state; marks every tool read / change / send
config.py credentials.py folders.py actionlog.py
imap_session.py one connection, UIDVALIDITY checks, reconnect
parse.py headers, MIME structure, part-by-part fetching
sanitize.py HTML to visible text; invisible-character removal
envelope.py fencing of email-derived text in results
compose.py smtp_send.py
tools/ read.py organize.py outgoing.py
tests/ unit/ integration/ docker/
```
## License
MIT. See [LICENSE](LICENSE).
TDQS
Scored across 17 tools
Each tool targets a distinct resource+action: folder CRUD (create/delete/rename/list), message operations (read/search/delete/move/flags), thread lookup, attachment read vs. save, and send family (send_email, reply_email, forward_email, save_draft, send_draft). The potentially overlapping pairs (read_attachment vs. save_attachment, send_email vs. send_draft) are explicitly delineated in their descriptions.
All 17 tools follow a consistent verb_noun snake_case pattern (get_thread, list_folders, read_message, search_messages, create_folder, delete_messages, move_messages, set_flags, reply_email, save_draft, etc.). No camelCase or stylistic divergence appears.
17 tools sit slightly above the ideal 3-15 band, but the breadth is justified by a full mail client covering folders, messages, attachments, drafts, and sending. Each tool earns its place; nothing is obviously redundant.
Covers the full lifecycle: folder CRUD, message read/search/delete/move/flags, thread lookup, attachment read/save, and a complete send/draft flow. Minor gaps remain—no hard/permanent delete or empty-trash operation, and folder-scoped listing relies on search_messages rather than a dedicated tool—but these are workable or intentionally omitted for safety.