Email MCP Server
by minjaf
README.md
# email-mcp
Small personal MCP server for a single mailbox over IMAP + SMTP.
It is aimed at a private setup first:
- one mailbox
- credentials supplied through environment variables
- read mail over IMAP
- send mail over SMTP
- works well with Yandex Mail defaults, but can be pointed at any IMAP/SMTP provider
## What I changed
This repo originally worked only in `stdio` mode. That is fine for local MCP clients, but **ChatGPT web integration needs an HTTP MCP endpoint**. The server now supports:
- `stdio` for local/dev use
- `streamable-http` for ChatGPT web app use
- `sse` for compatibility
I also fixed a mail-threading issue:
- the old `reply_to` parameter only set the `Reply-To` header
- real replies should usually use `In-Reply-To` and `References`
- `read_email` now returns those headers so they can be passed back into `send_email`
And I improved `read_email` output by returning:
- decoded headers
- attachment metadata
- message threading headers
## Attachment support
This version supports both reading and sending attachments.
### Download an attachment from a received email
1. Call `read_email(uid=..., folder="INBOX")`
2. Inspect the `attachments` list
3. For a remote MCP, call:
```text
create_attachment_download(
uid=123,
folder="INBOX",
attachment_index=0
)
```
It returns a `download_url` valid for 15 minutes and one successful GET:
```powershell
curl.exe --location `
--output "report.xlsx" `
"https://mail.example.com/attachments/download/dwl_..."
```
The response includes the original content type and an RFC 5987 encoded
filename. It uses `Cache-Control: no-store`; the token is consumed by the
first successful request. The attachment bytes do not pass through model
context.
For very small attachments, `get_attachment(...)` remains available. Use its
`attachment_index` or `filename`.
`get_attachment(...)` returns:
- `filename`
- `content_type`
- `size_bytes`
- `content_base64`
### Send attachments in outgoing email
`send_email(...)` accepts an `attachments` list.
When the MCP server runs on another machine, upload the local file first.
For Codex, the recommended method sends raw bytes directly over HTTPS without
printing base64 or putting it into model context:
1. Call:
```text
create_attachment_upload(
filename="report.xlsx",
size_bytes=55455,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
sha256="optional lowercase SHA-256"
)
```
2. Use its `upload_url` and `upload_token` from the local shell:
```powershell
curl.exe --request PUT `
--header "Authorization: Bearer <upload_token>" `
--header "Content-Type: application/octet-stream" `
--data-binary "@G:\path\report.xlsx" `
"https://mail.example.com/attachments/upload"
```
The response contains `attachment_id`. The upload session is single-use and
expires after 15 minutes. File bytes travel directly from the local HTTP client
to the remote MCP server and never pass through model output.
Configure the remote server's public HTTPS origin:
```dotenv
MCP_PUBLIC_BASE_URL=https://mail.example.com
```
Use the origin only, without the MCP endpoint path such as `/mcp`. The reverse
proxy must forward `/attachments/upload` to this application, allow `PUT`, and
permit request bodies up to the configured attachment limit.
For very small files, base64 upload remains available:
```text
upload_attachment(
filename="report.xlsx",
content_base64="...",
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
sha256="optional lowercase SHA-256"
)
```
The result contains an opaque `attachment_id`. Pass it to `send_email`,
`reply_to_email`, or `create_draft`:
```json
{"attachment_id": "att_..."}
```
Uploads are stored temporarily on the MCP server and expire after 24 hours.
Use `delete_attachment(attachment_id)` to remove one earlier. Local filesystem
paths refer to the MCP server machine and must not be used for files that exist
only on the ChatGPT/Codex machine.
The default decoded-file limit is **5 MiB per attachment**, with a **10 MiB
combined attachment limit per message**. Base64 is approximately 33% larger
than the decoded file. Limits can be configured with:
```dotenv
MAIL_ATTACHMENT_MAX_BYTES=5242880
MAIL_ATTACHMENT_TOTAL_MAX_BYTES=10485760
MAIL_ATTACHMENT_DIR=/var/lib/email-mcp/attachments
```
For a local MCP process that shares the filesystem, an item can also use:
```json
{"path": "/path/to/file.pdf"}
```
```json
{"filename": "note.txt", "content_text": "hello from MCP"}
```
```json
{"filename": "report.pdf", "content_base64": "JVBERi0x...", "content_type": "application/pdf"}
```
## Sent folder behavior
After SMTP send succeeds, the same MIME message is appended to your IMAP sent folder.
By default that folder name is:
```bash
Sent
```
You can override it if your mailbox uses a different IMAP folder name:
```bash
export SENT_FOLDER="Sent"
# or
export MAILBOX_SENT_FOLDER="Sent"
```
If sent mail does not show up, first run `list_folders()` and use the exact folder name returned by your mailbox.
## Files
- `server.py` — MCP tool definitions and transport startup
- `mail_ops.py` — IMAP/SMTP implementation
- `requirements.txt` — Python dependencies
## Environment
Required:
```bash
export MAILBOX_EMAIL="you@example.com"
export MAILBOX_PASSWORD="your-app-password"
```
For local development, you can instead create a `.env` file beside
`server.py`:
```dotenv
MAILBOX_EMAIL=you@example.com
MAILBOX_PASSWORD=your-app-password
```
The `.env` file is ignored by Git. Environment variables already supplied to
the process take precedence over values in `.env`.
Optional provider settings:
```bash
export IMAP_HOST="imap.yandex.com"
export IMAP_PORT="993"
export SMTP_HOST="smtp.yandex.com"
export SMTP_PORT="465"
```
Optional sent-folder setting:
```bash
export SENT_FOLDER="Sent"
```
Optional MCP server settings:
```bash
export MCP_TRANSPORT="stdio"
export MCP_HOST="0.0.0.0"
export MCP_PORT="8000"
```
Aliases also supported for convenience:
```bash
export YANDEX_EMAIL="you@yandex.ru"
export YANDEX_APP_PASSWORD="..."
```
## Install
```bash
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
## Run locally with stdio
```bash
python server.py
```
This is the right mode for local MCP clients that spawn the process directly.
## Run for ChatGPT web app
ChatGPT web needs a public HTTPS MCP endpoint. Start the server in HTTP mode:
```bash
python server.py --transport streamable-http --host 0.0.0.0 --port 8000
```
Then expose that port through a public HTTPS tunnel or reverse proxy, and register the resulting MCP URL in ChatGPT.
## Tools exposed
### Health and folders
- `get_status()` checks IMAP and SMTP authentication without sending mail.
- `list_folders()` returns provider folder names and special-use flags.
- `create_attachment_upload()` prepares a direct binary upload that bypasses
model context.
- `create_attachment_download()` returns a short-lived, single-use binary URL
for a received attachment.
- `upload_attachment()` transfers a small file to temporary remote storage.
- `delete_attachment()` removes a temporary upload.
### `list_folders()`
Lists available IMAP folders.
### `search_emails(folder="INBOX", text=None, unseen_only=False, since_date=None, limit=30)`
Searches messages by IMAP criteria.
Returns items like:
- `uid`
- `subject`
- `from`
- `to`
- `date`
- `flags`
- `size_bytes`
### `read_email(uid, folder="INBOX")`
Fetches a full message without marking it read.
Returns:
- decoded headers
- `message_id`
- `in_reply_to`
- `references`
- `attachments`
- `body_plain`
- `body_html`
### `get_attachment(uid, folder="INBOX", attachment_index=None, filename=None)`
Fetches a single attachment and returns it as base64.
### `send_email(...)`
Sends a message through SMTP.
Important parameters:
- `reply_to_header` — sets the Reply-To header
- `in_reply_to` — threading header
- `references` — threading header
- `attachments` — optional list of attachment specs
For a real reply, use `in_reply_to` and usually also `references`.
Supply a unique `idempotency_key` for every logical send. Results distinguish
`sent`, `sent_but_not_saved`, `failed_before_send`, and
`delivery_uncertain`, and include `safe_to_retry`.
### Mailbox-wide retrieval
- `search_mailbox(...)` searches Inbox, Sent, and Archive by default with
structured participant, subject, body, and date filters.
- `read_emails(...)` batch-reads up to 50 results.
- `search_threads(...)` groups matching messages across folders.
- `read_thread(...)` reads an RFC-header-based thread chronologically.
- `find_correspondents(...)` resolves people from parsed address headers.
- `find_sent_examples(...)` returns cleaned authored text for style analysis.
### Replies and drafts
- `reply_to_email(...)` derives recipients and RFC thread headers.
- `create_draft(...)`, `list_drafts(...)`, `read_draft(...)`,
`update_draft(...)`, `send_draft(...)`, and `delete_draft(...)` provide a
review-before-send workflow.
### Local search index
`sync_search_index(...)` incrementally indexes normal mailbox folders into
the Git-ignored `.mail_index.sqlite3` database. Synchronization tracks folder
UIDVALIDITY and the last indexed UID.
`search_index(...)` performs ranked Unicode FTS5 retrieval with snippets.
Its optional `approximate` mode broadens words into local prefix alternatives.
No message content is sent to an external embedding service.
## Yandex notes
Typical Yandex defaults are:
- IMAP: `imap.yandex.com:993` over SSL/TLS
- SMTP: `smtp.yandex.com:465` over SSL/TLS
Use an **app password**, not your main account password.
## Tests
Run the offline test suite with:
```bash
python -m pytest
```
The suite covers structured errors, special folders, idempotent and partial
sending states, Unicode search construction, pagination, reply headers,
thread grouping, drafts, MIME body cleaning, and local FTS synchronization.
This server cannot be deployed
Maintenance
ActivityStale
ResponsivenessNo issues