A powerful Model Context Protocol (MCP) server for IMAP email integration with Claude
SaferSkills independently audited Imap Mcp Server (Agent Skill) and scored it 100/100 (green). The audit ran 55 deterministic rules across Security, Supply Chain, Maintenance, Transparency, and Community; it found 0 high-severity and 0 lower-severity findings. The full rule-by-rule trace and per-finding evidence are below. Free, methodology-open.
Findings & checks · 0 flagged
Every scanned point with the score it earned and what moved between them.
First recorded scan — no prior version to compare against.
The primary manifest — the file an agent reads to learn what this artifact does.
A powerful Model Context Protocol (MCP) server that provides seamless IMAP email integration with secure account management and connection pooling.
Requires Node.js 22.12 or newer. Node 18 and 20 have both reached end-of-life, and several of this package's dependencies no longer support them. Check yours with node --version.Once published to npm, you can run the server directly without cloning or building anything — npx downloads the prebuilt package and runs it:
npx -y imap-mcp-serverThis is the easiest way to use the server in an MCP client (see Configuration for ready-to-paste npx configs).
#### macOS/Linux:
curl -fsSL https://raw.githubusercontent.com/nikolausm/imap-mcp-server/main/install.sh | bash#### Windows (PowerShell as Administrator):
iwr -useb https://raw.githubusercontent.com/nikolausm/imap-mcp-server/main/install.ps1 | iexgit clone https://github.com/nikolausm/imap-mcp-server.git
cd imap-mcp-servernpm installnpm run buildAccounts are stored encrypted in ~/.imap-mcp/accounts.json. This file is shared by all run modes — whether you start the server via npx, a global install, or a local clone, they all read the same accounts. So you only need to set up your accounts once.
If you run the server via npx (no clone), you have two ways to add accounts:
Option A — Run the setup wizard directly via npx (no install needed):
npx -p imap-mcp-server imap-setupThis launches the same web-based wizard described below and writes to ~/.imap-mcp/accounts.json, which your npx-configured MCP server then picks up automatically.
Option B — Add accounts straight from your AI client:
Once the MCP server is configured, just ask your assistant to add an account — it uses the imap_add_account tool. For example:
"Add my IMAP account: host imap.gmail.com, port 993, user [email protected], password …"
No separate setup step required.
After installation, run the setup wizard:
npm run setupOr if installed globally:
imap-setupOr directly via npx without installing:
npx -p imap-mcp-server imap-setupThis will:
The wizard listens on 127.0.0.1 only, so nothing else on your network can reach it.
#### Running the wizard on another machine (server, NAS, VM)
Recommended: SSH tunnel. The wizard stays on loopback, and the connection is encrypted:
ssh -L 3000:localhost:3000 my-server # then, on the server:
imap-setup --no-openOpen http://localhost:3000 in your local browser.
Alternative: bind to the network. Pass --host (or set IMAP_MCP_BIND):
imap-setup --host 0.0.0.0 --no-openThe wizard then requires an access token and prints a URL containing it, e.g. http://my-server:3000/?token=…. Open that URL; the token is exchanged for a session cookie and removed from the address bar. Requests without the token are refused, and so are cross-origin requests. Scripts can send Authorization: Bearer <token> instead. To use a fixed token rather than a random one per start, set IMAP_MCP_WIZARD_TOKEN (at least 16 characters); it is then not printed.
The connection is plain HTTP, so anyone who can read your network traffic can see the token and the passwords you enter. Use this only on networks you trust, and prefer the SSH tunnel otherwise.
| Variable | Default | Meaning |
|---|---|---|
IMAP_MCP_BIND | 127.0.0.1 | Address the wizard binds to (--host takes precedence) |
IMAP_MCP_WIZARD_TOKEN | random per start | Access token when bound beyond loopback |
PORT | 3000 | Port for npm run web (imap-setup uses --port) |
You can override the username and password of an already-configured account at runtime with environment variables — useful when you inject secrets from a password manager or CI system instead of storing them in accounts.json.
The variables are keyed by the account name, uppercased with every non-alphanumeric character replaced by _. For an account named Work Gmail (key WORK_GMAIL):
| Variable | Overrides |
|---|---|
IMAP_MCP_ACCOUNT_WORK_GMAIL_IMAP_USERNAME | IMAP username (user) |
IMAP_MCP_ACCOUNT_WORK_GMAIL_IMAP_PASSWORD | IMAP password |
IMAP_MCP_ACCOUNT_WORK_GMAIL_SMTP_USERNAME | SMTP username (smtp.user) |
IMAP_MCP_ACCOUNT_WORK_GMAIL_SMTP_PASSWORD | SMTP password |
Notes:
matches, the variable is ignored.
accounts.json, and the values are used as-is (not re-encrypted).
an AES-256-encrypted in-memory cache and removed from process.env, so the plaintext secret does not linger in the environment (where it could leak to child processes or diagnostics). Set them before launching the server.
The setup wizard integrates with this: each credential field (IMAP password, IMAP username, SMTP username, SMTP password) has a "Do not save to config; set later using an environment variable" checkbox. When ticked, the value you enter is still used to test the connection, but it is not written to accounts.json — the wizard shows the exact variable name to export, and the account picks the credential up from that variable at runtime.
If the variable is missing, the account still holds the empty placeholder the wizard wrote. Rather than dialing out with a blank credential — which providers answer with a generic authentication failure that looks exactly like a wrong password — the server refuses the connection and names what to set:
Account "Work Gmail" has IMAP credentials marked as environment-managed, but
this variable was not set when the server started:
IMAP_MCP_ACCOUNT_WORK_GMAIL_IMAP_PASSWORD. Set it and restart the server, or
store the credentials on the account via imap_update_account.Because the variables are read once at startup, setting one in an already-running shell has no effect until the server is restarted.
The setup wizard includes pre-configured settings for:
#### Option A — via npx (no clone/build needed)
claude mcp add imap -- npx -y imap-mcp-serverThis always runs the latest published version and requires no local build.
#### Option B — from a local clone
If you use Claude Code in the terminal, add the MCP server with a single command:
Step 1: Make sure you have built the project first (see Manual Installation).
Step 2: Run this command in your terminal:
claude mcp add imap -- node /absolute/path/to/imap-mcp-server/dist/index.jsImportant: Replace /absolute/path/to/imap-mcp-server with the actual path where you cloned the repository. For example: ```bash # macOS/Linux example: claude mcp add imap -- node /Users/yourname/imap-mcp-server/dist/index.js>
# Windows example: claude mcp add imap -- node C:\Users\yourname\imap-mcp-server\dist\index.js ```
Step 3: Verify it was added:
claude mcp listYou should see imap in the list of configured MCP servers. That's it — the IMAP tools are now available in your Claude Code sessions.
Tip: If you want to remove the server later, run: ``bash claude mcp remove imap ``Add the IMAP MCP server to your Claude Desktop configuration file:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json
Option A — via npx (recommended, no clone/build needed):
{
"mcpServers": {
"imap": {
"command": "npx",
"args": ["-y", "imap-mcp-server"],
"env": {}
}
}
}Option B — from a local clone:
{
"mcpServers": {
"imap": {
"command": "node",
"args": ["/path/to/imap-mcp-server/dist/index.js"],
"env": {}
}
}
}By default all tools are exposed. You can restrict which tools the agent sees using two environment variables (set them under the env key of your MCP config). This is useful when you want to give an assistant read-only access to a mailbox, or expose only a hand-picked subset of tools.
| Variable | Effect |
|---|---|
IMAP_MCP_READ_ONLY | When truthy (1, true, yes, on), only the safe, read-only tools are registered — searching, reading, listing folders, unread counts, spam analysis. No tool that sends mail, deletes/moves messages, changes flags, or edits accounts is exposed. |
IMAP_MCP_ENABLED_TOOLS | Comma-separated allowlist of tool names — only these are registered. Names are case-insensitive and the imap_ prefix is optional (search_emails ≡ imap_search_emails). When set, it takes precedence over IMAP_MCP_READ_ONLY. |
Example — read-only access:
{
"mcpServers": {
"imap": {
"command": "npx",
"args": ["-y", "imap-mcp-server"],
"env": { "IMAP_MCP_READ_ONLY": "true" }
}
}
}Example — explicit allowlist:
{
"mcpServers": {
"imap": {
"command": "npx",
"args": ["-y", "imap-mcp-server"],
"env": { "IMAP_MCP_ENABLED_TOOLS": "imap_search_emails,imap_get_email,imap_get_latest_emails" }
}
}
}The read-only subset is: imap_list_accounts, imap_connect, imap_disconnect, imap_test_account, imap_search_emails, imap_get_email, imap_get_latest_emails, imap_download_attachment, imap_find_thread_messages, imap_find_email_by_message_id, imap_list_folders, imap_folder_status, imap_get_unread_count, imap_check_spam, imap_domain_stats, imap_list_spam_domains.
Once configured, the IMAP MCP server provides the following tools in Claude:
Choosing an account. For the email and folder tools,accountIdis optional and backward-compatible. You may instead passaccountName, and if you only have a single account configured you can omit both — that account is used by default. With multiple accounts and no selector, the tool returns a clear error listing your options (imap_list_accounts).
Parameters:
- name: Friendly name for the account
- host: IMAP server hostname
- port: Server port (default: 993)
- user: Username
- password: Password
- tls: Use TLS/SSL (default: true)
- allowStartTLS: When tls is false, set to false to also disable the
opportunistic STARTTLS upgrade imapflow otherwise attempts whenever the
server advertises it (validating the cert against `host` regardless of
`tls`). Needed for providers that advertise STARTTLS on a hostname
covered only by a shared/wildcard cert. Defaults to true.
- sentFolder: Explicit Sent-folder name for sent-mail copies, e.g. "Gesendet"
(optional — only needed when the server has no \Sent SPECIAL-USE folder
and auto-detection fails)
- defaultBcc: Optional BCC address(es) applied automatically to every
outbound send, reply, forward, and draft for this account. Merged with
any per-call `bcc` (duplicates removed case-insensitively)
- allowedFrom: Optional list of additional sender identities permitted in
outbound `From` headers. The account email and login are always allowed Parameters:
- accountId: ID of the account to update
- name, host, port, user, password, tls, allowStartTLS, email: IMAP fields (all optional)
- smtpHost, smtpPort, smtpSecure, smtpUser, smtpPassword: SMTP fields (optional)
- saveToSent: Save sent emails to the Sent folder (optional)
- sentFolder: Explicit Sent-folder override (optional). Pass an empty string
to clear the override and re-enable auto-detection
- defaultBcc: Optional default BCC address(es) (optional). Pass an empty
string to clear
- allowedFrom: Optional list of additional sender identities. Pass an empty
array to clearallowedFrom is an application-level guardrail, not a hard security boundary: an agent with access to imap_update_account can change the allowed identities. The SMTP server must enforce the actual sender authorization policy. Sender mailbox addresses are matched case-insensitively; the supplied display name and address casing are preserved in the outbound From header. This applies to sending, drafts, replies, and forwards.
Parameters:
- accountId: ID of the account to remove Parameters:
- accountId OR accountName: Account identifier Parameters:
- accountId: Account to disconnect Parameters:
- accountId: Account ID
- folder: Folder name (default: INBOX; ignored when searchAllFolders is true)
- searchAllFolders: Search across ALL folders at once (default: false).
Skips Trash/Spam/Drafts and non-selectable folders by default. Use when a
message may have been filed/moved/archived and you don't know its folder.
- includeTrash, includeSpam, includeDrafts: Opt those noisy folders back into
a searchAllFolders run (default: false each)
- from, to, subject, body: Search criteria
- since, before: Date filters
- seen, flagged: Status filters
- keywords: Match messages with ANY of these custom keywords (server-side OR).
Read a mailbox's available custom keywords from `imap_folder_status`'s
`customKeywords` field first.
- unKeywords: Exclude messages with ANY of these custom keywords (result has
NONE of them). Same keyword source as `keywords`.
- limit: Max results (default: 50)
- includeBody: Include parsed message body in the response (default: false).
Fetches the RFC822 source once and parses it with mailparser, so you get
uid + body in a single tool call instead of paying the N+1 cost of one
`imap_get_email` per match. Body is rendered per `bodyFormat` and capped
at `bodyMaxLength` per field.
- bodyFormat: How to render the body when `includeBody` is true — `markdown`
(default, clean Markdown via Turndown), `text`, `html`, or `auto`.
- bodyMaxLength: Per-field cap when `includeBody` is true (default: 10000).WithsearchAllFolders, results include afolderfield per message plusfoldersSearched, and any folder that failed to open is reported infoldersErrored(so a 0-result answer is never silently incomplete).
>
includeBodyis honored in the single-folder path only. For a cross-folder sweep the lightweight header shape is preserved by design — pulling RFC822 source for every match across many folders would multiply bandwidth and parse cost. Follow up withimap_get_emailfor the specific uids whose bodies you need.
>
On some servers a "flagged"/starred message carries a custom keyword (e.g. an Open-Xchange color label or Apple's$MailFlagBit*) instead of, or in addition to, the\Flaggedsystem flag — after any flagged search, check each result'scustomKeywordsfield before concluding a message is or isn't flagged.
Parameters:
- accountId: Account ID
- folder: Folder name
- uid: Email UID
- maxContentLength: Max characters for text/html body (default: 10000)
- includeAttachmentText: Include text attachment previews (default: true)
- maxAttachmentTextChars: Max characters per text attachment (default: 100000) Parameters:
- accountId: Account ID
- folder: Folder name (default: INBOX)
- count: Number of emails (default: 10)
- includeBody: Include parsed message body (default: false). Same semantics
as the `includeBody` option on `imap_search_emails` — one round-trip
instead of N×`imap_get_email`.
- bodyFormat: `markdown` (default), `text`, `html`, or `auto`.
- bodyMaxLength: Per-field cap (default: 10000). Parameters:
- accountId: Account ID
- folder: Folder name
- uid: Email UID, OR an array of UIDs to flag in one call. Batch uses a
single IMAP STORE so the operation is atomic at the server level — all
UIDs are flagged, or none. Useful when triaging many messages at once.$cl_N, $MailFlagBit*) when flagging; unflag only clears \Flagged, so if a message still shows as flagged, check customKeywords via imap_get_email and clear it with imap_remove_keyword. Parameters:
- accountId: Account ID
- folder: Folder name
- uid: Email UID$cl_1..$cl_10 or Apple Mail's $MailFlagBit0..$MailFlagBit2, or any other custom keyword). Backslash-prefixed system flags (e.g. \Flagged, \Seen, \Deleted) are rejected — use the dedicated flag/read tools for those. Not every server permits custom-keyword changes (see the mailbox's PERMANENTFLAGS); if the server rejects or silently ignores the change, the call fails instead of reporting success. Parameters:
- accountId: Account ID
- folder: Folder name
- uid: Email UID
- keyword: IMAP keyword to set/remove (e.g. "$cl_3") Parameters:
- accountId: Account ID
- folder: Folder name
- uid: Email UID Parameters:
- accountId: Account ID
- folder: Source folder name (default: INBOX)
- uid: Email UID, OR an array of UIDs to move in one call. Batch moves are
attributed per-uid in the response (`results[]` with per-uid `uidMap`
and any errors). Single-uid calls return the legacy response shape.
- targetFolder: Destination folder name
- createDestinationIfMissing: Create the destination folder if it does not exist (default: false) Parameters:
- accountId: Account ID
- sourceFolder: Folder containing the already-sorted thread messages
- searchFolder: Folder to search for related messages (default: INBOX)
- searchReferences: Also match the References header for multi-level threads (default: true)
- includeBody: Include parsed message body for each found thread message
(default: false). Same semantics as the `includeBody` option on
`imap_search_emails` — one round-trip instead of N×`imap_get_email`.
- bodyFormat: `markdown` (default), `text`, `html`, or `auto`.
- bodyMaxLength: Per-field cap (default: 10000). Parameters:
- accountId: Account ID
- folder: Folder name (default: INBOX)
- uid: Email UID
- filename: Attachment filename or contentId (as listed by imap_get_email; NFC/NFD
spellings of accented characters are treated as equal, and a contentId may
be passed with or without angle brackets)
- savePath: Optional file path to save the attachment to
- extractText: For PDFs, extract and return text content inline (default: true) Parameters:
- accountId: Account ID
- folder: Folder name (default: INBOX)
- uids: Array of email UIDs to delete
- chunkSize: Emails to delete per batch (default: 50) Parameters:
- accountId: Account ID
- folder: Folder name (default: INBOX)
- from, to, subject: Search criteria (optional)
- before, since: Date filters (optional)
- chunkSize: Emails to delete per batch (default: 50)
- dryRun: Preview what would be deleted without deleting (default: false)At least one concrete criterion (from, to, subject, before, or since) is required — a call with no criteria is refused, so it can never match and delete an entire folder. On servers whose SEARCH is broken (see Troubleshooting → Search returns nothing) this tool, imap_delete_spam and imap_delete_by_domain return an error instead of deleting from a client-side match.
Parameters:
- accountId: Account ID to send from
- from: Sender identity (optional). Must match the account email/login or an
address configured in `allowedFrom`
- to: Recipient email address(es) — an array, or a single comma-separated string
- subject: Email subject
- text: Plain text content (optional)
- html: HTML content (optional)
- cc: CC recipients (optional)
- bcc: BCC recipients (optional)
- replyTo: Reply-to address (optional)
- attachments: Array of attachments (optional)
- filename: Attachment filename
- content: Base64 encoded content; provide exactly one of `content` or `path`
- path: Readable local file path to attach; provide exactly one of `path` or `content`
- contentType: MIME type (optional; detected from the filename extension when omitted)
- contentDisposition: "attachment" (default) or "inline" — use "inline" for images shown in the HTML body via cid:
- cid: Content-ID for inline attachments; must match the `cid:` value used in an `<img src="cid:...">` tag in `html`
- dryRun: Validate attachments and compose MIME without sending or saving to Sent (optional, default: false)Attachments are validated before SMTP is contacted. Invalid base64, unreadable paths, missing filenames, ambiguous sources, and inline attachments without cid fail fast. Successful sends and dry-runs return attachmentCount and safe attachmentDiagnostics: filename, MIME type, size, source, disposition, and cid. Diagnostics omit bytes, raw MIME, and local file paths.
For large files, upload with imap_upload_file first and pass its returned local path; for inline images, set contentDisposition: "inline" and a matching cid.
After sending, a copy is saved to the account's Sent folder (unless saveToSent is disabled on the account). The folder is resolved via the account's sentFolder override → the server's \Sent SPECIAL-USE flag → a list of known localized names ("Sent", "Gesendet", "Éléments envoyés", …). The response reports the outcome: savedToSent (boolean), sentFolder (the folder used), and — when the save fails — sentSaveError explaining why, instead of failing silently. The same applies to imap_reply_to_email and imap_forward_email.
When the account has defaultBcc configured, those address(es) are always BCC'd on send, reply, forward, and draft (merged with any per-call bcc; duplicates removed case-insensitively). The Bcc header is kept in the MIME stored for drafts and Sent-folder copies so mail clients show it.
imap_send_email, plus inReplyTo, references, and an optional folder override for the Drafts folder. Parameters:
- accountId: Account ID
- folder: Folder containing the original email
- uid: UID of the email to reply to
- text: Plain text reply content (optional)
- html: HTML reply content (optional)
- replyAll: Reply to all recipients (default: false)
- bcc: BCC recipients (optional; merged with account defaultBcc)
- attachments: Array of attachments (optional, same shape as imap_send_email, including contentDisposition/cid for inline images) Parameters:
- accountId: Account ID
- folder: Folder containing the original email
- uid: UID of the email to forward
- to: Forward to email address(es)
- text: Additional text to include (optional)
- bcc: BCC recipients (optional; merged with account defaultBcc)
- includeAttachments: Include original attachments (default: true) Parameters:
- accountId: Account IDEach folder includes its attributes (raw IMAP LIST flags) and, when the server advertises it, specialUse — the RFC 6154 role (\Sent, \Drafts, \Trash, \Junk, \Archive) that identifies a folder independent of its localized display name (e.g. "Gesendet" carries specialUse: "\Sent").
Parameters:
- accountId: Account ID
- folder: Folder name
Returns:
- messages: { total, new, unseen } — from IMAP STATUS
- uidvalidity, uidnext
- flags, permanentFlags: string arrays
- customKeywords: the mailbox's non-system keywords, usable as the
`keywords` / `unKeywords` input of imap_search_emails Parameters:
- accountId: Account ID
- folder: Full folder path to create (e.g. "Archives/2026/2026-05" or "INBOX.Archive") Parameters:
- accountId: Account ID
- folders: Specific folders (optional)~/.imap-mcp/.key~/.imap-mcp/accounts.json.key, and accounts.json are written owner-only(0700/0600) so other local users cannot read the key or the credentials
filenames cannot write outside it
npm run devnpm run buildsrc/
├── index.ts # MCP server entry point
├── services/
│ ├── imap-service.ts # IMAP connection management
│ ├── smtp-service.ts # SMTP service for sending emails
│ └── account-manager.ts # Account configuration
├── tools/
│ ├── index.ts # Tool registration
│ ├── account-tools.ts # Account management tools
│ ├── email-tools.ts # Email operation tools (including send/reply/forward)
│ └── folder-tools.ts # Folder operation tools
└── types/
└── index.ts # TypeScript type definitions"Add my Gmail account with username [email protected]"
"Show me the latest 5 emails from my Gmail account"
"Search for emails from [email protected] in the last week"
"Send an email to [email protected] with subject 'Project Update'"
"Reply to the latest email from my boss"
"Forward the email with subject 'Meeting Notes' to [email protected]"
"Move the invoice email from INBOX to my Taxes folder"
"List all folders in my email account and show unread counts"
["[email protected]","[email protected]"]to, cc, bcc, references and uid accept either a single value or an array. In JSON Schema that is an anyOf, and some MCP clients drop the anyOf before showing the schema to the model — the field then looks untyped or string-typed, and the client serializes the model's array into a string. The server used to pass that string straight to nodemailer, which folded the literal [ and ] into the first and last address, so every recipient was rejected by the receiving mail server (issue #127).
The server now detects a stringified array and restores it, both when validating tool input and again before composing the message, and logs a warning to stderr naming the field. Nothing needs to change on your side. If you want to bypass the client behavior entirely, pass recipients as one comma-separated string: "Alice <[email protected]>, Bob <[email protected]>".
Since mid-2026 Strato's IMAP server (imap.strato.com) answers every SEARCH command with an empty result, while FETCH still works (issue #138). The server detects this: when a SEARCH comes back empty for a folder that is not empty and SEARCH ALL is empty as well, it fetches the envelopes and applies the criteria itself. imap_search_emails, imap_find_thread_messages, the unread counts and the spam analysis keep working; imap_get_latest_emails never needed SEARCH.
Limits of the fallback:
body search downloads and parses each remaining candidate, so it isrefused above 2000 candidates; narrow it with since/from/subject.
imap_bulk_delete_by_search, imap_delete_spam,imap_delete_by_domain) do not use it and return an error instead. Find the messages with imap_search_emails and delete their UIDs with imap_bulk_delete.
The server automatically configures SMTP settings based on your IMAP provider. If you need custom SMTP settings, you can specify them when adding an account:
{
"smtp": {
"host": "smtp.example.com",
"port": 587,
"secure": false
}
}MIT
Contributions are welcome! Please feel free to submit a Pull Request.
~30 seconds. Free. No account. Every finding cites a rule and a line of evidence.