Skip to content
Back to search

apple-mail-mcp

MarketplaceWorks with Claude CodeGitHub

Apple Mail integration for Claude Code and Codex via MCP

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/sweetrb/apple-mail-mcp with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/sweetrb/apple-mail-mcp'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/sweetrb--apple-mail-mcp/badge.svg)](/listings/sweetrb--apple-mail-mcp)

HTML

<a href="/listings/sweetrb--apple-mail-mcp"><img src="/api/listings/sweetrb--apple-mail-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Using Claude Code (Easiest)

If you're using [Claude Code](https://claude.com/product/claude-code) (in Terminal or VS Code), just ask Claude to install it:

Install the sweetrb/apple-mail-mcp MCP server so you can help me manage my Apple Mail

Claude will handle the installation and configuration automatically.

Or register it deterministically in one command:

claude mcp add apple-mail -s user -- npx -y apple-mail-mcp

Using the Plugin Marketplace

Install as a Claude Code plugin for automatic configuration and enhanced AI behavior:

/plugin marketplace add sweetrb/apple-mail-mcp
/plugin install apple-mail

This method also installs a **skill** that teaches Claude when and how to use Apple Mail effectively.

> **Configuring IMAP/SMTP for a plugin install:** a plugin install has no editable `env` block, > so supply settings via the config file at `~/Library/Application Support/apple-mail-mcp/config.json` > — Method B in the [IMAP / SMTP Setup Guide](https://github.com/sweetrb/apple-mail-mcp/blob/main/docs/IMAP-SETUP.md). > Passwords stay in the macOS Keychain; run the `doctor` tool to verify.

Using the Codex Marketplace

See [Apple Mail in Codex](docs/CODEX-SETUP.md) for setup and diagnostics, and the [guided setup and OAuth proposal](docs/CODEX-PLUGIN-AUTH-PROPOSAL.md) for proposed future authorization support.

Install the same public marketplace in Codex:

codex plugin marketplace add sweetrb/apple-mail-mcp
codex plugin add apple-mail@apple-mail-mcp

The Codex package includes a portable `codex/plugin.json`, typed stdio server configuration in `codex/mcp.json`, the Apple Mail skill, and the existing assets. It retains `codex/.codex-plugin/plugin.json` and `codex/.mcp.json` for compatible older hosts. Both layouts register the same `apple-mail` MCP identity through `npx -y apple-mail-mcp@<plugin version>`. Release synchronization updates both runtime pins and manifest metadata; tests and CI reject drift. An unreleased candidate can be discovered locally, but its exact npm version must be published before that pinned launcher can be installed from the registry.

For ongoing upstream updates, keep the Git marketplace configured. After a new release is published, refresh its catalog:

codex plugin marketplace upgrade apple-mail-mcp

Install the published plugin version from the refreshed marketplace, then start a new Codex session. The refresh does not replace the runtime pin with `@latest`; the plugin and its pinned npm runtime must refer to the same available release.

The standalone plugin archive bundles the server and requires only Node.js 20+ on the Mac; it does not fetch a runtime from npm. Download it from the release assets, or use the candidate artifact attached to a successful CI run. See [Standalone plugin archive](docs/CODEX-SETUP.md#standalone-plugin-archive) for the distribution format and local build command.

An imported archive or separately uploaded private account plugin is a snapshot, not a subscription to this repository's releases. Updating that copy requires a replacement package. When switching to the maintained marketplace distribution, preserve settings and approvals, verify Mail access and reply behavior, then remove the redundant installation. See [Updates and migration](docs/CODEX-SETUP.md#updates-and-migration).

For a personal build, you may explicitly supply a local PNG: `node scripts/package-codex-plugin.mjs /path/apple-mail.tar.gz --icon /path/icon.png`. The optional image must be square, noninterlaced, 48–2,048 pixels per side, and at most 4 MiB. It is bundled inside the skill's assets directory and used for the generated portable and compatibility manifests' light/dark logo and composer icons. Source manifests, the runtime, and default artwork remain unchanged; omitting `--icon` preserves the standard archive. No image is fetched automatically. Supply only artwork you have permission to use and distribute; this option does

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 36 lines
  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "apple-mail-mcp",
  4. "version": "2.20.62",
  5. "description": "Apple Mail integration for Claude Code and Codex via MCP",
  6. "owner": {
  7. "name": "Rob Sweet",
  8. "email": "rob@superiortech.io"
  9. },
  10. "plugins": [
  11. {
  12. "name": "apple-mail",
  13. "displayName": "Apple Mail",
  14. "description": "Manage Apple Mail through natural language - read, search, send, and organize emails (macOS only)",
  15. "version": "2.20.62",
  16. "author": {
  17. "name": "Rob Sweet",
  18. "email": "rob@superiortech.io"
  19. },
  20. "homepage": "https://github.com/sweetrb/apple-mail-mcp#readme",
  21. "repository": "https://github.com/sweetrb/apple-mail-mcp",
  22. "license": "MIT",
  23. "keywords": [
  24. "mcp",
  25. "apple-mail",
  26. "mail",
  27. "email",
  28. "claude",
  29. "codex",
  30. "macos"
  31. ],
  32. "source": "./",
  33. "category": "productivity"
  34. }
  35. ]
  36. }
README.md · README · 2,609 lines
  1. # Apple Mail MCP Server
  2. A [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server that enables AI assistants like Claude to read, send, search, and manage emails in Apple Mail on macOS.
  3. [![npm version](https://img.shields.io/npm/v/apple-mail-mcp)](https://www.npmjs.com/package/apple-mail-mcp)
  4. [![npm downloads](https://img.shields.io/npm/dm/apple-mail-mcp)](https://www.npmjs.com/package/apple-mail-mcp)
  5. [![node](https://img.shields.io/node/v/apple-mail-mcp)](https://www.npmjs.com/package/apple-mail-mcp)
  6. [![CI](https://github.com/sweetrb/apple-mail-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/sweetrb/apple-mail-mcp/actions/workflows/ci.yml)
  7. [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/sweetrb/apple-mail-mcp/badge)](https://scorecard.dev/viewer/?uri=github.com/sweetrb/apple-mail-mcp)
  8. [![platform: macOS](https://img.shields.io/badge/platform-macOS-111?logo=apple&logoColor=white)](https://www.apple.com/macos/)
  9. [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  10. [![MCP](https://img.shields.io/badge/MCP-server-blue)](https://modelcontextprotocol.io)
  11. <p align="center">
  12. <img src="https://raw.githubusercontent.com/sweetrb/apple-mail-mcp/main/codex/assets/screenshot.png" alt="Apple Mail MCP — read, search, send, and organize Apple Mail from Codex, Claude, and other AI assistants" width="680">
  13. </p>
  14. > **Note:** This is the **npm/Node.js** package — install with `npx` or `npm`. There is an unrelated Python project of the same name on PyPI ([`imdinu/apple-mail-mcp`](https://github.com/imdinu/apple-mail-mcp)) installed via `pipx`/`uvx`. If you're using `uvx` and seeing a `cyclopts` dependency error, you're looking for that project, not this one.
  15. ## What is This?
  16. This server acts as a bridge between AI assistants and Apple Mail. Once configured, you can ask Claude (or any MCP-compatible AI) to:
  17. - "Check my inbox for unread messages"
  18. - "Find emails from john@example.com"
  19. - "Send an email to the team about the meeting"
  20. - "Create a draft email for me to review"
  21. - "Reply to that message"
  22. - "Forward this to my colleague"
  23. - "Move old newsletters to the Archive folder"
  24. The AI assistant communicates with this server, which then uses AppleScript to interact with the Mail app on your Mac. All data stays local on your machine.
  25. ## Quick Start
  26. ### Using Claude Code (Easiest)
  27. If you're using [Claude Code](https://claude.com/product/claude-code) (in Terminal or VS Code), just ask Claude to install it:
  28. ```
  29. Install the sweetrb/apple-mail-mcp MCP server so you can help me manage my Apple Mail
  30. ```
  31. Claude will handle the installation and configuration automatically.
  32. Or register it deterministically in one command:
  33. ```bash
  34. claude mcp add apple-mail -s user -- npx -y apple-mail-mcp
  35. ```
  36. ### Using the Plugin Marketplace
  37. Install as a Claude Code plugin for automatic configuration and enhanced AI behavior:
  38. ```bash
  39. /plugin marketplace add sweetrb/apple-mail-mcp
  40. /plugin install apple-mail
  41. ```
  42. This method also installs a **skill** that teaches Claude when and how to use Apple Mail effectively.
  43. > **Configuring IMAP/SMTP for a plugin install:** a plugin install has no editable `env` block,
  44. > so supply settings via the config file at `~/Library/Application Support/apple-mail-mcp/config.json`
  45. > — Method B in the [IMAP / SMTP Setup Guide](https://github.com/sweetrb/apple-mail-mcp/blob/main/docs/IMAP-SETUP.md).
  46. > Passwords stay in the macOS Keychain; run the `doctor` tool to verify.
  47. ### Using the Codex Marketplace
  48. See [Apple Mail in Codex](docs/CODEX-SETUP.md) for setup and diagnostics, and the
  49. [guided setup and OAuth proposal](docs/CODEX-PLUGIN-AUTH-PROPOSAL.md) for proposed
  50. future authorization support.
  51. Install the same public marketplace in Codex:
  52. ```bash
  53. codex plugin marketplace add sweetrb/apple-mail-mcp
  54. codex plugin add apple-mail@apple-mail-mcp
  55. ```
  56. The Codex package includes a portable `codex/plugin.json`, typed stdio server
  57. configuration in `codex/mcp.json`, the Apple Mail skill, and the existing assets.
  58. It retains `codex/.codex-plugin/plugin.json` and `codex/.mcp.json` for compatible
  59. older hosts. Both layouts register the same `apple-mail` MCP identity through
  60. `npx -y apple-mail-mcp@<plugin version>`. Release synchronization updates both
  61. runtime pins and manifest metadata; tests and CI reject drift. An unreleased
  62. candidate can be discovered locally, but its exact npm version must be
  63. published before that pinned launcher can be installed from the registry.
  64. For ongoing upstream updates, keep the Git marketplace configured. After a new
  65. release is published, refresh its catalog:
  66. ```bash
  67. codex plugin marketplace upgrade apple-mail-mcp
  68. ```
  69. Install the published plugin version from the refreshed marketplace, then start
  70. a new Codex session. The refresh does not replace the runtime pin with `@latest`;
  71. the plugin and its pinned npm runtime must refer to the same available release.
  72. The standalone plugin archive bundles the server and requires only Node.js 20+
  73. on the Mac; it does not fetch a runtime from npm. Download it from the release
  74. assets, or use the candidate artifact attached to a successful CI run. See
  75. [Standalone plugin archive](docs/CODEX-SETUP.md#standalone-plugin-archive) for the
  76. distribution format and local build command.
  77. An imported archive or separately uploaded private account plugin is a snapshot,
  78. not a subscription to this repository's releases. Updating that copy requires a
  79. replacement package. When switching to the maintained marketplace distribution,
  80. preserve settings and approvals, verify Mail access and reply behavior, then
  81. remove the redundant installation. See [Updates and migration](docs/CODEX-SETUP.md#updates-and-migration).
  82. For a personal build, you may explicitly supply a local PNG:
  83. `node scripts/package-codex-plugin.mjs /path/apple-mail.tar.gz --icon /path/icon.png`.
  84. The optional image must be square, noninterlaced, 48–2,048 pixels per side, and
  85. at most 4 MiB. It is bundled inside the skill's assets directory and used for
  86. the generated portable and compatibility manifests' light/dark logo and composer
  87. icons. Source manifests, the runtime, and default artwork remain unchanged;
  88. omitting `--icon` preserves the standard archive. No image is fetched automatically.
  89. Supply only artwork you have permission to use and distribute; this option does
  90. not grant rights to Apple or other third-party artwork, or guarantee that a host
  91. will refresh an existing listing's cached presentation.
  92. The compose tools accept `composition: "native-editor"` to insert new prose
  93. through Mail's visible editor, leaving its signature and reply history intact.
  94. This opt-in path uses existing macOS Accessibility and Automation permissions;
  95. it does not require a separate computer-control plugin. It verifies the composer
  96. and sender, preserves the clipboard, and stops without sending if insertion
  97. cannot be verified. See [native composition](docs/NATIVE-COMPOSITION.md) for
  98. setup, examples, and verification limits. Existing SMTP and AppleScript behavior
  99. is unchanged when the option is omitted.
  100. ### Other Hosts (Hermes, Antigravity)
  101. Two more hosts can run the same `apple-mail` MCP server (`npx -y apple-mail-mcp`):
  102. - **[Hermes Agent](https://hermes-agent.nousresearch.com/)** (NousResearch) — Hermes has no plugin/marketplace drop-in, so there is nothing in this repo to install from. Register the server with the CLI:
  103. ```bash
  104. hermes mcp add apple-mail --command npx --args -y apple-mail-mcp
  105. ```
  106. Or add it to `~/.hermes/config.yaml` by hand:
  107. ```yaml
  108. mcp_servers:
  109. apple-mail:
  110. command: npx
  111. args: ["-y", "apple-mail-mcp"]
  112. ```
  113. Restart your Hermes session afterward so the tools load.
  114. - **[Antigravity](https://antigravity.google/)** (Google) — add the server entry from [`.antigravity-plugin/mcp_config.json`](https://github.com/sweetrb/apple-mail-mcp/blob/main/.antigravity-plugin/mcp_config.json) to `~/.gemini/config/mcp_config.json` (or via Antigravity's MCP settings).
  115. ### Manual Installation
  116. **1. Install the server:**
  117. ```bash
  118. npm install -g apple-mail-mcp
  119. ```
  120. **2. Add to Claude Desktop** (`~/Library/Application Support/Claude/claude_desktop_config.json`):
  121. ```json
  122. {
  123. "mcpServers": {
  124. "apple-mail": {
  125. "command": "npx",
  126. "args": ["apple-mail-mcp"]
  127. }
  128. }
  129. }
  130. ```
  131. **3. Restart Claude Desktop** and start using natural language:
  132. ```
  133. "Show me my unread emails"
  134. ```
  135. On first use, macOS will ask for permission to automate Mail.app. Click "OK" to allow.
  136. ## Configuring email (IMAP & SMTP)
  137. The server works out of the box over AppleScript with **no configuration**. Two
  138. **opt-in** power features take a one-time setup:
  139. - **Fast IMAP reads** — server-side search, counts, and large-mailbox handling
  140. that AppleScript is too slow for (it times out on big Gmail mailboxes).
  141. - **Clean SMTP sending** — `send-email` submits clean MIME directly, avoiding the
  142. macOS 15+ Mail.app `<blockquote>` wrapping that otherwise makes sent mail look
  143. quoted/indented like a reply.
  144. Both are driven by non-secret `APPLE_MAIL_MCP_*` settings — supplied via an `env`
  145. block **or** a `config.json` file (for hosts like Claude Desktop that strip `env`)
  146. — with passwords kept in the macOS **Keychain**, never in config.
  147. 👉 **[IMAP / SMTP Setup Guide](https://github.com/sweetrb/apple-mail-mcp/blob/main/docs/IMAP-SETUP.md)** — step-by-step: app passwords,
  148. Keychain, both config methods, multi-account, SMTP, verification with the `doctor`
  149. tool, and troubleshooting. Verify any time by running the **`doctor`** tool.
  150. ## Requirements
  151. - **macOS** - Apple Mail and AppleScript are macOS-only
  152. - **Node.js 20+** - Required for the MCP server
  153. - **Node.js 22.5+ and Full Disk Access** - Required by `search-contacts` only. It reads the Contacts database directly through Node's built-in `node:sqlite`, which does not exist before 22.5. On an older runtime, or without Full Disk Access for the Node binary, it logs one line to stderr and returns **an empty list rather than an error** — so "no contacts found" can mean "cannot read Contacts". Every other tool works on Node 20+. See [Node runtime & TCC permissions](https://github.com/sweetrb/apple-mail-mcp/blob/main/docs/NODE-RUNTIME-AND-TCC-PERMISSIONS.md).
  154. - **Apple Mail** - Must have at least one account configured (iCloud, Gmail, Exchange, etc.)
  155. ## Features
  156. ### Messages
  157. | Feature | Description |
  158. | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
  159. | **List Messages** | List messages with pagination, sender filter, date display |
  160. | **Search Messages** | Search by sender, subject, content, date range, read/flagged status — across all accounts |
  161. | **Read Messages** | Get full email content (plain text or HTML) |
  162. | **Read Headers** | Get a message's raw RFC 5322 headers — the author's `Date:`, Message-ID, threading ids, `Received:` trace — without downloading the body |
  163. | **Send Email** | Compose and send new emails (attach by file path or inline base64 content; optional `inReplyTo`/`references` threading over SMTP) |
  164. | **Send Serial Email** | Mail merge — send personalized emails to a list of recipients with {{placeholder}} support |
  165. | **Create Draft** | Save emails to Drafts folder (attach by file path or inline base64 content; threaded drafts filed over IMAP) |
  166. | **Update Saved Draft** | Preview and partially edit a stored IMAP draft, retaining unchanged MIME and returning the new UID and revision |
  167. | **Reply** | Reply to messages (with reply-all support and attachments) |
  168. | **Forward** | Forward messages to new recipients (with extra attachments) |
  169. | **Get Thread** | Group a conversation by normalized subject (across AppleScript or IMAP) |
  170. | **Mark Read/Unread** | Change read status (single or batch) |
  171. | **Flag/Unflag** | Flag or unflag messages (single or batch) |
  172. | **Delete Messages** | Move messages to trash (single or batch) |
  173. | **Move Messages** | Organize into mailboxes (single or batch) |
  174. | **List Attachments** | View attachment metadata (name, type, size) |
  175. | **Save Attachment** | Save attachments to disk |
  176. | **Fetch Attachment** | Get an attachment's bytes as base64 (no disk write) |
  177. Read/list/get tools also return **structured JSON** (`structuredContent`) alongside the text, so agents can consume results without parsing prose.
  178. ### Mailbox & Account Management
  179. | Feature | Description |
  180. | -------------------------------- | ------------------------------------------- |
  181. | **List Mailboxes** | Show all folders with message/unread counts |
  182. | **Create/Delete/Rename Mailbox** | Full mailbox lifecycle management |
  183. | **List Accounts** | Show configured accounts |
  184. | **Unread Count** | Get unread counts per mailbox |
  185. ### Rules, Contacts & Templates
  186. | Feature | Description |
  187. | ------------------------ | ---------------------------------------------------------------------------------------- |
  188. | **List Rules** | View all mail rules and their enabled status |
  189. | **Enable/Disable Rules** | Toggle mail rules on or off |
  190. | **Create/Delete Rules** | Create rules with conditions + actions, or delete by name |
  191. | **Search Contacts** | Look up contacts from Contacts.app by name |
  192. | **Email Templates** | Save, list, use, and delete reusable email templates (persisted to disk across restarts) |
  193. ### Diagnostics
  194. | Feature | Description |
  195. | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  196. | **Health Check** | Verify Mail.app connectivity |
  197. | **Doctor** | Diagnose Mail permission, account state, and each IMAP/SMTP backend with actionable messages |
  198. | **Statistics** | Message and unread counts per account, recently received stats |
  199. | **Sync Status** | Check if Mail.app is actively syncing |
  200. | **Effect reconciliation** | Every delete/move reports what it actually did to the mailbox (`countDelta`), and warns when more messages left than were operated on — see [Auditing destructive operations](#auditing-destructive-operations) |
  201. ### MCP resources & prompts
  202. Resources expose read-only context the client can attach without a tool call:
  203. `mail://accounts`, `mail://templates`, and `mail://mailboxes/{account}`. Prompts
  204. package common workflows: `triage-inbox`, `compose-reply`, `weekly-summary`.
  205. ---
  206. ## Tool Reference
  207. This section documents all available tools. AI agents should use these tool names and parameters exactly as specified.
  208. ### Message Operations
  209. #### `search-messages`
  210. Search for messages matching criteria. Searches all accounts by default.
  211. | Parameter | Type | Required | Description |
  212. | ----------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  213. | `query` | string | No | Text to search in subject/sender |
  214. | `body` | string | No | Text to search in the message body. IMAP backend only (server-side `BODY` search); AppleScript-only accounts are reported as not searched |
  215. | `from` | string | No | Filter by sender email address |
  216. | `subject` | string | No | Filter by subject line |
  217. | `mailbox` | string | No | Mailbox to search in (omit to search all mailboxes) |
  218. | `account` | string | No | Account to search in (omit to search all accounts) |
  219. | `isRead` | boolean | No | Filter by read status |
  220. | `isFlagged` | boolean | No | Filter by flagged status |
  221. | `flagColor` | string | No | Filter to messages flagged with exactly this color — see [`flag-message`](#flag-message--unflag-message) for the palette. Implies `isFlagged: true`; pairing this with `isFlagged: false` is rejected. See the flag-color note below. |
  222. | `dateFrom` | string | No | Start date filter (e.g., "January 1, 2026") |
  223. | `dateTo` | string | No | End date filter (e.g., "March 1, 2026") |
  224. | `limit` | number | No | Max results, 1–500 (default: 50) |
  225. | `offset` | number | No | Newest matches to skip, ≥ 0 (for pagination). IMAP accounts only; without a `mailbox`, `offset` + `limit` may not exceed 5,000 |
  226. **Returns:** List of matching messages with ID, date, subject, sender, read state,
  227. mailbox and account, and `flagColor` when flagged with an explicit color. When
  228. the results can come from more than one mailbox or account, each text line ends
  229. with where that message is, e.g. `| in "Deleted Items" (Exchange)`: a sent
  230. message and the earlier drafts of it that Exchange keeps in Deleted Items share
  231. a subject, and the ids alone don't tell them apart. A search of one mailbox of
  232. one account leaves the lines as they were.
  233. **Flag color as a label (#286).** Every row from both backends carries
  234. `flagColor` (the palette name — `red`, `orange`, `yellow`, `green`, `blue`,
  235. `purple`, `gray`) whenever the message is flagged with an explicit color;
  236. omitted for an unflagged message or one flagged with Mail's plain default (no
  237. color chosen). Combined with the `flagColor` filter above, a colored flag
  238. works as a label across mailboxes: flag a set of messages with
  239. `flag-message`/`batch-flag-messages`, then find exactly that set later with
  240. `search-messages`, without moving anything into a dedicated folder. **Known
  241. limitation, inherent to Apple's `$MailFlagBit0/1/2` IMAP wire encoding, not
  242. specific to this server:** `red` (palette index 0) sets no keyword bits, so
  243. over IMAP it is indistinguishable from a plain colorless flag, both when
  244. reading `flagColor` back and when filtering on it. AppleScript-backed
  245. accounts are unaffected (Mail's own `flag index` property is `0` for red, `-1`
  246. for none).
  247. ⚠️ **Row dates.** Since 2.19.7 every row — on both the IMAP and AppleScript
  248. backends — carries both `dateSent` (the message's `Date:` header) and
  249. `dateReceived` (mailbox arrival — IMAP `INTERNALDATE` or Mail's `date received`).
  250. They differ legitimately by transit time; when they differ by **years**, the
  251. mailbox was migrated or re-imported and the arrival timestamp was reset — trust
  252. `dateSent` for chronology ([#224](https://github.com/sweetrb/apple-mail-mcp/issues/224)).
  253. `dateSent` is omitted (not invented) when the message carries no parseable
  254. `Date:` header, or when it is more than 7 days later than `dateReceived` — Mail
  255. substitutes a timestamp of its own for a `Date:` header it cannot parse
  256. ([#234](https://github.com/sweetrb/apple-mail-mcp/issues/234)).
  257. **Large mailboxes & partial results.** Apple Mail's AppleScript bridge cannot
  258. search very large IMAP/Gmail mailboxes (tens of thousands of messages) before
  259. the Apple Event times out — empirically even reading the newest 20 messages of
  260. a 44k-message mailbox takes ~45s. To avoid burning minutes only to return a
  261. misleading empty result, an unscoped (all-mailboxes) search **skips** mailboxes
  262. whose message count exceeds a threshold (default **5000**), enforces a
  263. per-account time budget, and **reports** anything it skipped or that timed out
  264. rather than silently returning nothing. When coverage is incomplete the result
  265. includes an explicit warning, e.g.:
  266. ```
  267. ⚠️ Partial results — this is NOT a confirmed "no such mail":
  268. - skipped mailbox(es) too large to search via AppleScript: Gmail / All Mail (44287) — scope the search with `mailbox` + a `dateFrom`/`dateTo` window to target them
  269. ```
  270. To search inside a large mailbox, scope the call with `mailbox` (and ideally a
  271. `dateFrom`/`dateTo` window). Tune or disable the skip threshold with the
  272. `APPLE_MAIL_MAX_SEARCH_MAILBOX` environment variable (default `5000`; set to `0`
  273. to disable the guard and attempt every mailbox regardless of size).
  274. ([#24](https://github.com/sweetrb/apple-mail-mcp/issues/24))
  275. **Envelope Index search (opt-in, read-only).** For accounts with no IMAP config,
  276. set `APPLE_MAIL_MCP_ENVELOPE_INDEX=1` to answer header searches (`query`, `from`,
  277. `subject`, read/flagged state, dates, mailbox) from Mail's own on-disk Envelope Index
  278. instead of an AppleScript scan, so large mailboxes are searched completely rather than
  279. skipped. It needs Full Disk Access for the server's Node runtime and opens the database
  280. read-only. Text filters ignore case the way Mail does, accented and non-Latin letters
  281. included (`über` finds `Über`). Anything the index can't answer completely (a
  282. `flagColor` filter, an unknown mailbox, no Full Disk Access, an unrecognised schema, a
  283. corrupt or locked database, or Mail not running — opening the index then would create
  284. files in the mail store) falls back to the AppleScript scan. (Mail not running is judged
  285. by its `-wal`/`-shm` files being gone; after a Mail crash leaves them behind, a search can
  286. still update `-shm`, which SQLite rebuilds when Mail next opens the index.) The `backend`
  287. field below reports which one answered.
  288. ([#342](https://github.com/sweetrb/apple-mail-mcp/issues/342))
  289. **Body search for AppleScript-only accounts (opt-in local body index).** Without IMAP,
  290. `search-messages` can't search message bodies (AppleScript would have to pull every
  291. body through Mail), so a `body` query reports those accounts as not searched. Set
  292. `APPLE_MAIL_MCP_BODY_INDEX=1` **together with** `APPLE_MAIL_MCP_ENVELOPE_INDEX=1` to
  293. search them through a local full-text index of the `.emlx` files Mail already keeps
  294. on disk. ([#349](https://github.com/sweetrb/apple-mail-mcp/issues/349))
  295. - **What it reads, and what it needs.** Message files under `~/Library/Mail`, read
  296. only; the mail store is never written. Like the Envelope Index backend, it needs
  297. **Full Disk Access** for the app that runs the server (its Node runtime). `doctor`
  298. reports when it can't read the store, with the same wording.
  299. - **Where the index lives.** `~/Library/Application Support/apple-mail-mcp/body-index.db`
  300. (plus `-wal`, `-shm` and `.writer-lock` next to it); set
  301. `APPLE_MAIL_MCP_BODY_INDEX_FILE` to move it. The directory is created `0700` and the
  302. files `0600`. The index is _contentless_: it stores the search tokens, not a copy of
  303. any message, but the tokens still reveal a lot about your mail — treat the file as
  304. sensitive. Expect roughly 70 MB per 22,000 messages.
  305. - **Deleting it.** Turn the flag off (or stop the server), then delete the files:
  306. ```bash
  307. rm -f ~/Library/Application\ Support/apple-mail-mcp/body-index.db*
  308. ```
  309. It is only a cache; with the flag on it is rebuilt from scratch on the next start.
  310. - **First build and upkeep.** One server instance (the first to start) builds and
  311. updates the index in the background in small slices; other instances — one per
  312. conversation in some hosts — search it read-only and take over if that instance
  313. exits. The walking and parsing run in a short-lived child process (the same
  314. `build/index.js` on the same Node runtime, so the same Full Disk Access grant
  315. applies), which exits as soon as it has caught up: the server stays responsive during
  316. a build, and the memory parsing takes goes back to the system instead of staying with
  317. the server. If that process can't start or can't read the store, the server builds
  318. on its own main thread instead and `doctor` says why (and tries a build process again
  319. an hour later). A build process that stops responding for a minute is stopped and
  320. restarted. (A host that runs the server on Electron's Node gets the main-thread build:
  321. a forked process there would start the app.) A message file that can't be read or
  322. parsed is skipped, counted, and tried
  323. again on the next full check; it never holds up the rest. New mail is picked up through
  324. file-system events within seconds, with a full check every 10 minutes as a safety
  325. net. A build of ~22,000 messages took about 40 s on an Apple-silicon Mac.
  326. - **What it matches.** Words and word beginnings, ignoring case and accents: `invoice`
  327. finds `invoices` and `Invoice`, but not `reinvoice`, as the index stores words, not
  328. text. Text with no letters or digits (`@`), and Chinese, Japanese or Thai text (written
  329. without spaces between words), can't be matched that way, so a body search for it
  330. reports the account as not searched rather than as no match.
  331. - **Coverage is always reported.** A body search never presents an incomplete index as
  332. "no matches". Messages in the searched scope that it couldn't read in full are
  333. counted, and the result is `partial: true` with a `notSearchedMailboxes` entry such as
  334. `Google / * (1,234 messages not downloaded, 12 not indexed yet)`. _Not downloaded_
  335. means Mail has only the headers (common for older mail on IMAP/Exchange accounts set
  336. to download recent messages only); open those messages in Mail, or change the
  337. account's download setting, to make them searchable. Messages over 25 MB are not read.
  338. Until the first build has walked the whole store, messages it hasn't reached yet are
  339. counted as _not indexed yet_.
  340. - **Requirements.** Node 22.5 or later (for `node:sqlite`); on older runtimes the
  341. feature turns itself off and says why in the logs and `doctor`.
  342. **Coverage diagnostics (structured fields).** The warning above is prose for a
  343. human reader; the same information is also returned as structured fields on
  344. `search-messages` and `list-messages`, so a caller can tell _"nothing matched"_
  345. apart from _"I did not look everywhere"_ without parsing the text:
  346. | Field | Type | Meaning |
  347. | ----------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  348. | `partial` | boolean | Coverage was incomplete — **the result is not a confirmed "no such mail"**. True whenever any field below is non-empty. |
  349. | `skippedLargeMailboxes` | string[] | Mailboxes never scanned because their message count exceeded `APPLE_MAIL_MAX_SEARCH_MAILBOX`, formatted `"Account / Mailbox (count)"` — e.g. `"iCloud / Archive (90694)"`. |
  350. | `notSearchedMailboxes` | string[] | Mailboxes that _were_ reached but timed out or errored mid-scan, formatted `"Account / Mailbox"`. Also carries the IMAP path's `failedMailboxes`. |
  351. | `timedOutAccounts` | string[] | Accounts whose whole-account AppleScript was killed by the per-account time budget — nothing from that account was searched. |
  352. | `failedMailboxes` | string[] | IMAP-backend mailboxes that errored. These are merged into `notSearchedMailboxes` as well; read that field unless you need to attribute the failure to the IMAP path specifically. |
  353. | `failedMailboxReasons` | object | The IMAP server's own error text for each entry in `failedMailboxes`, keyed the same way. |
  354. | `omittedMessages` | object[] | IMAP messages that belong on the page but whose `FETCH` response could not be read even with a reduced item set — `{ id, mailbox, uid, reason }`. The page is short by exactly these; the `id` still works with `get-message` / `get-message-headers`. ([#256](https://github.com/sweetrb/apple-mail-mcp/issues/256)) |
  355. | `timedOutMailboxes` | string[] | IMAP mailboxes the search did not finish because the call was **cancelled** (`notifications/cancelled`) or reached its **deadline** (`APPLE_MAIL_MCP_SEARCH_DEADLINE_MS`, default 45s), formatted `"Account / Mailbox"`; an account never reached is `"Account / *"`. Results from the mailboxes that did finish are still returned. ([#276](https://github.com/sweetrb/apple-mail-mcp/issues/276)) |
  356. | `stoppedBy` | string | `"deadline"` or `"cancelled"` — present only with `timedOutMailboxes`. |
  357. | `backend` | string | `search-messages` only: which backend answered the non-IMAP accounts — `"envelope-index"`, `"applescript"`, or `"mixed"` (see `backendByAccount`). Also shown on the summary line while `APPLE_MAIL_MCP_ENVELOPE_INDEX` is on. ([#342](https://github.com/sweetrb/apple-mail-mcp/issues/342)) |
  358. | `backendByAccount` | object | Present only when `backend` is `"mixed"`: account name → `"envelope-index"` or `"applescript"`. |
  359. **Deadline and cancellation ([#276](https://github.com/sweetrb/apple-mail-mcp/issues/276)).** Tool
  360. calls run one at a time (so they cannot race into Mail.app), which means a long search holds every
  361. later call behind it. An IMAP `search-messages` therefore stops at
  362. `APPLE_MAIL_MCP_SEARCH_DEADLINE_MS` (default `45000`, minimum `2000`, measured from when the request
  363. arrived — time queued behind other calls counts) and returns what it found plus `timedOutMailboxes`,
  364. and it stops the same way when the client cancels the request. The mailbox being searched at that
  365. moment is abandoned by closing its IMAP connection (the next call reconnects), so the queue is
  366. released promptly rather than after a server-side `SEARCH` that can take a minute and a half on a
  367. very large mailbox. A request cancelled while still queued is skipped. Keep the deadline below your
  368. client's own request timeout.
  369. Treat a non-empty `skippedLargeMailboxes` as actionable rather than
  370. informational: re-run scoped to the named mailbox with a `dateFrom`/`dateTo`
  371. window, or configure the [IMAP backend](#imap-backend--opt-in), which searches
  372. those mailboxes server-side. The list fields are optional and are omitted (or
  373. empty) when coverage was complete.
  374. A row the IMAP backend could only read with a reduced item set (its full
  375. `BODYSTRUCTURE`, or its whole `FETCH` response, was unparseable — e.g. a message
  376. forwarded as an attachment many levels deep) is still returned, with a
  377. `metadataIncomplete` note saying what was missing; its `hasAttachments` is then
  378. inferred from the top-level `Content-Type`.
  379. ---
  380. #### `get-message`
  381. Get the full content of a message.
  382. | Parameter | Type | Required | Description |
  383. | ------------ | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  384. | `id` | string | Yes | Message ID |
  385. | `preferHtml` | boolean | No | Return HTML source instead of plain text |
  386. | `mailbox` | string | No | Mailbox holding the message (e.g. `"Sent Items"`). With `account`, opens that mailbox directly instead of scanning every mailbox — this is the fix for timeouts on large folders. A miss there is reported as "not found in <account> / <mailbox>"; it never falls back to the cross-mailbox scan |
  387. | `account` | string | No | Account holding the message. Pair with `mailbox` to skip the cross-mailbox scan |
  388. **Returns:** Subject line and message body (plain text by default, HTML if `preferHtml` is true and HTML content is available). `structuredContent` also carries `rfcMessageId` and, since 2.19.0, two dates: `dateSent` (the message's `Date:` header — Mail's `date sent`) and `dateReceived` (arrival in the mailbox — Mail's `date received` / IMAP `INTERNALDATE`). They differ legitimately by transit time; when they differ by **years**, the mailbox was migrated or re-imported and the arrival timestamp was reset — trust `dateSent` for chronology ([#224](https://github.com/sweetrb/apple-mail-mcp/issues/224)). Since 2.19.6 `dateSent` is **omitted** when it is more than 7 days later than `dateReceived`: a message cannot be sent after it arrived, and Mail.app substitutes a timestamp of its own for a `Date:` header it cannot parse ([#234](https://github.com/sweetrb/apple-mail-mcp/issues/234)). `isHtml` reports what was actually returned — a message with no `text/plain` part returns its HTML part with `isHtml: true`. Bodies are decoded by each part's declared `charset`, falling back to windows-1252 for bytes that are not valid UTF-8.
  389. **Numeric ids — how the message is found ([#270](https://github.com/sweetrb/apple-mail-mcp/issues/270)):** with `account` + `mailbox` the read opens that one mailbox and stops there. Otherwise it opens the mailbox the id was last listed or searched from. A stale remembered location is forgotten before a bounded scan, but an ambiguous remembered account or mailbox stops without a scan. That cross-mailbox scan skips any mailbox holding more than `APPLE_MAIL_MAX_BYID_SCAN_MAILBOX` messages (default `50000`; `0` disables the guard) and stops after ~9s, because Mail's `whose id is` probe costs seconds per hundred thousand messages; a miss then names the mailboxes it skipped and, if it stopped early, the ones it never reached. A mailbox whose size count does not answer within 3s is remembered — on disk, for 7 days, across restarts (`APPLE_MAIL_MCP_STALLED_MAILBOXES_FILE`, default `~/Library/Application Support/apple-mail-mcp/stalled-mailboxes.json`; delete it to forget) — and never counted again, since Mail.app keeps working on an abandoned count and everything after it would queue; the scan stops the moment such a count times out rather than queue behind it. If Mail.app is not running these reads say so instead of launching it. Pass `account` + `mailbox` to read from one of those, or use the message's `imap:` id, which never scans. The same resolution backs `get-message-headers`, `get-thread`'s seed lookup, and the original-message read of `reply-to-message` / `forward-message` and the attachment tools.
  390. > **Large messages / attachments:** reading a full message routes through
  391. > `osascript`, whose captured output buffer defaults to **64 MB**. Override it
  392. > with the `APPLE_MAIL_MCP_MAX_BUFFER` environment variable (in **bytes**) if you
  393. > work with messages whose raw MIME (e.g. a large embedded attachment) exceeds
  394. > that — a value below the message size makes the read fail with a buffer-overflow
  395. > error rather than truncating ([#27](https://github.com/sweetrb/apple-mail-mcp/issues/27)).
  396. ---
  397. #### `get-message-headers`
  398. Return a message's raw RFC 5322 header block — without fetching the body or any attachment — plus the parsed fields chronological and threading work needs. Added in 2.19.0 for mailboxes whose arrival timestamps were reset by a migration ([#224](https://github.com/sweetrb/apple-mail-mcp/issues/224)): the `Date:` header is the author's send time and survives such moves; `INTERNALDATE` / `date received` does not.
  399. | Parameter | Type | Required | Description |
  400. | --------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------- |
  401. | `id` | string | Yes | Message ID (numeric or `imap:…`) |
  402. | `mailbox` | string | No | Mailbox holding the message. With `account`, opens that mailbox directly instead of scanning every mailbox |
  403. | `account` | string | No | Account holding the message. Pair with `mailbox` to skip the cross-mailbox scan |
  404. **Returns:** The raw header block as text. `structuredContent` carries `raw`, every header as ordered `headers[]` (`{name, value}`, folded lines joined, duplicates such as `Received:` kept in wire order, values left RFC 2047-encoded), `headerCount`, and the decoded key fields: `date` (ISO 8601, from the `Date:` header), `dateHeader` (verbatim), `dateReceived` (mailbox arrival time — IMAP `INTERNALDATE` or Mail's `date received`), `messageId`, `subject`, `from`, `to`, `cc`, `replyTo`, `inReplyTo`, `references[]` and `received[]` (first entry = last hop). Fields the message does not carry are omitted. `backend` says which backend read the block (`"imap"` or `"applescript"`), and `warnings[]` appears when a malformed block was repaired ([#234](https://github.com/sweetrb/apple-mail-mcp/issues/234)).
  405. **Backends (`get-message-headers`):** an `imap:` id reads the first 64 KiB of `BODY.PEEK[]` over IMAP and cuts the header block out of it (cheap even for a 20 MB message). That is deliberate: iCloud rewrites 8-bit header bytes to `*` in ENVELOPE and `BODY[HEADER]`, and only `BODY[]` returns them as stored; each line is decoded as UTF-8, falling back to windows-1252, so a raw latin-1 display name survives. A header block larger than the window falls back to `BODY.PEEK[HEADER]`. A numeric id reads Mail's `all headers` property over AppleScript, with the same mailbox-scoped fast path as `get-message`. ⚠️ That property is Mail's own rendering, not the stored bytes: for a `Date:` value Mail cannot parse it drops the value and joins the next header onto the name (`Date: Subject: …`). The tool splits that back apart, reports the date as absent rather than as a Subject string, and says so in `warnings[]`; the `imap:` id for the same message has the real `Date:`.
  406. ---
  407. #### `get-message-rfc822`
  408. Acquire a message's **complete original RFC 822 bytes exactly as the IMAP server stores them**, together with the IMAP identity that links the copy back to its source ([#244](https://github.com/sweetrb/apple-mail-mcp/issues/244)). Built for archival, forensic review and evidence preservation: nothing is decoded, charset-converted, line-ending-normalized or MIME-re-serialized, and the SHA-256 is computed over exactly the bytes returned. **IMAP-only** — it needs an `imap:` id, i.e. an IMAP-configured account ([docs/IMAP-SETUP.md](docs/IMAP-SETUP.md)). There is no AppleScript path on purpose: Mail's bridge exposes its own rendering of a message, not the stored bytes.
  409. | Parameter | Type | Required | Description |
  410. | ---------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  411. | `id` | string | Yes | An `imap:` message id (numeric Mail.app ids are refused with an explanation) |
  412. | `savePath` | string | No | Directory inside the configured allowed roots. Writes the bytes to a **new** `.eml` there instead of returning them inline, and raises the size ceiling to 25 MiB |
  413. | `fileName` | string | No | File name to use with `savePath` (no path separators, no `..`). Default `<account>-<mailbox>-uidv<UIDVALIDITY>-uid<UID>.eml` |
  414. | `maxBytes` | number | No | Refuse — never truncate — a message larger than this many raw bytes. Default and inline maximum 6 MiB (`6291456`); with `savePath` up to 25 MiB (`26214400`) |
  415. **Returns:** a one-line summary as text. `structuredContent` carries the acquisition record: `account`, `mailbox`, `uid`, `uidValidity` (decimal string), `internalDate` (ISO 8601 `INTERNALDATE` — arrival, not the `Date:` header), `flags[]`, `size` (the server's `RFC822.SIZE`), `bytes` (the count actually acquired and hashed), `sha256` (hex, over exactly those bytes), `messageId` (from `ENVELOPE`, for convenience — the authoritative copy is in the bytes), `readMethod` (the IMAP commands issued), `backend: "imap"` and `warnings[]` — plus **`contentBase64`** in inline mode or **`savedPath`** in file mode. The base64 is carried **only** in `structuredContent`; the text block never repeats it.
  416. **Read-only by construction.** The mailbox is opened with `EXAMINE` and the body fetched with `BODY.PEEK[]`, so `\Seen` is not set and no `STORE`, `COPY`, `MOVE`, `APPEND` or `EXPUNGE` is issued. No Mail.app, AppleScript or osascript is involved. The only side effect is the optional file, created with `wx` (an existing file or symlink is refused, never overwritten) and mode `0600`, and only inside the allowed roots — the same policy as `save-attachment`.
  417. **Sizes.** The inline ceiling exists because the MCP stdio transport drops any single message over 10 MB with no error text: 6 MiB of raw bytes is 8 MiB of base64. `maxBytes` is a ceiling, not a cut — an oversize message is refused with its `RFC822.SIZE`, so you can choose between raising `maxBytes` (inline, up to 6 MiB) and `savePath` (up to 25 MiB). `warnings[]` reports an `RFC822.SIZE` that disagrees with the byte count actually received (the hash still covers what was received) and a server that reported no `UIDVALIDITY`.
  418. **Verifying a derivative.** `shasum -a 256 file.eml` must equal `sha256`. `account` + `mailbox` + `uidValidity` + `uid` is the durable pointer back to the source message — a UID on its own is meaningful only for one `UIDVALIDITY`, which the server may change (typically on a mailbox rebuild).
  419. ---
  420. #### `list-messages`
  421. List messages in a mailbox.
  422. | Parameter | Type | Required | Description |
  423. | ------------ | ------- | -------- | ------------------------------------------------ |
  424. | `mailbox` | string | No | Mailbox name (omit to list from all mailboxes) |
  425. | `account` | string | No | Account name |
  426. | `limit` | number | No | Max messages, 1–500 (default: 50) |
  427. | `offset` | number | No | Number of messages to skip, ≥ 0 (for pagination) |
  428. | `from` | string | No | Filter by sender email address or name |
  429. | `unreadOnly` | boolean | No | Only show unread messages |
  430. **Returns:** List of messages with ID, date, subject, sender, mailbox and
  431. account, and `flagColor` when flagged with an explicit color (see the flag-color
  432. note under [`search-messages`](#search-messages), which also supports filtering
  433. by it). As there, each text line names its mailbox and account when the listing
  434. can span more than one.
  435. ⚠️ **Row dates.** Since 2.19.7 every row — on both the **IMAP** and
  436. **AppleScript** backends — carries both `dateSent` (the message's `Date:`
  437. header) and `dateReceived` (mailbox arrival — IMAP `INTERNALDATE`, falling back
  438. to the header date if the server withholds it; Mail's `date received` on the
  439. AppleScript path). They differ legitimately by transit time; when they differ
  440. by **years**, the mailbox was migrated or re-imported and the arrival timestamp
  441. was reset — trust `dateSent` for chronology
  442. ([#224](https://github.com/sweetrb/apple-mail-mcp/issues/224)). Since 2.19.6 the
  443. IMAP `dateSent` is recovered even when the server's own parse of the `Date:`
  444. header failed (legacy locale dates such as `jue ago 30 13:55:12 2007`); both
  445. backends omit `dateSent` (rather than reporting it) when it is more than 7 days
  446. later than `dateReceived` ([#234](https://github.com/sweetrb/apple-mail-mcp/issues/234)).
  447. Before 2.19.7 the AppleScript path carried only `dateReceived`. Sort order keys
  448. on the header date on both backends, which is the stable one.
  449. ---
  450. #### `send-email`
  451. Send a new email immediately.
  452. **⚠️ Safety:** Sends real mail immediately and cannot be unsent. Confirm the recipients, subject, and body with the user before calling.
  453. | Parameter | Type | Required | Description |
  454. | ------------- | --------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  455. | `to` | string[] | Yes | Recipient addresses |
  456. | `subject` | string | Yes | Email subject |
  457. | `body` | string | Yes | Email body (plain text) |
  458. | `cc` | string[] | No | CC recipients |
  459. | `bcc` | string[] | No | BCC recipients |
  460. | `account` | string | No | Mail.app account name or exact sender address (AppleScript path: resolved to one address of an enabled account and verified against Mail's `sender` before sending — no match, or Mail would use another sender, is an error and nothing is sent; the sender used is returned as `from`), or an email-form SMTP From override. An SMTP override must match `APPLE_MAIL_MCP_SMTP_USER`, `APPLE_MAIL_MCP_SMTP_FROM`, or an address in `APPLE_MAIL_MCP_SMTP_ALLOWED_FROM` |
  461. | `attachments` | (string \| {filename, contentBase64})[] | No | Up to 20 attachments: absolute file paths inside the configured read roots (e.g., `"/Users/me/Documents/report.pdf"`) and/or inline `{filename, contentBase64}` objects up to 25 MiB decoded each |
  462. | `transport` | `"applescript"` \| `"smtp"` | No | Send transport. If omitted, **SMTP is used automatically when configured** (otherwise AppleScript), unless `account` is a Mail.app account label, which selects AppleScript. Pass `"smtp"` to require clean MIME (a bare account label is then rejected before sending rather than silently using the configured SMTP identity), or `"applescript"` to force the Mail.app path — see [SMTP transport](#smtp-transport) |
  463. | `replyTo` | string | No | SMTP only: `Reply-To` header, when replies should go somewhere other than the From address. Ignored on the AppleScript transport |
  464. | `inReplyTo` | string | No | SMTP only (2.20.0): thread the message as a reply — the parent's `Message-ID` token with angle brackets, e.g. `"<abc@mail.example.com>"`. Emitted verbatim, never RFC 2047-encoded. See [Threading headers](#threading-headers-inreplyto--references) |
  465. | `references` | string[] | No | SMTP only (2.20.0): the `References` chain, oldest first (the parent's own `References` + its `Message-ID`). Defaults to `[inReplyTo]` when omitted |
  466. **Example:**
  467. ```json
  468. {
  469. "to": ["colleague@company.com"],
  470. "subject": "Meeting Tomorrow",
  471. "body": "Hi, just confirming our meeting at 2pm tomorrow.",
  472. "account": "Work",
  473. "attachments": ["/Users/me/Documents/agenda.pdf"]
  474. }
  475. ```
  476. ##### Threading headers (`inReplyTo` / `references`)
  477. `send-email` and `create-draft` accept caller-built threading headers (2.20.0, #267) for
  478. callers that compose the recipients and quoted text themselves. **Prefer
  479. `reply-to-message`** — it derives recipients, `In-Reply-To`/`References` and the quote
  480. from the original, and (since 2.20.0) takes attachments too.
  481. - Each value must be a single RFC 5322 msg-id token **with** angle brackets
  482. (`<left@right>`, no whitespace); anything else is rejected by validation.
  483. - The headers are always emitted as plain `<id>` tokens — never RFC 2047-encoded, even
  484. for Outlook/Exchange IDs longer than 76 characters (a long header is folded at
  485. whitespace between tokens, which is legal and does not alter the id).
  486. - Mail.app's AppleScript cannot set these headers, so they are **never silently
  487. dropped**: `send-email` refuses them unless the SMTP transport is in use, and
  488. `create-draft` files a threaded draft over IMAP instead of through Mail.app (below).
  489. ##### SMTP transport
  490. On macOS 15+ (Sequoia/Tahoe), Mail.app wraps any AppleScript-injected body in
  491. `<blockquote type="cite">` under the `Apple-Mail-URLShareWrapperClass` template,
  492. so emails sent through the default `applescript` transport render to recipients
  493. as if they were quoted/forwarded (Apple radar **FB11734014**, open since
  494. Ventura). The SMTP transport bypasses Mail.app entirely and submits clean MIME
  495. directly. **Once SMTP is configured, `send-email` uses it automatically** (no
  496. need to pass `transport` per call); pass `transport: "applescript"` to force the
  497. Mail.app path.
  498. Two differences to know when SMTP is auto-preferred:
  499. - **Sent-folder copy is best-effort over IMAP.** SMTP submission itself never
  500. touches IMAP, so since 2.18.0 the server files the sent message into the Sent
  501. mailbox of whichever configured IMAP account's login matches the SMTP identity
  502. (`APPLE_MAIL_MCP_IMAP_*` mirroring `APPLE_MAIL_MCP_SMTP_*`), flagged `\Seen`.
  503. The copy carries the same `Message-ID` that was delivered, so replies thread
  504. against it correctly, and it keeps the `Bcc` header the recipients never see —
  505. your own archive is exactly where that belongs. Results report `sentCopy: true`
  506. or `sentCopy: false` with `sentCopyError`; the field is **absent** when no
  507. configured IMAP account matches the SMTP identity, which is a skip, not a
  508. failure. A copy that fails never fails the send — the mail has already gone.
  509. Before appending, the Sent mailbox is searched for that `Message-ID`; if the
  510. submission server already filed it (Gmail's SMTP always does — the server
  511. waits up to ~3 s for it there), nothing is appended and the result adds
  512. `sentCopyAlreadyFiled: true` alongside `sentCopy: true`.
  513. Use `transport: "applescript"` if you want Mail.app itself to file the copy.
  514. - **`account` is a From override, not account selection.** Over SMTP, `account`
  515. is used as the From address only when it is an email address; a Mail.app
  516. account _label_ (e.g. `"Work"`) can't select an account over SMTP, so a call
  517. that passes one is left on the AppleScript path automatically. To force
  518. account selection, pass `transport: "applescript"` explicitly. For sender
  519. safety, an email-form override must match the SMTP login user, the configured
  520. `APPLE_MAIL_MCP_SMTP_FROM`, or an address listed in the comma-separated
  521. `APPLE_MAIL_MCP_SMTP_ALLOWED_FROM`; any other From address is rejected before
  522. connecting.
  523. Both plain-text and HTML bodies are supported — over SMTP an HTML body (CLI
  524. `--html-body-file`) is sent as `multipart/alternative` with the plain-text
  525. fallback.
  526. ###### SMTP submission outcomes
  527. SMTP acceptance is not confirmation that a message reached an inbox. The
  528. `send-email`, `reply-to-message`, and `forward-message` tools preserve the
  529. server's `accepted` and `rejected` recipient lists when available:
  530. | Outcome | Result | Retry guidance |
  531. | ------------------------------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------- |
  532. | All recipients accepted | `ok: true`, `sent: true` | The submission succeeded. |
  533. | Some recipients rejected | `ok: false`, `sent: true`, `partial: true` | Do not resend to accepted recipients; reconsider only the rejected addresses. |
  534. | Known refusal or failure before submission | Tool error, `ok: false`, `sent: false` | Correct the reported problem before retrying. |
  535. | Final acknowledgment lost | `ok: false`, `deliveryUnknown: true`; `sent` omitted | Verify the outcome before retrying; the server may already have accepted the message. |
  536. Partial and unknown outcomes are **non-error MCP responses** so callers do not
  537. automatically retry a submission that may have succeeded. Check `ok`, `partial`,
  538. and `deliveryUnknown`, not only `isError`. No automatic retry or transport fallback
  539. occurs. Serial sends retain recipient acceptance fields on each result and use
  540. numeric `sent`, `failed`, and optional `unknown` counts rather than a boolean
  541. `sent`. Unknown submissions are excluded from the other two counts. A best-effort
  542. Sent-folder copy remains a separate result, not proof of recipient delivery.
  543. Configure SMTP via environment variables on the MCP server. The password is
  544. read from the macOS **Keychain** by default, so no secret goes in config:
  545. Non-implicit-TLS SMTP connections fail closed if STARTTLS is unavailable.
  546. `APPLE_MAIL_MCP_SMTP_ALLOW_PLAINTEXT=1` is a deliberate escape hatch for a
  547. trusted isolated server or test fixture; it disables the upgrade requirement and
  548. can expose credentials and message content. The server emits a warning when it
  549. is used. Keep the default unset.
  550. | Variable | Required | Default | Description |
  551. | -------------------------------------- | -------- | --------------------------- | -------------------------------------------------------------------------------------------- |
  552. | `APPLE_MAIL_MCP_SMTP_HOST` | Yes | — | SMTP server hostname (e.g. `smtp.fastmail.com`) |
  553. | `APPLE_MAIL_MCP_SMTP_USER` | Yes | — | SMTP username |
  554. | `APPLE_MAIL_MCP_SMTP_PORT` | No | `465` if secure, else `587` | SMTP port |
  555. | `APPLE_MAIL_MCP_SMTP_SECURE` | No | `false` | `true` for implicit TLS (port 465); otherwise STARTTLS |
  556. | `APPLE_MAIL_MCP_SMTP_ALLOW_PLAINTEXT` | No | `0` | Set `1` only for an explicitly trusted plaintext test/server; otherwise STARTTLS is required |
  557. | `APPLE_MAIL_MCP_SMTP_FROM` | No | = user | From address |
  558. | `APPLE_MAIL_MCP_SMTP_ALLOWED_FROM` | No | — | Comma-separated sender aliases permitted as per-message From overrides |
  559. | `APPLE_MAIL_MCP_SMTP_PASSWORD` | No | — | Password (if set, used instead of the Keychain) |
  560. | `APPLE_MAIL_MCP_SMTP_KEYCHAIN_SERVICE` | No | = host | Keychain item service/server name |
  561. | `APPLE_MAIL_MCP_SMTP_KEYCHAIN_ACCOUNT` | No | = user | Keychain item account |
  562. Store the password in the Keychain once (an app-specific password for Gmail/
  563. iCloud). A generic-password item with an explicit service name keeps it from
  564. colliding with the system mail account password, and matches
  565. `APPLE_MAIL_MCP_SMTP_KEYCHAIN_SERVICE`:
  566. ```bash
  567. # Fastmail (Keychain service defaults to the host)
  568. security add-internet-password -s smtp.fastmail.com -a you@example.com -w
  569. # Gmail / Google Workspace, using a dedicated Keychain service name:
  570. # APPLE_MAIL_MCP_SMTP_HOST=smtp.gmail.com
  571. # APPLE_MAIL_MCP_SMTP_USER=you@gmail.com
  572. # APPLE_MAIL_MCP_SMTP_KEYCHAIN_SERVICE=apple-mail-mcp-smtp
  573. security add-generic-password -s apple-mail-mcp-smtp -a you@gmail.com -w
  574. ```
  575. Once the env vars are set, a plain `send-email` (no `transport`) already goes
  576. out clean:
  577. ```json
  578. {
  579. "to": ["colleague@company.com"],
  580. "subject": "Standings",
  581. "body": "Plain body — no blockquote wrapping."
  582. }
  583. ```
  584. ###### `apple-mail-send` CLI (no MCP server required)
  585. The package also installs an `apple-mail-send` binary — a standalone CLI over the
  586. same SMTP path, for cron jobs, scheduled tasks, and scripts that can't run an MCP
  587. session. It reads the identical `APPLE_MAIL_MCP_SMTP_*` env + Keychain config:
  588. ```bash
  589. apple-mail-send \
  590. --from you@example.com --to colleague@company.com \
  591. --subject "Standings" --body-file /tmp/body.txt \
  592. [--html-body-file /tmp/body.html] [--attach /tmp/report.pdf]
  593. ```
  594. Repeatable `--to`/`--cc`/`--bcc`/`--attach`; an `--html-body-file` is sent as a
  595. `multipart/alternative` alongside the plain `--body-file`. Exit codes follow
  596. `sysexits.h` for usage/configuration failures: `64` usage error, `66` unreadable
  597. body file, `78` SMTP not configured. Submission exits are `0` for full acceptance,
  598. `1` for a known failure, `2` for partial acceptance, and `3` for an unknown
  599. outcome. Do not retry the complete command after exit `2` or `3`; follow the
  600. recipient details and verification guidance in its output.
  601. ##### IMAP backend — opt-in
  602. > 📘 **For step-by-step setup (app passwords, Keychain, config methods, multi-account, upgrading, troubleshooting), see the [IMAP / SMTP Setup Guide](https://github.com/sweetrb/apple-mail-mcp/blob/main/docs/IMAP-SETUP.md).** The summary below is the reference; the guide is the walkthrough.
  603. AppleScript runs `search`/`list` predicates client-side over the Apple Event
  604. bridge, which is slow and can time out (false-empty) on large Gmail/IMAP
  605. mailboxes (see [#24](https://github.com/sweetrb/apple-mail-mcp/issues/24)), and
  606. its `delete`/`rename mailbox` and draft handlers don't work on server-side
  607. accounts at all (#42). When an account is configured for IMAP, the MCP routes to
  608. a server-side IMAP backend ([#43](https://github.com/sweetrb/apple-mail-mcp/issues/43))
  609. that is fast and correct on exactly those mailboxes. This is **opt-in and
  610. additive**: any account without IMAP configured behaves exactly as before
  611. (AppleScript).
  612. What routes to IMAP when an account is IMAP-configured:
  613. - **Read:** `search-messages`, `list-messages` (server-side `SEARCH`, typically sub-second), and `get-message`.
  614. - **Folder ops:** `create-mailbox`, `rename-mailbox`, `delete-mailbox` — IMAP's `CREATE`/`RENAME`/`DELETE` succeed on the iCloud/Gmail/Workspace/Exchange mailboxes Mail.app's AppleScript bridge can't touch (#42).
  615. - **Message mutations:** `mark-as-read`/`unread`, `flag-message`/`unflag-message`, `move-message`, `delete-message`.
  616. - **Batch mutations (2.1):** `batch-mark-as-read`/`unread`, `batch-flag`/`unflag-messages`, `batch-move-messages`, `batch-delete-messages` — `imap:` ids are grouped by mailbox and applied as a single `UID STORE`/`UID MOVE`; numeric ids in the same batch still use AppleScript.
  617. - **Counts & stats (2.1):** `get-unread-count` and `list-mailboxes` use `STATUS`; `get-mail-stats` uses `STATUS` + `SEARCH SINCE` — authoritative and fast even on huge mailboxes. As of v2.6.0 these prefer IMAP whenever it's configured (see _Read routing_ below), merging across accounts when no `account` is given.
  618. - **Attachments (2.1):** `list-attachments`, `save-attachment`, `fetch-attachment` use `BODYSTRUCTURE` + `FETCH BODY[part]` for `imap:` ids — faster and able to see MIME-embedded attachments AppleScript misses.
  619. - **Threading (2.1):** `get-thread` links a conversation via `References`/`Message-ID` (`HEADER SEARCH`) for an `imap:` seed, falling back to subject grouping otherwise.
  620. **Message ids are backend-tagged.** The IMAP read path emits self-describing ids
  621. of the form `imap:<token>` (the token encodes the account, mailbox path, and
  622. UID). Pass that id back to `get-message`, a message mutation, a batch op, or the
  623. attachment/thread tools and it routes to IMAP automatically; bare numeric ids
  624. continue to use AppleScript. So an agent never has to know which backend a
  625. message came from — the id carries it.
  626. **Read routing (v2.6.0): reads PREFER direct IMAP whenever IMAP is configured.**
  627. The read tools — `search-messages`, `get-thread`, `list-messages`,
  628. `list-mailboxes`, `get-unread-count`, `get-mail-stats` — now go to IMAP whenever
  629. any `APPLE_MAIL_MCP_IMAP_*` account is configured, not just when an explicit
  630. matching `account` is passed. There are three cases:
  631. - **Explicit IMAP account** — single-account IMAP (fast server-side path).
  632. - **Explicit non-IMAP account** — AppleScript (that account isn't on IMAP).
  633. - **No `account` given** — **merge across all accounts**: the query fans out over
  634. _every_ configured IMAP account, **and** AppleScript runs **only for the
  635. accounts no IMAP config covers** (the account list is partitioned — accounts
  636. already served by IMAP are _not_ re-scanned via AppleScript). If every Mail
  637. account is IMAP-configured, AppleScript is skipped entirely. The results are
  638. merged so no account is dropped. Message lists still de-duplicate as a safety
  639. net (preferring the IMAP copy, which carries the round-trippable `imap:` id) and
  640. sort newest-first; count tools (`get-unread-count`, `get-mail-stats`) count each
  641. account via exactly one backend so a coverage mismatch can never double- (or
  642. under-) count.
  643. - **An omitted mailbox on `search-messages` searches the account's entire
  644. store, not just one default folder** (v2.17.1, [#199](https://github.com/sweetrb/apple-mail-mcp/issues/199)).
  645. Per account, the fan-out uses the server-advertised RFC 6154 `\All`
  646. mailbox when one exists (Gmail/Workspace's `[Gmail]/All Mail`); otherwise
  647. it searches every selectable mailbox the server lists (iCloud, generic
  648. IMAP), merges the matches, de-duplicates by Message-ID, and sorts
  649. newest-first before applying `limit`/`offset`. A mailbox that can't be
  650. selected or searched is named in the result instead of silently dropping
  651. coverage. Scanning every mailbox on a large, deeply-nested account costs
  652. one `SEARCH` + a bounded `FETCH` per mailbox over the pooled IMAP
  653. connection — pin a `mailbox` to skip the fan-out when you already know
  654. where to look. `list-messages` (no query) still defaults an omitted
  655. mailbox to `INBOX` on every provider — only unscoped _search_ scans the
  656. whole account.
  657. If IMAP is **not** configured at all, every read behaves exactly as before
  658. (pure AppleScript). The three mailbox-**write** ops (`create-mailbox`,
  659. `delete-mailbox`, `rename-mailbox`) remain conservative — they route to IMAP only
  660. for an explicitly-named IMAP account, never on an omitted account.
  661. | Variable | Required | Default | Description |
  662. | -------------------------------------- | -------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  663. | `APPLE_MAIL_MCP_IMAP_USER` | Yes | — | Login address; setting it enables IMAP |
  664. | `APPLE_MAIL_MCP_IMAP_ACCOUNT` | No | = user | Mail account name to match for routing |
  665. | `APPLE_MAIL_MCP_IMAP_HOST` | No | `imap.gmail.com` | IMAP server hostname |
  666. | `APPLE_MAIL_MCP_IMAP_PORT` | No | `993` | IMAP port (993 = implicit TLS) |
  667. | `APPLE_MAIL_MCP_IMAP_ALLOW_PLAINTEXT` | No | `0` | Set `1` only for an explicitly trusted plaintext test/server; otherwise STARTTLS is required |
  668. | `APPLE_MAIL_MCP_IMAP_PASSWORD` | No | — | Password (if set, used instead of the Keychain) |
  669. | `APPLE_MAIL_MCP_IMAP_KEYCHAIN_SERVICE` | No | — | Keychain item service/server name |
  670. | `APPLE_MAIL_MCP_IMAP_KEYCHAIN_ACCOUNT` | No | = user | Keychain item account |
  671. | `APPLE_MAIL_MCP_IMAP_ACCOUNTS` | No | — | JSON array of **additional** IMAP accounts for multi-account setups (see below) |
  672. | `APPLE_MAIL_MCP_IMAP_IDLE` | No | `0` | Set `1` to enable IMAP IDLE push notifications (new-mail alerts) for every configured account |
  673. | `APPLE_MAIL_MCP_IMAP_IDLE_MS` | No | `30000` | Idle timeout (ms) before a pooled IMAP connection is closed (`0` = never close) |
  674. | `APPLE_MAIL_MCP_STATS_BUDGET_MS` | No | `25000` | Per-account wall-clock budget for `get-mail-stats` (minimum `1000`). Raise it for very large accounts |
  675. | `APPLE_MAIL_MCP_STATS_DEADLINE_MS` | No | `50000` | Overall wall-clock deadline for one `get-mail-stats` call (minimum `2000`), measured from when the request arrived and covering time queued behind other tool calls, account enumeration **and** every per-account read. Keep it below your client's request timeout |
  676. | `APPLE_MAIL_MCP_SEARCH_DEADLINE_MS` | No | `45000` | Overall wall-clock deadline for one IMAP `search-messages` call (minimum `2000`), measured from when the request arrived. On expiry the search returns partial results plus `timedOutMailboxes` instead of holding the tool-call queue. Keep it below your client's request timeout |
  677. **Multiple IMAP accounts (C2):** set `APPLE_MAIL_MCP_IMAP_ACCOUNTS` to a JSON array, e.g.
  678. `[{"account":"Work","user":"me@co.com","host":"imap.co.com","keychainService":"imap.co.com"}]`.
  679. Each entry accepts `account`, `user`, `host`, `port`, `password`, `keychainService`,
  680. `keychainAccount`. Calls route to the account matching their `account` argument (or the
  681. decoded `imap:` id), and each account keeps its own pooled connection.
  682. Non-implicit-TLS IMAP connections require STARTTLS and fail closed when the server
  683. does not offer a usable upgrade. `APPLE_MAIL_MCP_IMAP_ALLOW_PLAINTEXT=1` is a
  684. deliberate escape hatch for a trusted isolated server or test fixture; it disables
  685. the upgrade requirement and can expose credentials and message content. Keep the
  686. default unset.
  687. As with SMTP, the password is read from the macOS **Keychain** by default (use
  688. an app-specific password for Gmail/Workspace/iCloud), so no secret goes in
  689. config. Gmail label semantics: common names (`All Mail`, `Sent`, `Trash`,
  690. `Spam`, `Important`, …) map to their `[Gmail]/…` IMAP paths automatically.
  691. > Note: IMAP connections are pooled — one kept-alive connection per account is
  692. > reused across calls (verified with a NOOP, closed after `APPLE_MAIL_MCP_IMAP_IDLE_MS`
  693. > of inactivity), so there's no per-call connection overhead ([#50](https://github.com/sweetrb/apple-mail-mcp/issues/50)).
  694. >
  695. > **iCloud:** set `APPLE_MAIL_MCP_IMAP_HOST=imap.mail.me.com`, `APPLE_MAIL_MCP_IMAP_USER`
  696. > to your iCloud address, `APPLE_MAIL_MCP_IMAP_ACCOUNT` to the Mail account name
  697. > (e.g. `iCloud`), and use an **app-specific password** (from appleid.apple.com)
  698. > stored in the Keychain.
  699. ##### Connection footprint (playing nice with Gmail)
  700. IMAP connections are a shared, capped resource: **Gmail allows at most 15
  701. simultaneous IMAP connections per account**, and Apple Mail itself needs some of
  702. those slots. This server keeps its footprint small:
  703. - **One pooled connection per account**, reused across calls and **closed after
  704. ~30s idle** (tune with `APPLE_MAIL_MCP_IMAP_IDLE_MS`; `0` = never close). So a
  705. server that isn't actively serving IMAP calls holds **zero** connections.
  706. - **IMAP IDLE is opt-in** (`APPLE_MAIL_MCP_IMAP_IDLE=1`). When on, it adds **one
  707. persistent connection per account** (a long-lived watcher), on top of the
  708. pooled request connection — leave it off if you don't need push notifications.
  709. - **Connections are dropped on shutdown** — SIGINT/SIGTERM and stdin-EOF (the
  710. MCP client/parent going away). As of **v2.6.1** the server also **self-exits if
  711. it becomes orphaned** (parent force-quit/crashed → reparented to launchd),
  712. polling every 30s, so it can't linger holding sockets after its session is gone.
  713. The catch is **multiple concurrent instances**. A host like the Claude desktop
  714. app spawns a _separate_ set of MCP servers per open conversation (and respawns
  715. them after a crash), so the footprint is **per instance × accounts**. With IDLE
  716. off, an idle instance trends to 0 connections; with many _active_ conversations
  717. or IDLE on, the per-account total climbs toward Gmail's 15-connection cap and can
  718. starve Apple Mail of slots (→ intermittent "cannot connect"). If you hit that,
  719. close idle Claude conversations, keep `APPLE_MAIL_MCP_IMAP_IDLE` off unless you
  720. need push, and/or lower `APPLE_MAIL_MCP_IMAP_IDLE_MS`.
  721. ##### Configuration file (when the host strips `env`)
  722. Some host apps (e.g. Claude Desktop) launch the MCP server with a scrubbed
  723. environment and ignore the `env` block in their server config, so there's no way
  724. to pass `APPLE_MAIL_MCP_*` settings through it. In that case, put them in a JSON
  725. file the host doesn't manage — `APPLE_MAIL_MCP_CONFIG_FILE`, or by default
  726. `~/Library/Application Support/apple-mail-mcp/config.json`:
  727. ```json
  728. {
  729. "APPLE_MAIL_MCP_IMAP_USER": "you@gmail.com",
  730. "APPLE_MAIL_MCP_IMAP_HOST": "imap.gmail.com",
  731. "APPLE_MAIL_MCP_IMAP_KEYCHAIN_SERVICE": "imap.gmail.com",
  732. "APPLE_MAIL_MCP_IMAP_KEYCHAIN_ACCOUNT": "you@gmail.com",
  733. "APPLE_MAIL_MCP_IMAP_IDLE": "1"
  734. }
  735. ```
  736. The server reads it at startup and merges values into the environment **without
  737. overriding** anything already set there (so an explicit `env` still wins). Store
  738. only non-secret config here — **passwords belong in the Keychain**, never in this
  739. file.
  740. ##### Push notifications (IMAP IDLE) — opt-in
  741. When `APPLE_MAIL_MCP_IMAP_IDLE=1`, the server opens a dedicated, long-lived
  742. connection to **each configured IMAP account** and watches its INBOX for new
  743. mail. On arrival it pushes two MCP notifications to the client (no polling by the
  744. client required):
  745. 1. **`notifications/message`** (logging) — a human-readable line, e.g.
  746. `New mail in "Work": 2 new message(s) (INBOX now 1843).`
  747. 2. **`notifications/resources/updated`** — for the affected account's resource
  748. `mail://mailboxes/{account}`, so a client subscribed to that resource knows to
  749. re-read it.
  750. This requires an IMAP account to be configured (single-account env or
  751. `APPLE_MAIL_MCP_IMAP_ACCOUNTS`); accounts that only use AppleScript aren't
  752. watched. Detection is **real-time** via the IMAP IDLE `EXISTS` event where the
  753. server pushes it, with an automatic **polling fallback** for servers that don't.
  754. Dropped connections reconnect with backoff, and the watchers shut down cleanly on
  755. `SIGINT`/`SIGTERM`.
  756. Enable it in your MCP client config alongside the IMAP settings:
  757. ```json
  758. {
  759. "mcpServers": {
  760. "apple-mail": {
  761. "command": "node",
  762. "args": ["/path/to/apple-mail-mcp/build/index.js"],
  763. "env": {
  764. "APPLE_MAIL_MCP_IMAP_USER": "you@gmail.com",
  765. "APPLE_MAIL_MCP_IMAP_KEYCHAIN_SERVICE": "imap.gmail.com",
  766. "APPLE_MAIL_MCP_IMAP_IDLE": "1"
  767. }
  768. }
  769. }
  770. }
  771. ```
  772. > Note: this is most useful with clients that surface MCP logging messages or
  773. > subscribe to resource-update notifications. Clients that ignore notifications
  774. > are unaffected — the feature is opt-in and adds no behavior unless enabled.
  775. ---
  776. #### `send-serial-email`
  777. Send individual personalized emails to a list of recipients (mail merge). Each recipient receives their own email — recipients don't see each other. Supports `{{placeholder}}` tokens in both subject and body.
  778. | Parameter | Type | Required | Description |
  779. | ------------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
  780. | `recipients` | object[] | Yes | List of recipients, max 100 (see below) |
  781. | `subject` | string | Yes | Email subject — use `{{Key}}` for placeholders |
  782. | `body` | string | Yes | Email body — use `{{Key}}` for placeholders |
  783. | `account` | string | No | Mail.app account label (AppleScript), or an allowed email-form SMTP From override |
  784. | `transport` | string | No | `smtp` or `applescript` for the whole batch. If omitted, configured SMTP is used unless `account` is a Mail.app label. Explicit SMTP rejects a bare label, and a missing SMTP credential or unapproved sender stops the batch before anything is sent — never a fallback to Mail.app |
  785. | `delayMs` | number | No | Delay between sends in ms (default: 500, max 10000) |
  786. Each recipient object:
  787. | Field | Type | Required | Description |
  788. | ----------- | ------ | -------- | ------------------------------------------- |
  789. | `email` | string | Yes | Recipient email address |
  790. | `variables` | object | Yes | Key-value pairs for placeholder replacement |
  791. **Example:**
  792. ```json
  793. {
  794. "recipients": [
  795. { "email": "alice@example.com", "variables": { "Name": "Alice", "Company": "Acme" } },
  796. { "email": "bob@example.com", "variables": { "Name": "Bob", "Company": "Globex" } }
  797. ],
  798. "subject": "Hello {{Name}}!",
  799. "body": "Dear {{Name}},\n\nGreat to connect about {{Company}}.\n\nBest regards"
  800. }
  801. ```
  802. **Returns:** Per-recipient success/failure results with a summary count, plus the `transport` used for the batch.
  803. **⚠️ Safety:** Sends real mail immediately to every recipient and cannot be unsent. Confirm the recipient list, subject, and body with the user before calling.
  804. ---
  805. #### `create-draft`
  806. Save an email to Drafts without sending.
  807. | Parameter | Type | Required | Description |
  808. | ------------- | --------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
  809. | `to` | string[] | Yes | Recipient addresses |
  810. | `subject` | string | Yes | Email subject |
  811. | `body` | string | Yes | Email body (plain text) |
  812. | `cc` | string[] | No | CC recipients |
  813. | `bcc` | string[] | No | BCC recipients |
  814. | `account` | string | No | Account for draft. With `inReplyTo`/`references` it must name a configured IMAP account (label or login) |
  815. | `attachments` | (string \| {filename, contentBase64})[] | No | Up to 20 attachments: absolute file paths inside the configured read roots and/or inline `{filename, contentBase64}` objects up to 25 MiB decoded each |
  816. | `inReplyTo` | string | No | (2.20.0) Parent `Message-ID` token, e.g. `"<abc@mail.example.com>"` — makes this a **threaded draft** (see below) |
  817. | `references` | string[] | No | (2.20.0) `References` chain, oldest first; defaults to `[inReplyTo]` |
  818. **Returns:** Confirmation that draft was created, with `transport` (`applescript`, or `imap` for a threaded draft).
  819. **Threaded drafts (2.20.0, #267):** Mail.app's `outgoing message` has no header property,
  820. so a draft with `inReplyTo`/`references` cannot go through AppleScript. Instead the
  821. server composes it with the same MIME builder as the SMTP send (attachments included) and
  822. files it over IMAP into the account's Drafts mailbox (SPECIAL-USE `\Drafts`), flagged
  823. `\Draft`. The account is `account` when given (it must be a configured IMAP account —
  824. pass the exact `accountLabel` or login from `list-accounts`/your `APPLE_MAIL_MCP_IMAP_*`
  825. config, e.g. `"user@icloud.com"`; a generic provider name like `"iCloud"` is not a
  826. recognized alias and is refused);
  827. otherwise the IMAP account whose login is the SMTP identity, else the only configured
  828. IMAP account. When none qualifies — IMAP unconfigured, an unknown `account`, or several
  829. accounts and no way to choose — the call **fails and files nothing**; it never falls back
  830. to an unthreaded Mail.app draft. The result names the Drafts `mailbox`, the `account` and
  831. the draft's `messageId`. Without threading headers, `create-draft` is unchanged
  832. (AppleScript).
  833. #### `update-saved-draft`
  834. Preview or edit an existing **stored** draft (#372). Requires a configured IMAP
  835. account and exactly one selectable SPECIAL-USE `\Drafts` mailbox; there is no
  836. AppleScript or SMTP fallback. The message itself must carry `\Draft` and must
  837. not be marked `\Deleted`. Editing requires UIDPLUS, so removal uses **UID
  838. EXPUNGE**, never a global EXPUNGE that could remove unrelated messages.
  839. | Parameter | Type | Required | Description |
  840. | --------------------- | ------- | ------------- | ---------------------------------------------------------------------------------------------------------------------- |
  841. | `draftId` | string | Yes | Fresh `imap:` ID from `list-messages` on Drafts. Numeric IDs are refused. |
  842. | `dryRun` | boolean | No | Defaults to `true`: only read and preview, including proposed changes when supplied. |
  843. | `approvedSha256` | string | For an update | `preview.sha256` of the current stored source. |
  844. | `approvedUidValidity` | string | For an update | `preview.uidValidity` of the current source mailbox. The UID is encoded in `draftId` and also returned in the preview. |
  845. | `changes` | object | For an update | Partial patch; omitted fields remain unchanged. |
  846. `changes` accepts `subject`, `to`, `cc`, `bcc`, `body`, `htmlBody`,
  847. `addAttachments` and `removeAttachments`. An explicit `[]` clears a recipient
  848. field. `body` replaces an existing text/plain part and `htmlBody` an existing
  849. text/html part. When both alternatives exist, **supply both** to avoid leaving
  850. a stale rendering. Missing or ambiguous body alternatives, signed/encrypted
  851. content, malformed MIME and unreadable bodies are refused before writing.
  852. Unchanged envelope/threading headers, native signatures and encoded MIME parts
  853. are retained. A changed body is the complete replacement for that body,
  854. including any signature it contains. `addAttachments` uses the same allowlisted
  855. file paths / inline `{filename, contentBase64}` inputs as `create-draft` (up to
  856. 20 additions). `removeAttachments` takes the current preview's **partId** values,
  857. so duplicate filenames are not ambiguous; embedded CID images cannot be removed.
  858. The source and resulting stored MIME are each capped at 25 MiB, and each body
  859. representation in the preview at 100,000 characters.
  860. **Workflow:** list Drafts, call with `dryRun: true`, review `preview` and any
  861. `proposed` changes with the user, then call with `dryRun: false`, the same
  862. `draftId`, the current preview's approval tokens and the approved `changes`.
  863. The tokens identify the **source**; a proposed preview is not yet a stored
  864. revision. A changed UIDVALIDITY or source SHA-256 refuses the edit. The format
  865. matches the UIDVALIDITY/UID/MIME-SHA-256 revision used in the proposed
  866. [`send-saved-draft` work (#241)](https://github.com/sweetrb/apple-mail-mcp/pull/241).
  867. That send feature is separate and is not introduced here.
  868. **Returns:** `status: preview`, `updated` or `unchanged`, `sourceDraftId`,
  869. `draftId`, the stored `preview` (From, To/Cc/Bcc, subject, bodies, attachment
  870. metadata and revision), and optionally `proposed`. On update, the replacement
  871. is APPENDed and its UID and stored bytes verified **before** the old UID is
  872. removed. Use the **new** `draftId` and revision afterwards.
  873. Failures are separate outcomes: `append_failed` leaves the source untouched;
  874. `append_unknown` preserves it and reports any known replacement ID;
  875. `cleanup_failed` reports the saved replacement preview and both IDs. Inspect
  876. Drafts before retrying: neither APPEND nor cleanup is retried automatically.
  877. `sourceRemoved` is true only after confirmation; it is omitted when a cleanup
  878. connection failure leaves the outcome uncertain.
  879. IMAP does not provide an atomic cross-client compare-and-replace. The source is
  880. checked again before APPEND and cleanup; a concurrently created UID is never
  881. deleted, but a racing edit or connection failure may leave multiple versions.
  882. **⚠️ Safety:** This overwrites a draft only and never sends mail. Confirm the
  883. patch with the user before `dryRun: false`. A successful edit removes the old
  884. revision after confirming its replacement; a cleanup failure is not a reason
  885. to repeat the already saved edit.
  886. #### `get-thread`
  887. Group a conversation by normalized subject (across the AppleScript or IMAP backend).
  888. | Parameter | Type | Required | Description |
  889. | --------- | ------ | -------- | ------------------------------------------------------ |
  890. | `id` | string | Yes | A message ID in the conversation (numeric or `imap:…`) |
  891. | `account` | string | No | Account to search (omit to search all) |
  892. | `mailbox` | string | No | Mailbox to search (omit to search all) |
  893. | `limit` | number | No | Max messages in the thread (default 50) |
  894. **Returns:** The conversation's messages, oldest-first. A thread usually spans
  895. mailboxes (INBOX and Sent), so each text line ends with where that message is,
  896. unless the call named one mailbox of one account.
  897. #### `fetch-attachment`
  898. Return an attachment's bytes as base64 (the read counterpart to inline-base64 send).
  899. | Parameter | Type | Required | Description |
  900. | ---------------- | ------ | -------- | --------------------------------------------- |
  901. | `id` | string | Yes | Message ID (numeric or `imap:…`) |
  902. | `attachmentName` | string | Yes | Attachment filename (from `list-attachments`) |
  903. **Returns:** The attachment bytes, base64-encoded (also in `structuredContent.contentBase64`).
  904. **Inline limit:** 3 MiB of decoded bytes on either backend. The result keeps
  905. both base64 representations; its total serialized size is also bounded to
  906. leave room under the MCP SDK's default 10 MiB stdio read buffer. Larger or
  907. unverifiable inline results return an error directing you to `save-attachment`.
  908. IMAP saves retain their separate 25 MiB limit and the existing allowed roots.
  909. ---
  910. #### `resolve-message-id`
  911. Map `imap:` message IDs to their numeric Mail.app IDs, via each message's RFC 5322 `Message-ID` (the join key both backends share). Needed for the AppleScript reply/forward path; direct SMTP replies and forwards read `imap:` IDs without numeric conversion. Numeric IDs pass through unchanged.
  912. | Parameter | Type | Required | Description |
  913. | --------- | -------- | -------- | ------------------------------------------- |
  914. | `ids` | string[] | Yes | 1–100 message IDs, each numeric or `imap:…` |
  915. **Returns:** For each input ID, its `numericId` (or `null` when it can't be resolved) and the `messageId` used, plus `count` and `resolvedCount`. The lookup scopes to the message's account and checks its INBOX first, to avoid scanning a large All Mail/Archive mailbox.
  916. > **You do not need this for flag colors (v2.10.0+).** Colors used to require the numeric-ID path, and older docs and tool descriptions said so. `flag-message` and `batch-flag-messages` now write the color over IMAP directly, as Mail.app's `$MailFlagBit0/1/2` keywords, so a smart mailbox keyed on flag color matches an IMAP-flagged message. Resolving IDs just to apply a color reintroduces the AppleScript/TCC dependency 2.10.0 removed. Flag, move, mark, and delete all accept `imap:` IDs as-is.
  917. ---
  918. #### `reply-to-message`
  919. Reply to an existing message.
  920. | Parameter | Type | Required | Description |
  921. | ------------- | --------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  922. | `id` | string | Yes | Message ID to reply to |
  923. | `account` | string | No | Source account for a numeric ID; provide together with `mailbox` |
  924. | `mailbox` | string | No | Source mailbox path for a numeric ID; provide together with `account` |
  925. | `body` | string | Yes | Reply body (plain text; HTML tags such as `<br>` are not rendered) |
  926. | `replyAll` | boolean | No | Reply to all recipients (default: false) |
  927. | `send` | boolean | No | Send immediately (default: true, false = save as draft) |
  928. | `transport` | string | No | `smtp` or `applescript`; omitted prefers configured SMTP when sending. Drafts use AppleScript. |
  929. | `composition` | string | No | `native-editor` uses Mail's visible editor and preserves its native reply history |
  930. | `attachments` | (string \| {filename, contentBase64})[] | No | Up to 20 attachments, same rules as `send-email`: absolute file paths inside the configured read roots and/or inline `{filename, contentBase64}` objects up to 25 MiB decoded each |
  931. **Example - Reply to sender only:**
  932. ```json
  933. {
  934. "id": "12345",
  935. "body": "Thanks for the update!"
  936. }
  937. ```
  938. **Example - Reply all, save as draft:**
  939. ```json
  940. {
  941. "id": "12345",
  942. "account": "Work",
  943. "mailbox": "INBOX",
  944. "body": "I'll review this and get back to everyone.",
  945. "replyAll": true,
  946. "send": false
  947. }
  948. ```
  949. **Example - Reply all with an attachment (2.20.0):**
  950. ```json
  951. {
  952. "id": "imap:eyJhIjoiV29yayIsInAiOiJJTkJPWCIsInUiOjQyfQ",
  953. "body": "Here is the PDF you asked for.",
  954. "replyAll": true,
  955. "attachments": [
  956. "/Users/me/Documents/quote.pdf",
  957. { "filename": "notes.txt", "contentBase64": "SGVsbG8K" }
  958. ]
  959. }
  960. ```
  961. **Attachments (2.20.0, #267):** same schema, limits (20 items, 25 MiB each) and read
  962. roots as `send-email`, validated before the original is fetched — an out-of-roots path
  963. fails with exactly `send-email`'s error. Recipients, threading headers and the quote are
  964. identical to the same call without attachments. Over SMTP the files ride the same
  965. nodemailer path `send-email` uses, so the Sent-folder copy (`sentCopy`) carries them too.
  966. On the AppleScript transport they are added with `make new attachment` **after** the
  967. reply content is set and before `save`/`send` (inline items are written to `0600` temp
  968. files and removed afterwards), so a `send: false` draft contains both the attachments and
  969. the quoted original. `make new attachment` returns before Mail has loaded the file, so the
  970. script waits until Mail counts every file (bounded at 15 s) before saving or sending
  971. (2.20.16, #293; the same wait applies to `send-email` and `create-draft`). Results report
  972. `attachmentCount`.
  973. **Delivery:** `imap:` IDs are read directly from their encoded account, mailbox, and UID. Numeric IDs are read through Mail.app. With SMTP configured, replies use clean MIME with the original `Message-ID` in `In-Reply-To` and the full `References` chain. Only the original plain-text body is quoted; the new text is not. Pass `transport: "smtp"` to require this path, or `transport: "applescript"` to use Mail.app explicitly.
  974. **Numeric source scope:** Pass `account` and `mailbox` together using the account
  975. and full mailbox path from the original search or listing. Both the original read
  976. and the Mail reply target use that scope; a missing or ambiguous account, mailbox,
  977. or message stops the operation instead of scanning elsewhere. For Mail.app
  978. composition, the original must have a usable `Message-ID`, which is checked again
  979. against the selected message before the composer is created. An `imap:` ID already
  980. encodes its source: omit both fields for that form. Supplying only one field, or
  981. supplying either with an `imap:` ID, returns an error. Without explicit scope,
  982. numeric IDs retain the remembered-location and bounded-scan strategy described
  983. under [numeric IDs](#get-message), but an ambiguous remembered account or mailbox
  984. now stops instead of falling back to a scan. For numeric SMTP replies and forwards,
  985. the configured From mailbox must belong to the source's enabled Mail account,
  986. whether the scope was supplied or resolved. A matching SMTP login or an entry in
  987. `APPLE_MAIL_MCP_SMTP_ALLOWED_FROM` does not authorize a different configured From.
  988. A display name around one valid From mailbox is supported. A local "On My Mac"
  989. source has no Mail account whose SMTP From can be verified, so SMTP stops rather
  990. than selecting an identity.
  991. Unscoped numeric SMTP requests read the MIME source and location together. The
  992. quotation comes from that same MIME source, not a second plaintext lookup. If a
  993. bounded scan cannot establish a unique source because it skipped or could not
  994. reach a mailbox, provide the original account and full mailbox path explicitly.
  995. An unreadable MIME body stops the request; no alternative sender or transport
  996. is chosen.
  997. **AppleScript transport quoting (v2.19.12):** every draft (`send: false`) and any send that falls back to AppleScript (SMTP not configured) also gets the original quoted — an "On \<date\>, \<sender\> wrote:" attribution line followed by the `> `-prefixed original body, built the same way as the SMTP path. Mail's own `reply`/`forward` AppleScript commands generate this quote internally but expose no way to read it back, so it's built here instead of relying on Mail's (unreadable) copy. Unlike SMTP, this path has no sending-identity restriction — it's read-only source lookup, not sending.
  998. **Sender on the AppleScript transport (2.20.15, #294):** Mail's `reply`/`forward` commands set no sender, so Mail would answer from its default sending account. The reply or forward is now sent from the account the original sits in: the original's to/cc address that belongs to that account — or, for a message you sent, its own From address. When none of its to/cc addresses belongs to that account (a message another account forwarded in), the to/cc address that belongs to any other enabled account is used; otherwise the account's first address. The sender is read back before saving or sending; a mismatch deletes the compose and returns an error. A message in an "On My Mac" mailbox has no account, so its recipients are matched against every enabled account and, with no match, the sender is left to Mail. The same applies to `forward-message`.
  999. **Failure behavior:** SMTP and AppleScript-content replies stop if the original source or plain-text body cannot be read, rather than silently dropping the quote. Numeric-message replies can recover text from raw MIME when Mail.app's decoded content is unavailable. A genuinely empty original body is allowed; an unreadable body is not. Native-editor mode preserves Mail's own reply history and requires the original source to be readable, but does not reconstruct its plain-text quote. Once SMTP is selected, a missing password, unreadable source, missing reply address or `Message-ID`, or known SMTP refusal returns an error. Partial acceptance and uncertain submission use the [structured SMTP outcomes](#smtp-submission-outcomes) above instead of implying that nothing was sent. The tool does not silently switch to AppleScript or create an unthreaded new message. With SMTP unconfigured and transport omitted, AppleScript remains available. `send: false` saves a Mail.app draft; combining it with `transport: "smtp"` is rejected before composing.
  1000. The direct IMAP source read is bounded to 25 MiB, including MIME attachments. Its account login must match the SMTP login, configured From, or an explicitly configured `APPLE_MAIL_MCP_SMTP_ALLOWED_FROM` identity; otherwise the call fails rather than sending from an unrelated account. The SMTP configuration still represents a single sending identity, not a per-account SMTP registry.
  1001. Success includes `transport`, `attachmentCount` and, for SMTP when returned by the server, the new `messageId`. Over SMTP a best-effort Sent-folder copy is filed over IMAP exactly as for `send-email` (`sentCopy` / `sentCopyError`, see [SMTP transport](#smtp-transport)). `send-email` is for **new conversations**: adding `Re:` to its subject does not add threading headers. Use this reply tool with the original id instead.
  1002. **⚠️ Safety:** With the default `send: true`, sends real mail immediately and cannot be unsent. Confirm the recipients, subject, and body with the user before calling (or pass `send: false` to save a draft for review).
  1003. ---
  1004. #### `forward-message`
  1005. Forward a message to new recipients.
  1006. | Parameter | Type | Required | Description |
  1007. | ------------- | --------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  1008. | `id` | string | Yes | Message ID to forward |
  1009. | `account` | string | No | Source account for a numeric ID; provide together with `mailbox` |
  1010. | `mailbox` | string | No | Source mailbox path for a numeric ID; provide together with `account` |
  1011. | `to` | string[] | Yes | Recipients to forward to |
  1012. | `body` | string | No | Message to prepend (plain text) |
  1013. | `send` | boolean | No | Send immediately (default: true, false = save as draft) |
  1014. | `transport` | string | No | `smtp` or `applescript`; omitted prefers configured SMTP when sending. Drafts use AppleScript. |
  1015. | `composition` | string | No | `native-editor` uses Mail's visible editor and preserves its native forward history |
  1016. | `attachments` | (string \| {filename, contentBase64})[] | No | Up to 20 additional attachments, same rules as `send-email`: absolute file paths inside the configured read roots and/or inline `{filename, contentBase64}` objects up to 25 MiB decoded each |
  1017. **Delivery:** uses the same source lookup, transport selection, 25 MiB source limit, account-identity check, and failure behavior as `reply-to-message`. A forward deliberately starts a new conversation, so it has no `In-Reply-To` or `References` headers. The existing plain-text forwarding behavior is unchanged: original attachments are not reattached. See [SMTP transport](#smtp-transport). On the AppleScript transport, a `body` is merged with the forwarded-message header block and original text the same way the SMTP path builds it (see `reply-to-message`'s AppleScript transport quoting note); with no `body`, Mail's own forward content is left untouched — unless `attachments` are given, in which case the forwarded-message block is built the same way so Mail has a paragraph to anchor the new files after.
  1018. **Attachments (2.20.0, #267):** `attachments` adds new files to the forward, with or without a prepended `body`, under the same rules, validation and per-transport mechanics as `reply-to-message`'s attachments. They are independent of the original's attachments (which the SMTP path still does not reattach).
  1019. SMTP forwarding requires a readable plain-text original. Scoped AppleScript-content forwards that add a body or attachments also stop if the original text is unreadable; without added content, Mail retains its own forward history. Native-editor mode preserves Mail's native history. An intentionally empty plain-text message is still valid.
  1020. **⚠️ Safety:** With the default `send: true`, sends real mail immediately and cannot be unsent. Confirm the recipients, subject, and body with the user before calling (or pass `send: false` to save a draft for review).
  1021. ---
  1022. #### `mark-as-read` / `mark-as-unread`
  1023. Change read status of a message.
  1024. | Parameter | Type | Required | Description |
  1025. | --------- | ------ | -------- | ----------- |
  1026. | `id` | string | Yes | Message ID |
  1027. ---
  1028. #### `flag-message` / `unflag-message`
  1029. Flag or unflag a message. `flag-message` optionally takes a flag **color**; `unflag-message` removes the flag entirely (which also clears any color).
  1030. | Parameter | Type | Required | Description |
  1031. | --------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
  1032. | `id` | string | Yes | Message ID |
  1033. | `color` | string | No | (`flag-message` only) Flag color: `red`, `orange`, `yellow`, `green`, `blue`, `purple`, `gray` (`grey` accepted). Omit for Mail's default flag. |
  1034. **Flag colors** are an Apple Mail feature — the message's `flag index` (0 red, 1 orange, 2 yellow, 3 green, 4 blue, 5 purple, 6 gray), which is the property a Mail smart mailbox can match on. **The color is applied on both routes** (since 2.10.0): AppleScript sets the flag index directly, and for an **IMAP-routed** id (`imap:…`) the color is written as Mail.app's `$MailFlagBit0/1/2` keywords — a 3-bit field holding the same palette index. `\Flagged` on its own really is colorless, but those keywords ride alongside it in an ordinary `UID STORE`, so a smart mailbox keyed on flag color matches an IMAP-flagged message too. You do **not** need to resolve to a numeric id just to color a flag.
  1035. To **read** a color back, or **find** messages by color, use
  1036. [`search-messages`](#search-messages) (or [`list-messages`](#list-messages) for
  1037. read-back only) — both routes now return `flagColor` (the palette name) on
  1038. every flagged-with-a-color row, and `search-messages` takes a `flagColor`
  1039. filter using this same palette (#286). The IMAP route additionally still
  1040. carries the raw 0-6 `flagColorIndex` for back-compat.
  1041. ---
  1042. #### `delete-message`
  1043. Delete a message (move to trash).
  1044. | Parameter | Type | Required | Description |
  1045. | --------- | ------ | -------- | ----------- |
  1046. | `id` | string | Yes | Message ID |
  1047. `structuredContent` carries `countDelta` — what the delete actually did to the
  1048. source mailbox. See [Auditing destructive operations](#auditing-destructive-operations).
  1049. **⚠️ Safety:** Destructive. Requires explicit user confirmation; search/list first to confirm the message id.
  1050. ---
  1051. #### `move-message`
  1052. Move a message to a different mailbox.
  1053. | Parameter | Type | Required | Description |
  1054. | --------- | ------ | -------- | --------------------------------------------------------------------------------------------- |
  1055. | `id` | string | Yes | Message ID |
  1056. | `mailbox` | string | Yes | Destination mailbox — full path (`Work/Archive`) or a leaf name that is unique on the account |
  1057. | `account` | string | No | Account containing mailbox |
  1058. A destination is matched first as a full path, then as a leaf name. If a leaf
  1059. name matches **more than one** mailbox (e.g. `Archive` under both `Work` and
  1060. `Thornlands`), the move is refused with an error naming every candidate — pass
  1061. the full path. The same applies to `batch-move-messages`, `delete-mailbox` and
  1062. `rename-mailbox`.
  1063. `structuredContent` carries `countDelta` — what the move actually did to the
  1064. **source** mailbox. See [Auditing destructive operations](#auditing-destructive-operations).
  1065. ---
  1066. #### `list-attachments`
  1067. List attachments on a message.
  1068. | Parameter | Type | Required | Description |
  1069. | --------- | ------ | -------- | ----------- |
  1070. | `id` | string | Yes | Message ID |
  1071. **Returns:** List of attachments with name, MIME type, and `size` — the **decoded** byte count,
  1072. i.e. what `fetch-attachment` returns.
  1073. **A numeric `id` resolves the same way the read tools resolve one** (2.20.21): the mailbox the id
  1074. was listed from when that is known, else a bounded cross-mailbox scan that skips very large
  1075. mailboxes and stops at its time budget. An id that several mailboxes hold is **refused**, with the
  1076. candidates named, rather than answered for whichever copy came first — so list or search the
  1077. mailbox you mean immediately before calling this. `imap:…` ids are never ambiguous.
  1078. **Sizes over IMAP.** `BODYSTRUCTURE` reports a part's size in its transfer encoding, so a
  1079. base64 attachment's raw figure is ~4/3 of the file. `list-attachments` converts it: a
  1080. `Content-Disposition` `size=` parameter wins when present; 7bit/8bit/binary parts are exact
  1081. as reported; base64 parts are measured exactly from a short tail of each part (padding and
  1082. line wrap), fetched in one batched `FETCH` for the whole message; quoted-printable parts up
  1083. to 64 KiB are fetched and counted exactly. If a part can't be measured (the probe fails, the
  1084. wrap is irregular, or a quoted-printable part is larger), the size is an estimate within a
  1085. few bytes for base64 — an upper bound for quoted-printable — and the entry carries
  1086. `sizeApproximate: true`. `fetch-attachment` always reports the exact `bytes`.
  1087. ---
  1088. #### `save-attachment`
  1089. Save a message attachment to disk.
  1090. The destination must not already exist: `save-attachment` fails closed instead
  1091. of overwriting an existing file. AppleScript and MIME fallback paths stage the
  1092. bytes privately, commit with an exclusive create, and leave the saved file
  1093. owner-readable/writable (`0600`).
  1094. **A numeric `id` resolves the same way the read tools resolve one** (2.20.21): the mailbox the id
  1095. was listed from when that is known, else the bounded cross-mailbox scan. An id that several
  1096. mailboxes hold **saves nothing** rather than writing some other message's attachment under the
  1097. name you asked for.
  1098. | Parameter | Type | Required | Description |
  1099. | ---------------- | ------ | -------- | -------------------------- |
  1100. | `id` | string | Yes | Message ID |
  1101. | `attachmentName` | string | Yes | Filename of the attachment |
  1102. | `savePath` | string | Yes | Directory to save to |
  1103. ---
  1104. ### Batch Operations
  1105. All batch operations accept an array of message IDs (max 100 per batch) and return per-item success/failure results.
  1106. **Numeric IDs are scoped to the mailbox you listed them from.** Mail.app numbers messages per
  1107. mailbox, so on a label store (Gmail, iCloud) one message answers to the same id in `INBOX`,
  1108. `Important` and `All Mail` at once — and deleting the `All Mail` copy is not the same operation as
  1109. deleting the `INBOX` copy. Each id is therefore bound to the mailbox it was listed/searched from and
  1110. the operation is applied only there, so **list or search the mailbox immediately before acting on
  1111. it**. An id the server hasn't seen listed is accepted only when exactly one mailbox holds it;
  1112. if several do, that id fails with the candidate mailboxes named instead of being applied to an
  1113. arbitrary copy. `imap:…` ids carry their own account + mailbox + UID and are never ambiguous.
  1114. **Say which mailbox with `sourceMailbox` / `sourceAccount`.** The binding above is remembered
  1115. per running server, so a client that reconnects, restarts, or replays a saved list of ids has
  1116. nothing recorded and every id takes the slower whole-tree path — where, on a label store, it is
  1117. likely to be refused as ambiguous. Passing the source mailbox explicitly is the reliable way to
  1118. stay scoped, and it overrides the remembered location. These parameters name where the ids **came
  1119. from**; for `batch-move-messages` that is distinct from `mailbox`, the destination.
  1120. `sourceMailbox` and `sourceAccount` are an atomic scope pair: provide **both** for numeric ids.
  1121. The server never fills in a missing account from mutable default-send state, because the same
  1122. mailbox name can exist in more than one account and numeric ids are only unique within an account
  1123. and mailbox. A whitespace-only source field is rejected. `sourceAccount` by itself pins nothing,
  1124. since the mailbox is what an id is scoped to; `imap:…` ids ignore both fields because they carry
  1125. their own account, mailbox, and UID identity.
  1126. **A repeated id is one message.** `ids` is treated as a set: a duplicate names the same message,
  1127. so it is operated on once, and the batch returns **one result per distinct id**. `success` is
  1128. therefore a count of messages, not of list positions.
  1129. #### `batch-delete-messages`
  1130. | Parameter | Type | Required | Description |
  1131. | --------------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
  1132. | `ids` | string[] | Yes | Message IDs to delete (max 100) |
  1133. | `sourceMailbox` | string | No | Mailbox the **numeric** ids were listed from — pins them to it. Ignored for `imap:` ids. |
  1134. | `sourceAccount` | string | No | Account the numeric ids were listed from. Required when `sourceMailbox` is supplied; on its own it pins nothing. |
  1135. `structuredContent` carries `countDelta` — what the batch actually did to each
  1136. source mailbox. See [Auditing destructive operations](#auditing-destructive-operations).
  1137. **⚠️ Safety:** Destructive. Requires explicit user confirmation; search/list first to confirm the message ids.
  1138. #### `batch-move-messages`
  1139. | Parameter | Type | Required | Description |
  1140. | --------------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
  1141. | `ids` | string[] | Yes | Message IDs to move (max 100) |
  1142. | `mailbox` | string | Yes | Destination mailbox |
  1143. | `account` | string | No | Account containing mailbox |
  1144. | `sourceMailbox` | string | No | Mailbox the **numeric** ids were listed from — pins them to it. Ignored for `imap:` ids. |
  1145. | `sourceAccount` | string | No | Account the numeric ids were listed from. Required when `sourceMailbox` is supplied; on its own it pins nothing. |
  1146. `structuredContent` carries `countDelta` — what the batch actually did to each
  1147. **source** mailbox. See [Auditing destructive operations](#auditing-destructive-operations).
  1148. #### `batch-mark-as-read` / `batch-mark-as-unread`
  1149. | Parameter | Type | Required | Description |
  1150. | --------------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
  1151. | `ids` | string[] | Yes | Message IDs (max 100) |
  1152. | `sourceMailbox` | string | No | Mailbox the **numeric** ids were listed from — pins them to it. Ignored for `imap:` ids. |
  1153. | `sourceAccount` | string | No | Account the numeric ids were listed from. Required when `sourceMailbox` is supplied; on its own it pins nothing. |
  1154. #### `batch-flag-messages` / `batch-unflag-messages`
  1155. | Parameter | Type | Required | Description |
  1156. | --------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  1157. | `ids` | string[] | Yes | Message IDs (max 100) |
  1158. | `color` | string | No | (`batch-flag-messages` only) Flag color — see [`flag-message`](#flag-message--unflag-message). Applied on both routes, so a mixed batch of numeric and `imap:` ids all end up colored. |
  1159. | `sourceMailbox` | string | No | Mailbox the **numeric** ids were listed from — pins them to it. Ignored for `imap:` ids. |
  1160. | `sourceAccount` | string | No | Account the numeric ids were listed from. Required when `sourceMailbox` is supplied; on its own it pins nothing. |
  1161. ---
  1162. ### Mailbox Operations
  1163. #### `list-mailboxes`
  1164. List all mailboxes for an account.
  1165. | Parameter | Type | Required | Description |
  1166. | --------- | ------ | -------- | ---------------------------------------------------------- |
  1167. | `account` | string | No | Account to list from, or `"On My Mac"` for the local store |
  1168. **Returns:** List of mailbox **paths** (account-relative, e.g. `Archive/Inbox` for
  1169. a nested mailbox — a top-level `Inbox` stays `Inbox`) with message and unread
  1170. counts. A source that could not be read is **named** (`partial: true` +
  1171. `failedAccounts`) rather than dropped, and a listing Mail refused outright
  1172. returns an error naming the accounts that do exist — never an empty list.
  1173. **Nested mailboxes and Gmail labels.** Every `mailbox` parameter across this
  1174. server (search-messages, list-messages, get-unread-count, move-message,
  1175. delete-mailbox, rename-mailbox, create-rule's `moveTo`) accepts either the full
  1176. path or a leaf name that is unique across the account — the same rule
  1177. move-message has always used. A leaf name that matches more than one mailbox
  1178. (e.g. a top-level `Inbox` and an `Archive/Inbox` on an Exchange account) is
  1179. refused rather than guessed; pass the full path to disambiguate. This also
  1180. means Gmail's nested special mailboxes now report their real path, e.g.
  1181. `[Gmail]/All Mail` rather than `All Mail` — a visible change from before 2.17.0.
  1182. Matching ignores letter case **and Unicode normalization form**: a typed
  1183. precomposed `México` (NFC) finds a mailbox the server stores decomposed (NFD —
  1184. common for folders created on a Mac, and what iCloud keeps), and the server's
  1185. own stored spelling is what gets selected. Two mailboxes whose names differ
  1186. _only_ in case or normalization look identical in any listing, so a name that
  1187. matches both is refused with an error saying so — rename one of them. For the
  1188. same reason `create-mailbox` treats a normalization-equivalent existing name as
  1189. already existing, and `rename-mailbox` refuses to create such a twin.
  1190. **Messages awaiting expunge are not listed.** On IMAP accounts, search,
  1191. list, thread and mail-stats queries only match messages _not_ flagged
  1192. `\Deleted` (IMAP `UNDELETED`). iCloud keeps flagged-but-never-expunged
  1193. messages out of its message counts yet still returns them from `UID SEARCH`,
  1194. which made a filter-less `list-messages` fail on such a mailbox before 2.19.16.
  1195. **Very large IMAP mailboxes are read newest-first in bounded windows**
  1196. ([#256](https://github.com/sweetrb/apple-mail-mcp/issues/256)). Above 10,000
  1197. messages, a filter-less `list-messages`/`search-messages` pages by message
  1198. sequence number: page `offset` of `limit` is sequence numbers
  1199. `N-offset-limit+1 .. N-offset`, so it fetches UIDs and flags for that range
  1200. alone (plus a small margin; `\Deleted` ones are skipped and the page topped up
  1201. from below) and full rows for the page. The cost is the page, not the offset:
  1202. `limit: 1` at offset 790,000 of a 793,614-message mailbox is one ~33-message
  1203. `FETCH`, not a whole-mailbox `SEARCH` or a walk over every skipped message.
  1204. Offsets count sequence positions. iCloud keeps messages awaiting expunge out of
  1205. the sequence space, so there they are exact; on a server that keeps them in it,
  1206. a page shifts by the number of such messages above it (they are never
  1207. returned).
  1208. A filtered search there runs the same criteria over newest-first sequence
  1209. windows (5,000 messages, growing to 50,000) and stops once the page is full;
  1210. the reported total then reads `at least N` unless the walk reached the bottom
  1211. of the mailbox. A filtered search's deep `offset` has no such shortcut — which
  1212. messages match is only known by searching the skipped windows — so its cost
  1213. still grows with the offset (in 50,000-message `SEARCH` windows); narrow it
  1214. with `dateTo` instead. A `SEARCH` or `FETCH` that fails names the mailbox, its size and
  1215. the server's own reason (or a likely timeout) instead of reporting "no
  1216. messages".
  1217. **Mail's local "On My Mac" mailboxes** are not children of any account — they
  1218. hang off the application — so they are reported under the synthetic account label
  1219. **`On My Mac`**. An unscoped call includes them (listed last); `account="On My
  1220. Mac"` lists only them. `on my computer`, `local` and `local folders` are accepted
  1221. as aliases.
  1222. They deliberately do **not** appear in `list-accounts`, which reports real
  1223. accounts only: the local store is a store, not an account. Nothing selects it
  1224. implicitly — omitting `account` still resolves to a real account for every other
  1225. tool.
  1226. The mail inside them is reachable too: `list-messages` and `search-messages`
  1227. accept `account="On My Mac"`, and `get-message` resolves an id that lives only in
  1228. a local mailbox. An id present **both** in an account mailbox and locally is
  1229. reported as ambiguous rather than silently resolving to the account copy.
  1230. ---
  1231. #### `get-unread-count`
  1232. Get unread message count.
  1233. | Parameter | Type | Required | Description |
  1234. | --------- | ------ | -------- | --------------------------------------------------- |
  1235. | `mailbox` | string | No | Mailbox to check (omit for **INBOX**) |
  1236. | `account` | string | No | Account to check (omit to sum each account's INBOX) |
  1237. **Returns:** The unread count for the requested scope.
  1238. > Omitting `mailbox` counts **INBOX**, not a cross-mailbox total. This changed in 2.8.15: summing every mailbox was slow and wrong on Gmail, where one message appears in INBOX, All Mail and every label it carries. For account-wide totals use [`get-mail-stats`](#get-mail-stats).
  1239. ---
  1240. #### `create-mailbox`
  1241. Create a new mailbox.
  1242. | Parameter | Type | Required | Description |
  1243. | --------- | ------ | -------- | -------------------- |
  1244. | `name` | string | Yes | Mailbox name |
  1245. | `account` | string | No | Account to create in |
  1246. ---
  1247. #### `delete-mailbox`
  1248. Delete a mailbox.
  1249. | Parameter | Type | Required | Description |
  1250. | --------- | ------ | -------- | -------------------------- |
  1251. | `name` | string | Yes | Mailbox name |
  1252. | `account` | string | No | Account containing mailbox |
  1253. **⚠️ Safety:** Destructive — deletes the mailbox and its contents. Requires explicit user confirmation; list mailboxes first to confirm the name.
  1254. ---
  1255. #### `rename-mailbox`
  1256. Rename a mailbox (creates new, moves messages, deletes old).
  1257. | Parameter | Type | Required | Description |
  1258. | --------- | ------ | -------- | -------------------------- |
  1259. | `oldName` | string | Yes | Current mailbox name |
  1260. | `newName` | string | Yes | New mailbox name |
  1261. | `account` | string | No | Account containing mailbox |
  1262. ---
  1263. ### Smart Mailbox Operations (intelligente Postfächer)
  1264. > **Requires Full Disk Access.** These tools read and write `~/Library/Mail/V*/MailData/SyncedSmartMailboxes.plist`, which is TCC-protected. Without Full Disk Access for the server's Node runtime the read simply finds nothing, and the tools report "no smart mailboxes" or "launch Mail at least once" rather than a permission error — see [Node runtime & TCC permissions](https://github.com/sweetrb/apple-mail-mcp/blob/main/docs/NODE-RUNTIME-AND-TCC-PERMISSIONS.md).
  1265. Smart mailboxes are Apple Mail's **criteria-based virtual views** — not real folders, so no messages are moved. AppleScript's `smart mailbox` / `intelligentes Postfach` terms don't compile reliably on localized (e.g. German) macOS, so these tools read and edit `~/Library/Mail/V*/MailData/SyncedSmartMailboxes.plist` directly.
  1266. **How writes stay safe:** creating or deleting a smart mailbox first backs the plist up to `SyncedSmartMailboxes.plist.bak`, edits a temp copy with `plutil`/`PlistBuddy`, validates it with `plutil -lint`, and only then atomically renames it into place. Your **existing** smart mailboxes — including any with date/data criteria — are never rewritten, only the single target entry is added or removed. These tools do **not** quit or restart Mail: **quit Mail first** for reliable results, since a running Mail may not show a new smart mailbox until it's relaunched and can overwrite plist edits it didn't make.
  1267. #### `list-smart-mailboxes`
  1268. List existing smart mailboxes.
  1269. **Parameters:** None
  1270. **Returns:** List of smart mailbox names + criteria summary.
  1271. ---
  1272. #### `create-smart-mailbox`
  1273. Create a smart mailbox with a simple contains rule.
  1274. | Parameter | Type | Required | Description |
  1275. | ----------------- | ------ | -------- | ------------------------------ |
  1276. | `name` | string | Yes | Name for the smart mailbox |
  1277. | `fromContains` | string | No | Match if From contains this |
  1278. | `subjectContains` | string | No | Match if Subject contains this |
  1279. | `bodyContains` | string | No | Match if Body contains this |
  1280. Provide at least one of the three `*Contains` fields.
  1281. **⚠️ Safety:** edits `SyncedSmartMailboxes.plist` (backed up + atomic, existing smart mailboxes preserved). Quit Mail first for reliable results; the new smart mailbox appears the next time Mail launches.
  1282. ---
  1283. #### `delete-smart-mailbox`
  1284. Delete a smart mailbox by name.
  1285. | Parameter | Type | Required | Description |
  1286. | --------- | ------ | -------- | ------------------ |
  1287. | `name` | string | Yes | Smart mailbox name |
  1288. **⚠️ Safety:** destructive — removes the smart mailbox from `SyncedSmartMailboxes.plist` (backed up + atomic; every other smart mailbox is preserved). Not undoable in-app. Confirm the exact name with `list-smart-mailboxes` first, and quit Mail first for reliable results.
  1289. ---
  1290. #### `create-newsletter-smart-mailboxes`
  1291. High-level tool: scan recent messages in your INBOXes, detect likely newsletters (volume + signals like List-Unsubscribe, noreply, repetitive subjects), and create smart mailboxes for them (names prefixed "NL: ...").
  1292. | Parameter | Type | Required | Description |
  1293. | ---------- | ------- | -------- | ------------------------------------------ |
  1294. | `dryRun` | boolean | No | Default true — only propose, do not create |
  1295. | `minCount` | number | No | Min messages from a sender (default 3) |
  1296. | `days` | number | No | Lookback window in days (default 90) |
  1297. Defaults to a **safe dry run** that only proposes. Pass `dryRun: false` to actually create the smart mailboxes for newsletters cluttering your Inbox.
  1298. **⚠️ Safety:** with `dryRun: false` this edits `SyncedSmartMailboxes.plist` (backed up + atomic, existing entries preserved) and can create many smart mailboxes at once — review a dry run first. Scans up to ~400 recent messages per inbox via AppleScript, which can be slow on large mailboxes.
  1299. ---
  1300. ### Account Operations
  1301. #### `list-accounts`
  1302. List all configured Mail accounts.
  1303. **Parameters:** None
  1304. **Returns:** List of account names and email addresses.
  1305. #### `get-account-settings`
  1306. Read the settings of one account: full name, email addresses, enabled, server and port, whether deleted mail goes to the Trash, when Trash/Junk/Sent are emptied, which IMAP folders are kept on the server, and the outgoing (SMTP) server.
  1307. **Parameters:** `account` (name or email address)
  1308. **Returns:** `{ account, settings }`. The password is never read or returned.
  1309. #### `set-account-settings`
  1310. Change settings of one account that cannot lock it out or redirect its mail.
  1311. **Parameters:** `account`, and at least one of `enabled`, `fullName`, `includeWhenGettingNewMail`, `moveDeletedMessagesToTrash`, `emptyTrashOnQuit`, `emptyJunkOnQuit`, `emptySentOnQuit`, `storeDraftsOnServer`, `storeJunkOnServer`, `storeSentOnServer`, `storeDeletedOnServer`, `compactMailboxesWhenClosing`.
  1312. **Returns:** the settings read back, or the settings Mail refused. Servers, ports, user names, passwords and the account's email addresses are read-only here. Allowed in `no_send` mode, not in `read_only`.
  1313. ---
  1314. ### Rules
  1315. #### `list-rules`
  1316. List all mail rules.
  1317. **Parameters:** None
  1318. **Returns:** List of rule names and enabled status.
  1319. ---
  1320. #### `enable-rule` / `disable-rule`
  1321. Enable or disable a mail rule.
  1322. | Parameter | Type | Required | Description |
  1323. | --------- | ------ | -------- | ----------- |
  1324. | `name` | string | Yes | Rule name |
  1325. ---
  1326. #### `create-rule`
  1327. Create a Mail rule with one or more conditions and actions.
  1328. | Parameter | Type | Required | Description |
  1329. | ------------ | -------- | -------- | ------------------------------------------------------------- |
  1330. | `name` | string | Yes | Rule name (must be unique) |
  1331. | `conditions` | object[] | Yes | One or more `{field, operator, value}` (see below) |
  1332. | `actions` | object | Yes | At least one of `markRead`, `markFlagged`, `delete`, `moveTo` |
  1333. | `matchAll` | boolean | No | `true` (default) = all conditions must match; `false` = any |
  1334. | `enabled` | boolean | No | Whether the rule is enabled on creation (default `false`) |
  1335. Each condition is `{ field, operator, value }` where `field` is one of `from`, `to`, `cc`, `subject`, `content` and `operator` is one of `contains`, `notContains`, `equals`, `beginsWith`, `endsWith`. Actions: `markRead` / `markFlagged` / `delete` (booleans), `moveTo` (mailbox name) with optional `moveToAccount`.
  1336. New rules are created **disabled by default**, including rules that delete or move
  1337. messages. Review the conditions and actions with `list-rules` and in Mail.app,
  1338. then call `enable-rule` explicitly when the rule is approved. Set
  1339. `enabled: true` only when immediate activation is deliberate.
  1340. **Example:**
  1341. ```json
  1342. {
  1343. "name": "Newsletters",
  1344. "conditions": [{ "field": "from", "operator": "contains", "value": "newsletter" }],
  1345. "actions": { "markRead": true, "moveTo": "Reading" }
  1346. }
  1347. ```
  1348. ---
  1349. #### `delete-rule`
  1350. Delete a mail rule by name.
  1351. | Parameter | Type | Required | Description |
  1352. | --------- | ------ | -------- | ----------- |
  1353. | `name` | string | Yes | Rule name |
  1354. **⚠️ Safety:** Destructive. Requires explicit user confirmation; list rules first to confirm the name.
  1355. ---
  1356. ### Contacts
  1357. #### `search-contacts`
  1358. Search the macOS Contacts database by name, organization, nickname, or email substring.
  1359. Since 2.8.7 this reads the AddressBook SQLite files directly rather than driving Contacts.app over AppleScript, so **Contacts.app need not be running and no Automation grant is involved** — but the Node runtime does need **Full Disk Access**, and **Node 22.5+** (see [Requirements](#requirements)). Without either, the tool returns an empty list rather than an error.
  1360. | Parameter | Type | Required | Description |
  1361. | --------- | ------ | -------- | --------------------------------------------------------------------------------- |
  1362. | `query` | string | Yes | Substring matched against full name, organization, nickname, or any email address |
  1363. **Returns:** List of contacts with name, email addresses, and phone numbers. Results are **not** truncated — a broad query returns every match.
  1364. ---
  1365. ### Templates
  1366. Email templates are **persisted to disk** so they survive server restarts, stored as JSON at `APPLE_MAIL_MCP_TEMPLATES_FILE` (default `~/Library/Application Support/apple-mail-mcp/templates.json`).
  1367. #### `save-template`
  1368. Save or update an email template.
  1369. | Parameter | Type | Required | Description |
  1370. | --------- | -------- | -------- | -------------------------- |
  1371. | `name` | string | Yes | Template name |
  1372. | `subject` | string | Yes | Default subject line |
  1373. | `body` | string | Yes | Template body |
  1374. | `to` | string[] | No | Default recipients |
  1375. | `cc` | string[] | No | Default CC recipients |
  1376. | `id` | string | No | Template ID (for updating) |
  1377. ---
  1378. #### `list-templates`
  1379. List all saved templates.
  1380. **Parameters:** None
  1381. ---
  1382. #### `get-template`
  1383. Get a template by ID.
  1384. | Parameter | Type | Required | Description |
  1385. | --------- | ------ | -------- | ----------- |
  1386. | `id` | string | Yes | Template ID |
  1387. ---
  1388. #### `delete-template`
  1389. Delete a template.
  1390. | Parameter | Type | Required | Description |
  1391. | --------- | ------ | -------- | ----------- |
  1392. | `id` | string | Yes | Template ID |
  1393. **⚠️ Safety:** Destructive — removes the template from the on-disk store. Requires explicit user confirmation; list templates first to confirm the id.
  1394. ---
  1395. #### `use-template`
  1396. Create a draft from a template, with optional overrides.
  1397. | Parameter | Type | Required | Description |
  1398. | --------- | -------- | -------- | ------------------- |
  1399. | `id` | string | Yes | Template ID |
  1400. | `to` | string[] | No | Override recipients |
  1401. | `cc` | string[] | No | Override CC |
  1402. | `subject` | string | No | Override subject |
  1403. | `body` | string | No | Override body |
  1404. ---
  1405. ### Diagnostics
  1406. #### `health-check`
  1407. Verify Mail.app connectivity and permissions.
  1408. **Parameters:** None
  1409. **Returns:** Status of all health checks (app running, permissions, account access).
  1410. ---
  1411. #### `doctor`
  1412. Run a full setup diagnostic: Mail.app automation permission, account state (flagging disabled accounts), and each configured IMAP/SMTP backend — each reported as ok / warn / fail with an actionable message.
  1413. **Parameters:** None
  1414. **Returns:** A per-check report (`structuredContent` carries the raw `{healthy, checks[]}`).
  1415. ---
  1416. #### `get-mail-stats`
  1417. Get mail statistics.
  1418. | Parameter | Type | Required | Description |
  1419. | --------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------- |
  1420. | `account` | string | No | Limit to one account (uses fast IMAP `STATUS` when that account is IMAP-configured). Omit to merge across all accounts. |
  1421. **Returns:** Total and per-account message/unread counts, plus recently received stats (24h, 7d, 30d). The scoped IMAP path also returns a `perMailbox` breakdown.
  1422. Gathering stats costs one IMAP `STATUS` per mailbox, and Gmail lists every label
  1423. as a mailbox, so a large account is not instant. Accounts are counted
  1424. **concurrently**, and each is bounded by `APPLE_MAIL_MCP_STATS_BUDGET_MS`
  1425. (default `25000`). In the merged all-accounts path an account that fails or
  1426. overruns is reported via `partial: true` + `failedAccounts` rather than being
  1427. folded in as a silent zero; a scoped call to a single account returns an error
  1428. naming the budget instead. Raise the budget if you have a very large account.
  1429. The whole call is additionally bounded by one wall-clock deadline,
  1430. `APPLE_MAIL_MCP_STATS_DEADLINE_MS` (default `50000`), which covers the Mail.app
  1431. account enumeration as well as every per-account read. Per-step budgets alone
  1432. were not enough: their worst cases **add up**, and the sum could exceed a
  1433. client's request timeout, so the call died with nothing returned instead of
  1434. degrading. Keep the deadline below your MCP client's request timeout — whatever
  1435. cannot be read inside it is named in `failedAccounts`, so you always get a
  1436. partial answer rather than a dead call.
  1437. **Concurrent `get-mail-stats` calls do not run concurrently.** Tool calls are
  1438. serialized so they cannot race into Mail.app's single-threaded AppleScript
  1439. dispatch, so each call waits for the ones ahead of it and per-call latency grows
  1440. with queue depth — N concurrent calls take about N × the single-call cost. Since
  1441. this is the most expensive read tool, that is very visible here: measured on 3
  1442. IMAP accounts, three concurrent calls returned at 5.5s / 10.3s / 15.6s against a
  1443. ~5.2s solo cost. The deadline is measured from when the request **arrived**, so
  1444. that wait is spent from the same budget as the work: a call that waited ≥1s
  1445. reports `queueWaitMs`, and one that arrives with its deadline already spent
  1446. returns straight away naming the queue rather than starting work whose answer
  1447. would land after your client has given up. Issue these calls one at a time, and
  1448. prefer `get-unread-count` when a single number will do.
  1449. ---
  1450. #### `get-sync-status`
  1451. Check Mail.app sync activity.
  1452. **Parameters:** None
  1453. **Returns:** Whether sync is detected, pending uploads, recent activity, and seconds since last change.
  1454. ---
  1455. ## Auditing destructive operations
  1456. `delete-message`, `move-message`, `batch-delete-messages` and
  1457. `batch-move-messages` report what they actually did, not merely that Mail.app did
  1458. not raise an error. This exists because of
  1459. [#155](https://github.com/sweetrb/apple-mail-mcp/issues/155): a batch delete was
  1460. reported to have removed two messages whose ids were never passed, and nothing in
  1461. the server recorded enough to explain it.
  1462. ### `countDelta` — always on, no configuration
  1463. Every one of those four tools counts the affected **source** mailbox immediately
  1464. before and immediately after the mutation, **inside the same AppleScript it was
  1465. already running** (no extra `osascript` invocations, no measurable cost), and
  1466. returns the comparison in `structuredContent`:
  1467. ```json
  1468. {
  1469. "ok": true,
  1470. "success": 2,
  1471. "failed": 0,
  1472. "countDelta": [
  1473. {
  1474. "account": "you@gmail.com",
  1475. "mailbox": "INBOX",
  1476. "before": 412,
  1477. "after": 408,
  1478. "expected": 2,
  1479. "observed": 4,
  1480. "status": "over"
  1481. }
  1482. ]
  1483. }
  1484. ```
  1485. `status` is deliberately not a pass/fail flag:
  1486. | `status` | Meaning | Warns? |
  1487. | --------- | ---------------------------------------------------------------------------------------------------------- | ------- |
  1488. | `match` | Exactly as many messages left the mailbox as the operation acted on. | No |
  1489. | `over` | **More** left than were operated on. Messages are unaccounted for. | **Yes** |
  1490. | `unknown` | No comparison this server is willing to assert. `unknownReason` says which of four situations produced it. | No |
  1491. `unknownReason` distinguishes four cases that are _not_ interchangeable:
  1492. | `unknownReason` | Meaning |
  1493. | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  1494. | `count-unreadable` | Mail would not report a count at all (`before`/`after` null). |
  1495. | `no-expectation` | No expectation is predictable, so no comparison exists — a move whose destination **is** the source mailbox. |
  1496. | `count-did-not-move` | The count did not move. On a store that flags deletions instead of removing them this is the **ordinary, correct** reading for an operation that fully succeeded. |
  1497. | `count-partial` | The count moved, but by less than the operation accounted for. A flag-only store cannot produce this, which is why it is worth telling apart. |
  1498. > **`under` was removed in 2.11.0.** It used to mean "fewer left than expected"
  1499. > and was documented as routine. Field evidence retired it — see
  1500. > [Why `observed` is a lower bound](#why-observed-is-a-lower-bound-155).
  1501. #### What an `over` warning does and does not tell you
  1502. Only `over` produces a warning in the tool's text response. Be precise about what
  1503. that warning proves, because a warning is useful only for as long as it is
  1504. trusted:
  1505. - **It establishes** that more messages left the source mailbox across the window
  1506. of the operation than the operation accounted for. That is the data-loss
  1507. direction, and it is the #155 signature.
  1508. - **It does not establish that this server removed them.** The reading is a
  1509. before/after pair around a window, so anything else that removes mail from that
  1510. mailbox inside the window reads identically: a Mail.app rule firing mid-batch,
  1511. a server-side filter, another client (phone, webmail, a second Mail.app)
  1512. deleting or moving, or an IMAP expunge landing between the two counts.
  1513. **Concurrent departure is the benign cause to rule out first**, and the warning
  1514. text says so. What the asymmetry argument actually buys is the other half:
  1515. concurrent _arrivals_ cannot produce `over`, because a message arriving
  1516. mid-operation _raises_ the after-count and biases the reading short.
  1517. That is why `over` is the interesting direction — a strong signal, not a proof.
  1518. Setting `APPLE_MAIL_MCP_AUDIT_LOG` is what settles which one you have: the
  1519. collateral diff below **names** the messages that disappeared, and "the
  1520. newsletter my rule files every morning" is a very different report from a message
  1521. nothing should have touched.
  1522. #### Why `observed` is a lower bound (#155)
  1523. **`observed` is the movement of Mail's count. It is a lower bound on how many
  1524. messages left, not a count of how many left.**
  1525. On iCloud, @scottstern0325 ran the check that settled this: for two batches
  1526. reporting `observed: 0`, the messages were located **in Trash**, matched by
  1527. `date received` + sender against the audit log's pre-image. The deletes had
  1528. happened. Mail's count had not caught up. Across four readings — 0 of 4, 0 of 1
  1529. (a _single-id_ delete), 15 of 16, and 14 of 15 — the shortfall bore no relation
  1530. to batch size, which is what a lagging count looks like and not what a
  1531. store-behaviour rule looks like.
  1532. So a short reading is not evidence about your operation. **The per-id outcomes

Lines 2,001–2,609 are not shown. The link to the file on GitHub has every line.

src/security.test.ts · Bundled script · 303 lines · 1 finding marked
  1. /**
  2. * Tests for security hardening: input validation schemas and path traversal prevention.
  3. */
  4. import { describe, it, expect } from "vitest";
  5. import { resolve, isAbsolute } from "path";
  6. import { homedir } from "os";
  7. import { existsSync } from "fs";
  8. import { escapeForAppleScript, escapeForAppleScriptBody } from "@/services/appleMailManager.js";
  9. import {
  10. ATTACHMENTS_SCHEMA,
  11. BATCH_IDS_SCHEMA,
  12. DATE_FILTER_SCHEMA,
  13. MESSAGE_ID_SCHEMA,
  14. } from "@/schemas.js";
  15. describe("MESSAGE_ID_SCHEMA", () => {
  16. it("accepts valid numeric IDs", () => {
  17. expect(MESSAGE_ID_SCHEMA.parse("12345")).toBe("12345");
  18. expect(MESSAGE_ID_SCHEMA.parse("0")).toBe("0");
  19. expect(MESSAGE_ID_SCHEMA.parse("999999999")).toBe("999999999");
  20. });
  21. it("accepts injection-safe IMAP ids", () => {
  22. expect(MESSAGE_ID_SCHEMA.parse("imap:YWJjXzEyMw")).toBe("imap:YWJjXzEyMw");
  23. });
  24. it("rejects non-numeric IDs", () => {
  25. expect(() => MESSAGE_ID_SCHEMA.parse("abc")).toThrow();
  26. expect(() => MESSAGE_ID_SCHEMA.parse("123abc")).toThrow();
  27. expect(() => MESSAGE_ID_SCHEMA.parse("")).toThrow();
  28. });
  29. it("rejects AppleScript injection attempts", () => {
  30. expect(() => MESSAGE_ID_SCHEMA.parse('1" & do shell script "rm -rf /')).toThrow();
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 35 on GitHub
  31. expect(() => MESSAGE_ID_SCHEMA.parse("1; drop table")).toThrow();
  32. expect(() => MESSAGE_ID_SCHEMA.parse("-1")).toThrow();
  33. });
  34. it("rejects template-style IDs (tmpl_N format)", () => {
  35. expect(() => MESSAGE_ID_SCHEMA.parse("tmpl_1")).toThrow();
  36. });
  37. });
  38. describe("BATCH_IDS_SCHEMA", () => {
  39. it("accepts valid batch of numeric IDs", () => {
  40. const result = BATCH_IDS_SCHEMA.parse(["1", "2", "3"]);
  41. expect(result).toEqual(["1", "2", "3"]);
  42. });
  43. it("accepts a batch of IMAP ids", () => {
  44. expect(BATCH_IDS_SCHEMA.parse(["imap:YWJj", "imap:ZGVm"])).toEqual(["imap:YWJj", "imap:ZGVm"]);
  45. });
  46. it("rejects empty array", () => {
  47. expect(() => BATCH_IDS_SCHEMA.parse([])).toThrow("At least one message ID");
  48. });
  49. it("rejects more than 100 IDs", () => {
  50. const ids = Array.from({ length: 101 }, (_, i) => String(i));
  51. expect(() => BATCH_IDS_SCHEMA.parse(ids)).toThrow("Cannot process more than 100");
  52. });
  53. it("accepts exactly 100 IDs", () => {
  54. const ids = Array.from({ length: 100 }, (_, i) => String(i));
  55. expect(BATCH_IDS_SCHEMA.parse(ids)).toHaveLength(100);
  56. });
  57. it("rejects batch containing non-numeric IDs", () => {
  58. expect(() => BATCH_IDS_SCHEMA.parse(["123", "abc", "456"])).toThrow();
  59. });
  60. });
  61. describe("DATE_FILTER_SCHEMA", () => {
  62. it("accepts valid date strings", () => {
  63. expect(DATE_FILTER_SCHEMA.parse("January 1, 2026")).toBe("January 1, 2026");
  64. expect(DATE_FILTER_SCHEMA.parse("March 15, 2026")).toBe("March 15, 2026");
  65. expect(DATE_FILTER_SCHEMA.parse("2026-03-15")).toBe("2026-03-15");
  66. expect(DATE_FILTER_SCHEMA.parse("3/15/2026")).toBe("3/15/2026");
  67. });
  68. it("accepts undefined (optional)", () => {
  69. expect(DATE_FILTER_SCHEMA.parse(undefined)).toBeUndefined();
  70. });
  71. it("rejects strings with quotes (AppleScript injection)", () => {
  72. expect(() => DATE_FILTER_SCHEMA.parse('"January 1" & do shell script "evil"')).toThrow();
  73. });
  74. it("rejects strings with backslashes", () => {
  75. expect(() => DATE_FILTER_SCHEMA.parse("January\\1")).toThrow();
  76. });
  77. it("rejects strings with parentheses", () => {
  78. expect(() => DATE_FILTER_SCHEMA.parse("date(2026)")).toThrow();
  79. });
  80. it("rejects non-parseable date strings", () => {
  81. expect(() => DATE_FILTER_SCHEMA.parse("31")).toThrow();
  82. expect(() => DATE_FILTER_SCHEMA.parse("abc")).toThrow();
  83. expect(() => DATE_FILTER_SCHEMA.parse("1234567890")).toThrow();
  84. });
  85. });
  86. describe("saveAttachment input validation", () => {
  87. // Test the validation logic that lives in appleMailManager.saveAttachment
  88. // by checking the same regex/logic used there
  89. const isInvalidAttachmentName = (name: string): boolean => {
  90. return /[/\\\0]/.test(name) || name.includes("..");
  91. };
  92. it("blocks forward slash in attachment name", () => {
  93. expect(isInvalidAttachmentName("../../etc/passwd")).toBe(true);
  94. expect(isInvalidAttachmentName("path/to/file.txt")).toBe(true);
  95. });
  96. it("blocks backslash in attachment name", () => {
  97. expect(isInvalidAttachmentName("file\\name.txt")).toBe(true);
  98. });
  99. it("blocks null bytes in attachment name", () => {
  100. expect(isInvalidAttachmentName("file\0name.txt")).toBe(true);
  101. });
  102. it("blocks directory traversal in attachment name", () => {
  103. expect(isInvalidAttachmentName("..")).toBe(true);
  104. expect(isInvalidAttachmentName("../secret")).toBe(true);
  105. });
  106. it("allows normal attachment names", () => {
  107. expect(isInvalidAttachmentName("report.pdf")).toBe(false);
  108. expect(isInvalidAttachmentName("Q1 Budget (Final).xlsx")).toBe(false);
  109. expect(isInvalidAttachmentName("résumé.docx")).toBe(false);
  110. });
  111. const isAllowedPath = (savePath: string): boolean => {
  112. const resolvedPath = resolve(savePath);
  113. const allowedPrefixes = [homedir(), "/tmp", "/private/tmp", "/Volumes"];
  114. return allowedPrefixes.some((prefix: string) => resolvedPath.startsWith(prefix));
  115. };
  116. it("allows paths under home directory", () => {
  117. expect(isAllowedPath(`${homedir()}/Downloads`)).toBe(true);
  118. });
  119. it("allows /tmp", () => {
  120. expect(isAllowedPath("/tmp")).toBe(true);
  121. expect(isAllowedPath("/tmp/attachments")).toBe(true);
  122. });
  123. it("blocks traversal out of allowed directories", () => {
  124. expect(isAllowedPath("/tmp/../../etc")).toBe(false);
  125. });
  126. it("blocks /etc directly", () => {
  127. expect(isAllowedPath("/etc")).toBe(false);
  128. });
  129. it("blocks /usr paths", () => {
  130. expect(isAllowedPath("/usr/local")).toBe(false);
  131. });
  132. });
  133. describe("buildAttachmentCommands validation", () => {
  134. // Mirror the logic from appleMailManager.ts buildAttachmentCommands()
  135. // to test the validation in isolation without needing real files.
  136. function escapeForAppleScript(text: string): string {
  137. if (!text) return "";
  138. return text.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
  139. }
  140. function buildAttachmentCommands(attachments?: string[]): string {
  141. if (!attachments || attachments.length === 0) return "";
  142. for (const filePath of attachments) {
  143. if (!isAbsolute(filePath)) {
  144. throw new Error(`Attachment path must be absolute: "${filePath}"`);
  145. }
  146. if (!existsSync(filePath)) {
  147. throw new Error(`Attachment file not found: "${filePath}"`);
  148. }
  149. }
  150. let commands = "";
  151. for (const filePath of attachments) {
  152. const safePath = escapeForAppleScript(filePath);
  153. commands += `make new attachment with properties {file name:POSIX file "${safePath}"} at after the last paragraph\n`;
  154. }
  155. return commands;
  156. }
  157. it("returns empty string for undefined", () => {
  158. expect(buildAttachmentCommands(undefined)).toBe("");
  159. });
  160. it("returns empty string for empty array", () => {
  161. expect(buildAttachmentCommands([])).toBe("");
  162. });
  163. it("rejects relative paths", () => {
  164. expect(() => buildAttachmentCommands(["relative/path.pdf"])).toThrow("must be absolute");
  165. });
  166. it("rejects paths starting with ./", () => {
  167. expect(() => buildAttachmentCommands(["./file.pdf"])).toThrow("must be absolute");
  168. });
  169. it("rejects nonexistent files", () => {
  170. expect(() => buildAttachmentCommands(["/nonexistent/file.pdf"])).toThrow("not found");
  171. });
  172. it("generates correct AppleScript for valid files", () => {
  173. // Use a file we know exists
  174. const testFile = "/usr/bin/env";
  175. const result = buildAttachmentCommands([testFile]);
  176. expect(result).toContain("make new attachment");
  177. expect(result).toContain("POSIX file");
  178. expect(result).toContain(testFile);
  179. });
  180. it("escapes double quotes in file paths", () => {
  181. // Test the escaping function directly since we can't easily mock existsSync
  182. const escaped = escapeForAppleScript('/Users/test/file "name".pdf');
  183. expect(escaped).toContain('file \\"name\\"');
  184. });
  185. it("handles multiple attachments", () => {
  186. const testFile = "/usr/bin/env";
  187. const result = buildAttachmentCommands([testFile, testFile]);
  188. const matches = result.match(/make new attachment/g);
  189. expect(matches).toHaveLength(2);
  190. });
  191. it("rejects more than 20 attachments at schema level", () => {
  192. const paths = Array.from({ length: 21 }, (_, i) => `/tmp/file${i}.pdf`);
  193. expect(() => ATTACHMENTS_SCHEMA.parse(paths)).toThrow("Cannot attach more than 20");
  194. });
  195. it("accepts exactly 20 attachments at schema level", () => {
  196. const paths = Array.from({ length: 20 }, (_, i) => `/tmp/file${i}.pdf`);
  197. expect(ATTACHMENTS_SCHEMA.parse(paths)).toHaveLength(20);
  198. });
  199. });
  200. describe("escapeForAppleScript vs escapeForAppleScriptBody (audit #10 + body newlines)", () => {
  201. // These test the REAL exported functions from appleMailManager.ts, not a
  202. // local mirror. The single-line variant strips control chars entirely; the
  203. // body variant converts line breaks to the two-character AppleScript escape
  204. // sequence `\n` so paragraph breaks survive without any raw control
  205. // character ever entering the emitted literal.
  206. it("body: newlines survive as the \\n escape sequence", () => {
  207. const body = "Paragraph one.\n\nParagraph two.\nLine three.";
  208. const escaped = escapeForAppleScriptBody(body);
  209. expect(escaped).toBe("Paragraph one.\\n\\nParagraph two.\\nLine three.");
  210. // No raw control characters in the emitted literal
  211. // eslint-disable-next-line no-control-regex
  212. expect(escaped).not.toMatch(/[\x00-\x1f\x7f]/);
  213. });
  214. it("body: CRLF and lone CR normalize to \\n", () => {
  215. expect(escapeForAppleScriptBody("a\r\nb\rc\nd")).toBe("a\\nb\\nc\\nd");
  216. });
  217. it("body: tabs become the \\t escape sequence", () => {
  218. expect(escapeForAppleScriptBody("col1\tcol2")).toBe("col1\\tcol2");
  219. });
  220. it("body: injection combining quotes and raw newlines cannot escape the literal", () => {
  221. const attack = '"\ntell application "Finder" to delete every file\n"';
  222. const escaped = escapeForAppleScriptBody(attack);
  223. // Quotes are escaped, newlines are the two-char sequence — the payload
  224. // stays inside the AppleScript string literal.
  225. expect(escaped).toBe('\\"\\ntell application \\"Finder\\" to delete every file\\n\\"');
  226. // eslint-disable-next-line no-control-regex
  227. expect(escaped).not.toMatch(/[\x00-\x1f\x7f]/);
  228. });
  229. it("body: backslash escaped before quote/newline (no double-escape confusion)", () => {
  230. // A literal backslash followed by the letter n must NOT collapse into a
  231. // linefeed escape ambiguity: input \n (two chars) → \\n (three chars out).
  232. expect(escapeForAppleScriptBody("\\n")).toBe("\\\\n");
  233. // And a real newline after a backslash: \ + LF → \\ + \n
  234. expect(escapeForAppleScriptBody("\\\n")).toBe("\\\\\\n");
  235. });
  236. it("body: strips remaining control characters (NUL, ESC, DEL)", () => {
  237. expect(escapeForAppleScriptBody("a\x00b\x1bc\x7fd")).toBe("abcd");
  238. });
  239. it("single-line: still strips ALL control chars including newlines", () => {
  240. expect(escapeForAppleScript("Subject\nline\r\ntwo\ttabbed\x00")).toBe("Subjectlinetwotabbed");
  241. });
  242. it("single-line: quote/backslash escaping unchanged", () => {
  243. expect(escapeForAppleScript('say "hi" \\ bye')).toBe('say \\"hi\\" \\\\ bye');
  244. });
  245. it("both: empty and falsy input yield empty string", () => {
  246. expect(escapeForAppleScript("")).toBe("");
  247. expect(escapeForAppleScriptBody("")).toBe("");
  248. });
  249. });
src/utils/headers.test.ts · Bundled script · 403 lines · 1 finding marked
  1. import { describe, it, expect } from "vitest";
  2. import {
  3. decodeEncodedWords,
  4. decodeHeaderBytes,
  5. headersStructured,
  6. isoOrUndefined,
  7. MAX_SENT_AFTER_RECEIVED_MS,
  8. parseHeaderBlock,
  9. plausibleDateSent,
  10. } from "./headers.js";
  11. const BLOCK = [
  12. "Received: from mx2.example.net (mx2.example.net [10.0.0.2])",
  13. "\tby imap.example.com with ESMTPS id abc123;",
  14. "\tWed, 03 Jun 2020 14:05:00 +0000",
  15. "Received: from sender.example.org ([10.0.0.9])",
  16. " by mx2.example.net; Wed, 03 Jun 2020 14:04:58 +0000",
  17. "Date: Wed, 3 Jun 2020 16:04:55 +0200 (CEST)",
  18. "From: =?UTF-8?Q?Jos=C3=A9_Puertolas?= <jose@example.org>",
  19. "To: Rob <rob@example.com>",
  20. "Cc: =?utf-8?B?Sm9zw6k=?= Dos <dos@example.org>",
  21. "Reply-To: list@example.org",
  22. "Subject: =?UTF-8?B?SGVsbG8g?=",
  23. " =?UTF-8?B?d29ybGQ=?=",
  24. "Message-ID: <orig-id@example.org>",
  25. "In-Reply-To: <parent@example.org>",
  26. "References: <root@example.org>",
  27. "\t<parent@example.org>",
  28. "MIME-Version: 1.0",
  29. "",
  30. "Body text that must not be parsed as a header",
  31. "X-Not-A-Header: in the body",
  32. ].join("\r\n");
  33. describe("parseHeaderBlock", () => {
  34. const p = parseHeaderBlock(BLOCK);
  35. it("stops at the first blank line so body text is never read as a header", () => {
  36. expect(p.headers.some((h) => h.name === "X-Not-A-Header")).toBe(false);
  37. expect(p.raw.endsWith("MIME-Version: 1.0")).toBe(true);
  38. });
  39. it("unfolds continuation lines and keeps every header in wire order", () => {
  40. expect(p.headers[0]).toEqual({
  41. name: "Received",
  42. value:
  43. "from mx2.example.net (mx2.example.net [10.0.0.2]) by imap.example.com with ESMTPS id abc123; Wed, 03 Jun 2020 14:05:00 +0000",
  44. });
  45. expect(p.headers.map((h) => h.name).slice(0, 4)).toEqual([
  46. "Received",
  47. "Received",
  48. "Date",
  49. "From",
  50. ]);
  51. });
  52. it("keeps every Received hop, last hop first", () => {
  53. expect(p.received).toHaveLength(2);
  54. expect(p.received[0]).toMatch(/^from mx2\.example\.net/);
  55. expect(p.received[1]).toMatch(/^from sender\.example\.org/);
  56. });
  57. it("sources `date` from the Date: header, tolerating a trailing zone comment", () => {
  58. expect(p.dateHeader).toBe("Wed, 3 Jun 2020 16:04:55 +0200 (CEST)");
  59. expect(p.date).toBe("2020-06-03T14:04:55.000Z");
  60. });
  61. it("decodes RFC 2047 words in the display fields and joins adjacent words", () => {
  62. expect(p.from).toBe("José Puertolas <jose@example.org>");
  63. expect(p.cc).toBe("José Dos <dos@example.org>");
  64. expect(p.subject).toBe("Hello world");
  65. expect(p.replyTo).toBe("list@example.org");
  66. expect(p.to).toBe("Rob <rob@example.com>");
  67. });
  68. it("leaves the raw header values undecoded", () => {
  69. expect(p.headers.find((h) => h.name === "Subject")?.value).toBe(
  70. "=?UTF-8?B?SGVsbG8g?= =?UTF-8?B?d29ybGQ=?="
  71. );
  72. });
  73. it("strips angle brackets from the threading ids", () => {
  74. expect(p.messageId).toBe("orig-id@example.org");
  75. expect(p.inReplyTo).toBe("parent@example.org");
  76. expect(p.references).toEqual(["root@example.org", "parent@example.org"]);
  77. });
  78. it("accepts LF-only input and a block with no body", () => {
  79. const q = parseHeaderBlock("Subject: plain\nDate: not a date\nMessage-Id: <x@y>\n");
  80. expect(q.subject).toBe("plain");
  81. expect(q.date).toBeUndefined();
  82. expect(q.dateHeader).toBe("not a date");
  83. expect(q.messageId).toBe("x@y");
  84. expect(q.references).toEqual([]);
  85. expect(q.received).toEqual([]);
  86. });
  87. it("is lenient with malformed lines instead of aborting", () => {
  88. const q = parseHeaderBlock("garbage line\nSubject: ok\n");
  89. expect(q.headers).toEqual([{ name: "Subject", value: "ok" }]);
  90. });
  91. // #226 — old Entourage/Outlook-for-Mac (~2005-2011, MIME boundary
  92. // OUTLOOK2MACxxxxxxxx) wrote Date: using the OS locale instead of RFC 5322
  93. // (e.g. Spanish "jue ago 30 13:55:12 2007" — "jue" = Thursday, "ago" =
  94. // August). The reporter's literal minimal repro turns out to already parse
  95. // correctly today (this pins that down as a regression guard); the real,
  96. // previously-unguarded gap was bare-CR line endings, below.
  97. const outlook2macRepro = [
  98. "From: Test Sender <test@example.com>",
  99. "To: 'Test Recipient'",
  100. "Date: jue ago 30 13:55:12 2007",
  101. "Subject: diferencial",
  102. "MIME-Version: 1.0",
  103. 'Content-Type: multipart/mixed; boundary="OUTLOOK2MAC8473928"',
  104. ];
  105. it.each([
  106. ["LF", "\n"],
  107. ["CRLF", "\r\n"],
  108. ])(
  109. "never drops or merges a header just because Date: is an unparseable locale string (%s)",
  110. (_label, sep) => {
  111. const q = parseHeaderBlock(outlook2macRepro.join(sep));
  112. expect(q.dateHeader).toBe("jue ago 30 13:55:12 2007");
  113. // Was `toBeUndefined()` until #229: this test's subject is header
  114. // INTEGRITY, and the undefined `date` merely recorded the then-current
  115. // limitation that `ago` (agosto) is not an English month abbreviation.
  116. // parseDateHeader now maps it, which is what the reporter asked for; the
  117. // integrity assertions below are unchanged and still the point.
  118. expect(q.date).toBe(new Date("Thu Aug 30 13:55:12 2007").toISOString());
  119. expect(q.subject).toBe("diferencial");
  120. expect(q.headers.map((h) => h.name)).toEqual([
  121. "From",
  122. "To",
  123. "Date",
  124. "Subject",
  125. "MIME-Version",
  126. "Content-Type",
  127. ]);
  128. }
  129. );
  130. it("parses bare-CR line endings the same as LF/CRLF (#226 — AppleScript's `all headers of msg` can return \\r-only text; previously this silently dropped every header)", () => {
  131. const q = parseHeaderBlock(outlook2macRepro.join("\r"));
  132. expect(q.dateHeader).toBe("jue ago 30 13:55:12 2007");
  133. expect(q.subject).toBe("diferencial");
  134. expect(q.headers).toHaveLength(6);
  135. });
  136. it("stops at the first blank line under bare-CR endings too (CRCR, not just LFLF)", () => {
  137. const q = parseHeaderBlock(
  138. [...outlook2macRepro, "", "Body text that must not be parsed as a header"].join("\r")
  139. );
  140. expect(q.headers.map((h) => h.name)).toEqual([
  141. "From",
  142. "To",
  143. "Date",
  144. "Subject",
  145. "MIME-Version",
  146. "Content-Type",
  147. ]);
  148. });
  149. it("returns an empty result for empty input", () => {
  150. const q = parseHeaderBlock("");
  151. expect(q.headers).toEqual([]);
  152. expect(q.raw).toBe("");
  153. expect(q.date).toBeUndefined();
  154. });
  155. });
  156. describe("decodeEncodedWords", () => {
  157. it("passes through text without encoded-words untouched", () => {
  158. expect(decodeEncodedWords("plain <a@b>")).toBe("plain <a@b>");
  159. });
  160. it("decodes Q encoding underscores as spaces and hex escapes", () => {
  161. expect(decodeEncodedWords("=?iso-8859-1?Q?caf=E9_au_lait?=")).toBe("café au lait");
  162. });
  163. it("falls back to UTF-8 for an unknown charset rather than throwing", () => {
  164. expect(decodeEncodedWords("=?x-unknown-cs?B?aGk=?=")).toBe("hi");
  165. });
  166. it("leaves an undecodable word in place", () => {
  167. // `?=` with no text and a bad charset label still round-trips as text.
  168. expect(decodeEncodedWords("=?utf-8?X?zzz?=")).toBe("=?utf-8?X?zzz?=");
  169. });
  170. });
  171. describe("headersStructured", () => {
  172. it("carries the backend arrival timestamp beside the Date: header", () => {
  173. const s = headersStructured(
  174. "imap:abc",
  175. parseHeaderBlock(BLOCK),
  176. new Date("2026-01-02T03:04:05Z")
  177. );
  178. expect(s.id).toBe("imap:abc");
  179. expect(s.date).toBe("2020-06-03T14:04:55.000Z");
  180. expect(s.dateReceived).toBe("2026-01-02T03:04:05.000Z");
  181. expect(s.headerCount).toBe(12);
  182. expect(s.messageId).toBe("orig-id@example.org");
  183. });
  184. it("omits dateReceived when the backend had none or it was invalid", () => {
  185. expect(headersStructured("1", parseHeaderBlock("Subject: x"))).not.toHaveProperty(
  186. "dateReceived"
  187. );
  188. expect(
  189. headersStructured("1", parseHeaderBlock("Subject: x"), new Date("garbage"))
  190. ).not.toHaveProperty("dateReceived");
  191. });
  192. });
  193. describe("isoOrUndefined", () => {
  194. it("handles Date, string, empty and invalid inputs", () => {
  195. expect(isoOrUndefined(new Date("2020-01-01T00:00:00Z"))).toBe("2020-01-01T00:00:00.000Z");
  196. expect(isoOrUndefined("2020-01-01T00:00:00Z")).toBe("2020-01-01T00:00:00.000Z");
  197. expect(isoOrUndefined("")).toBeUndefined();
  198. expect(isoOrUndefined(undefined)).toBeUndefined();
  199. expect(isoOrUndefined(new Date("nope"))).toBeUndefined();
  200. });
  201. });
  202. describe("#229 — locale month abbreviations in legacy Date: headers", () => {
  203. // Byte-exact header block supplied by @j5pu from `BODY.PEEK[HEADER]` on the
  204. // reporting mailbox (message A, id 345559). From/To/Cc masked at his request;
  205. // Date/Subject/MIME-Version/Content-Type are untouched. Legacy Entourage /
  206. // Outlook for Mac wrote the system locale's month abbreviation.
  207. const MSG_A =
  208. "From: XXXX XXXXXX XXXXX XXXXX <xxxxx@xxxxx.net>\r\n" +
  209. "To: 'XXXXX XXXXX XXXXXXX XXXXXXXX'\r\n" +
  210. "Cc: 'XXXXXXX XXXXXXXXX, XXXXX'\r\n" +
  211. "Date: jue ago 30 13:55:12 2007\r\n" +
  212. "Subject: diferencial\r\n" +
  213. "MIME-Version: 1.0\r\n" +
  214. 'Content-Type: multipart/mixed; boundary="OUTLOOK2MAC8473928"\r\n\r\n';
  215. it("parses a Spanish-locale Date: header that Date.parse rejects", () => {
  216. // `new Date("jue ago 30 13:55:12 2007")` is NaN — `ago` is agosto, not Aug.
  217. expect(Number.isNaN(new Date("jue ago 30 13:55:12 2007").getTime())).toBe(true);
  218. const h = parseHeaderBlock(MSG_A);
  219. expect(h.date).toBe(new Date("Thu Aug 30 13:55:12 2007").toISOString());
  220. expect(h.dateHeader).toBe("jue ago 30 13:55:12 2007");
  221. });
  222. it("covers the months that silently worked and the ones that did not", () => {
  223. // ⚠️ The bug was PARTIAL: Spanish `oct` == English `Oct`, so a spot check on
  224. // an October message reports the mailbox healthy. These four did not.
  225. for (const [abbr, month] of [
  226. ["ene", 0],
  227. ["abr", 3],
  228. ["ago", 7],
  229. ["dic", 11],
  230. ] as [string, number][]) {
  231. const h = parseHeaderBlock(`Date: jue ${abbr} 30 13:55:12 2007\r\nSubject: s\r\n\r\n`);
  232. expect(h.date, `${abbr} should parse`).toBeDefined();
  233. expect(new Date(h.date!).getMonth(), `${abbr} -> month`).toBe(month);
  234. }
  235. });
  236. it("still returns undefined for a genuinely unusable date", () => {
  237. const h = parseHeaderBlock("Date: not a date at all\r\nSubject: s\r\n\r\n");
  238. expect(h.date).toBeUndefined();
  239. expect(h.dateHeader).toBe("not a date at all"); // verbatim, still visible
  240. });
  241. });
  242. describe("#234 — Mail.app hands back `all headers` with the next header fused onto Date:", () => {
  243. // Byte-exact (From/To/Cc masked) output of Mail's own `all headers of msg` for
  244. // @j5pu's message A, captured in Script Editor with no connector in the loop and
  245. // posted as base64 in #234. Bare LF, no CR, no folding: the Date: VALUE never
  246. // arrives at all, and Mail pulled the Subject: line up onto the Date: name.
  247. const FUSED_B64 =
  248. "RnJvbTogeHh4eHggeHh4eHh4eCB4eHh4eHh4eHh4IHh4eHh4eHh4eHggPHh4eHh4eHh4eEB4eHh4" +
    • Dismissed after review: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
    • Line 276 on GitHub
  249. "eC54eHg+ClRvOiAneHh4eHggeHh4eHggeHh4eHh4eCB4eHh4eHh4eCcKQ2M6ICd4eHh4eHggeHh4" +
  250. "eHh4eHh4LCB4eHh4eCcKRGF0ZTogU3ViamVjdDogZGlmZXJlbmNpYWwKTWltZS1WZXJzaW9uOiAx" +
  251. "LjAKQ29udGVudC1UeXBlOiBtdWx0aXBhcnQvbWl4ZWQ7IGJvdW5kYXJ5PSJPVVRMT09LMk1BQzg0" +
  252. "NzM5MjgiCgo=";
  253. const FUSED = Buffer.from(FUSED_B64, "base64").toString("utf8");
  254. it("the fixture really is the fused block (guards against a mangled fixture)", () => {
  255. expect(FUSED).toContain("\nDate: Subject: diferencial\nMime-Version: 1.0\n");
  256. expect(FUSED).not.toContain("\r");
  257. });
  258. it("splits the fused line back apart and reports the date as ABSENT, not a Subject string", () => {
  259. const h = parseHeaderBlock(FUSED);
  260. expect(h.dateHeader).toBeUndefined();
  261. expect(h.date).toBeUndefined();
  262. expect(h.subject).toBe("diferencial");
  263. expect(h.headers.map((x) => x.name)).toEqual([
  264. "From",
  265. "To",
  266. "Cc",
  267. "Date",
  268. "Subject",
  269. "Mime-Version",
  270. "Content-Type",
  271. ]);
  272. expect(h.headers.find((x) => x.name === "Date")?.value).toBe("");
  273. expect(h.warnings?.join(" ")).toMatch(/Date:.*Subject:/);
  274. // The forensic record is never rewritten.
  275. expect(h.raw).toContain("Date: Subject: diferencial");
  276. });
  277. it("leaves colon-bearing values alone: a real Date with 13:55:12 and a Subject of `Re: foo: bar`", () => {
  278. const h = parseHeaderBlock(
  279. "Date: Thu, 30 Aug 2007 13:55:12 +0200\nSubject: Re: foo: bar\nFrom: a <a@b.c>\n\n"
  280. );
  281. expect(h.dateHeader).toBe("Thu, 30 Aug 2007 13:55:12 +0200");
  282. expect(h.date).toBe("2007-08-30T11:55:12.000Z");
  283. expect(h.subject).toBe("Re: foo: bar");
  284. expect(h.headers).toHaveLength(3);
  285. expect(h.warnings).toBeUndefined();
  286. });
  287. it("does not split a Date value whose leading word is not a header name", () => {
  288. const h = parseHeaderBlock("Date: Note: unparseable\nSubject: s\n\n");
  289. expect(h.dateHeader).toBe("Note: unparseable");
  290. expect(h.headers).toHaveLength(2);
  291. expect(h.warnings).toBeUndefined();
  292. });
  293. it("only repairs Date: — a Subject whose text starts with a header name is left intact", () => {
  294. const h = parseHeaderBlock(
  295. "Date: Thu, 30 Aug 2007 13:55:12 +0200\nSubject: From: the desk of X\n\n"
  296. );
  297. expect(h.subject).toBe("From: the desk of X");
  298. expect(h.headers).toHaveLength(2);
  299. expect(h.warnings).toBeUndefined();
  300. });
  301. it("headersStructured names the backend and carries the repair warning (self-diagnosing)", () => {
  302. const s = headersStructured("345559", parseHeaderBlock(FUSED), undefined, "applescript");
  303. expect(s.backend).toBe("applescript");
  304. expect(s).not.toHaveProperty("dateHeader");
  305. expect(s).not.toHaveProperty("date");
  306. expect(s.subject).toBe("diferencial");
  307. expect(Array.isArray(s.warnings)).toBe(true);
  308. const clean = headersStructured(
  309. "imap:x",
  310. parseHeaderBlock("Subject: s\n\n"),
  311. undefined,
  312. "imap"
  313. );
  314. expect(clean.backend).toBe("imap");
  315. expect(clean).not.toHaveProperty("warnings");
  316. });
  317. });
  318. describe("#234 §2b — plausibleDateSent: a send time after arrival is invented, not skewed", () => {
  319. const RECEIVED = new Date("2014-01-14T12:53:59.000Z");
  320. const DAY = 24 * 60 * 60 * 1000;
  321. it("drops the reporter's decade-scale inversion (Mail's date sent 2024 vs arrival 2014)", () => {
  322. expect(plausibleDateSent(new Date("2024-08-24T00:26:38.000Z"), RECEIVED)).toBeUndefined();
  323. });
  324. it("keeps ordinary sender clock skew — hours ahead of arrival is normal", () => {
  325. const skewed = new Date(RECEIVED.getTime() + 9 * 60 * 60 * 1000);
  326. expect(plausibleDateSent(skewed, RECEIVED)).toEqual(skewed);
  327. });
  328. it("boundary: exactly the tolerance is kept, one second past it is dropped", () => {
  329. expect(MAX_SENT_AFTER_RECEIVED_MS).toBe(7 * DAY);
  330. const atLimit = new Date(RECEIVED.getTime() + MAX_SENT_AFTER_RECEIVED_MS);
  331. const past = new Date(RECEIVED.getTime() + MAX_SENT_AFTER_RECEIVED_MS + 1000);
  332. expect(plausibleDateSent(atLimit, RECEIVED)).toEqual(atLimit);
  333. expect(plausibleDateSent(past, RECEIVED)).toBeUndefined();
  334. });
  335. it("keeps a send time with no arrival to compare against, and drops an invalid one", () => {
  336. const sent = new Date("2007-08-30T11:55:12.000Z");
  337. expect(plausibleDateSent(sent, undefined)).toEqual(sent);
  338. expect(plausibleDateSent(sent, new Date(NaN))).toEqual(sent);
  339. expect(plausibleDateSent(new Date(NaN), RECEIVED)).toBeUndefined();
  340. expect(plausibleDateSent(undefined, RECEIVED)).toBeUndefined();
  341. });
  342. });
  343. describe("#234 §4 — decodeHeaderBytes: unencoded 8-bit header bytes", () => {
  344. it("decodes a raw latin-1 display name as windows-1252 instead of destroying it", () => {
  345. const bytes = Buffer.from(
  346. 'From: "Jos\xe9 Pu\xf1ez" <j@example.org>\r\nSubject: s\r\n',
  347. "latin1"
  348. );
  349. const text = decodeHeaderBytes(bytes);
  350. expect(text).toContain('From: "José Puñez" <j@example.org>');
  351. expect(text).not.toContain("\ufffd");
  352. });
  353. it("leaves valid UTF-8 lines as UTF-8, deciding per line", () => {
  354. const bytes = Buffer.concat([
  355. Buffer.from("Subject: Jos\u00e9 (utf-8)\r\n", "utf8"),
  356. Buffer.from("From: Pu\xf1ez <p@example.org>\r\n", "latin1"),
  357. ]);
  358. const h = parseHeaderBlock(decodeHeaderBytes(bytes));
  359. expect(h.subject).toBe("José (utf-8)");
  360. expect(h.from).toBe("Puñez <p@example.org>");
  361. });
  362. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.