README
¶
mail-app-cli
A command line for macOS Mail.app. On a terminal it prints tables; in a pipe it prints a JSON envelope. Agents get the same commands, an exit-code table, and an embedded skill. All names, message IDs, addresses, mailboxes, and message content in the examples are fictional.
Terminal UI
mail-app-cli tui # all inboxes
mail-app-cli tui -a "Example Account" # one account's INBOX
mail-app-cli tui -a "Example Account" -m "Example Receipts" --message 100001
A three-pane client: mailboxes on the left, the message list in the middle, and the open message on the right (the reader takes the whole width on terminals narrower than 140 columns). Lists come from the Envelope Index, so switching mailboxes is quick; complete cached bodies and attachments come from local MIME files. Actions use typed native Apple Events, with a spinner in the header while a call is queued.

| Key | Does |
|---|---|
j k g G pgup pgdn |
move |
enter |
open the message; n p step to the next or previous one while reading |
space |
select; actions then apply to the selection |
e # m |
archive, trash (asks first), move (mailbox picker with filtering) |
u ! |
toggle read, toggle flag |
/ |
search the account (or all accounts from All inboxes); esc leaves the results |
c r R f |
compose, reply, reply all, forward; ctrl+s sends, ctrl+d saves a draft, esc discards |
1..9 |
jump to a mailbox in the sidebar |
tab |
cycle sidebar, list, reader |
ctrl+r |
refresh mailboxes and the list |
? |
hide or show the key bar |
q |
quit; ctrl+c twice also quits |
Actions apply on screen right away and the list refreshes from the index two seconds after Mail.app confirms. Because Mail.app renumbers a message when it moves, there is no undo; use move from the destination mailbox instead. NO_COLOR turns color off, and the TUI uses the terminal's own 16 ANSI colors, so it follows your theme.
Features
- Inbox, unread, search, and per-mailbox listings from Mail's local Envelope Index (about 0.1s)
- Read, mark, flag, archive, delete, and move by message ID, one or many, with
--dry-runon every mutation - Extract HTML links, plain-text URLs, and unsubscribe headers without opening destinations
- Bulk operations by query, sender, or domain with receipts, chunking, verification, and report files
- Drafts, sending with attachments and signatures, rules, smart mailboxes, threads, signatures, VIP mail
- Export messages and attachments; validate exported JSON
--json,--quiet,--jq,--ids-only,--count,--plain;NO_COLORrespected- Typed errors with a fixed exit-code table and a
hint - A default account and mailbox from a config file, env, or the only account Mail.app has
doctor,commands --json,--agent --help,skill installfor agentstui, an interactive three-pane client for triage, reading, and replying
Install
curl -fsSL https://raw.githubusercontent.com/0xSMW/mail.app-cli/master/install.sh | sh
Or with Go 1.25 or newer and Xcode Command Line Tools:
CGO_ENABLED=1 go install github.com/0xSMW/mail.app-cli/v3/cmd/mail-app-cli@latest
The named command installs mail-app-cli into GOBIN (or $(go env GOPATH)/bin). The legacy module-root install remains supported but produces mail.app-cli with a dot.
Grant Full Disk Access to the app that runs mail-app-cli (Terminal, iTerm, your editor, your agent host) so it can read Mail's Envelope Index. Without it, reads fall back to Mail.app automation and cross-mailbox search is refused. mail-app-cli doctor tells you which is the case.
Links and unsubscribe discovery in 3.1.0
Screenshots with fictional mail are available for the human CLI, agent output, TUI, and unsubscribe discovery.
Find unsubscribe opportunities in one message or across entire local folders:
mail-app-cli unsubscribe show 100001 --json
mail-app-cli unsubscribe scan INBOX -a "Example Account" --json
mail-app-cli unsubscribe scan INBOX Archive -a "Example Account" --checkpoint /private/discovery.json --json
unsubscribe scan inspects every enumerated message's local headers and supported
body alternatives. Results group by mailing-list identity when List-Id is
available; sender-based fallback groups are explicitly provisional. Exact
destinations are deduplicated with their evidence retained. Groups include the
newest representative, every observed message and folder membership, and controls
found only in older messages. Identical RFC Message-ID copies count once per
group. Varying destinations are reported without visiting them or claiming they
are still valid.
The scan follows all mailbox pages within its time budget. --page-size changes
pagination, not the requested scope. Use --since to explicitly restrict receipt
dates, or --all-accounts to scan the named folders in every enabled account.
Coverage is based on sequential observations, not an atomic mailbox snapshot.
Discovery always saves a private checkpoint and reports its path. Resume by
repeating the original accounts, folders, and date filter with --checkpoint;
page size and time budget may change. For a bounded invocation, --max-pages 1
processes one new page before saving. Pending extraction is saved before the scan
advances, so interrupted work can be resumed. A completed checkpoint replays its
stored observations; --restart-checkpoint starts a fresh traversal. After local
message files become available, --retry-incomplete reinspects earlier partial
or unavailable messages and continues pending work.
complete: true requires exhausted folders, no pending messages, and complete
local extraction for every observed message. Otherwise the command exits 5 while
retaining discovered groups, per-folder coverage, and extraction exceptions.
Finding an unsubscribe header does not bypass body inspection or certify complete
discovery. Missing local files are reported without asking Mail to render or
download them. unsubscribe show uses the same local-only extraction policy.
These commands never open URLs, fetch remote content, send mail, or unsubscribe.
General link discovery remains available:
mail-app-cli links 100001 --json
mail-app-cli links 100001 --unsubscribe --plain
mail-app-cli show 100001 --links
mail-app-cli links 100001 --unsubscribe --jq '.data.links[] | {text, url, source, kind}'
links reads the message's local MIME file and lists destinations without opening
or fetching them. It does not send mail or unsubscribe. If the local file is
missing, it requests headers from Mail without asking Mail to render the body.
Partial files and header-only fallback retain recovered destinations, report
linkStatus.complete: false, and exit 5. An empty result from an incomplete
source does not establish that the message has no links.
Full show and messages read JSON results include links, linkStatus, and
unsubscribe alongside the existing body text. Each link records its exact
url, label in text, source (html, plain, or header), mimePart,
selected, kind, and openable. Links from alternate MIME renderings remain
distinguishable. Relative destinations are resolved when the HTML supplies a
usable base URL; unresolved or unsupported destinations have openable: false.
Body classification identifies unsubscribe and preferences candidates; it does
not establish what visiting a page will do.
Human show output includes unsubscribe and preferences destinations. Add
--links to print all labels and full URLs, or use links --unsubscribe to
retrieve only unsubscribe and preferences candidates. JSON always includes the
structured inventory independently of the human-output flag.
unsubscribe preserves List-Unsubscribe and List-Unsubscribe-Post header
values and reports header availability. Header destinations also appear in
links. oneClickAdvertised records the sender's declaration; it does not verify
DKIM or authorize a POST. Personalized query strings are preserved, so treat
the output with the same privacy as the message itself.
Native transport in 3.0.0
On macOS with cgo, the CLI sends typed Apple Events directly to Mail. Local lists use an embedded read-only SQLite connection, and complete cached MIME files supply bodies, recipients, and attachment bytes. Mail remains responsible for message changes, composition, and synchronization. Gmail archive uses Mail's Archive action with Accessibility access for the app running the CLI.
Use --backend legacy or MAIL_APP_CLI_BACKEND=legacy to select the scripting compatibility backend explicitly. --backend native requires the compiled native transport; --backend auto selects native when available. Builds made with CGO_ENABLED=0 select legacy automatically. A native operation that fails does not replay through the legacy backend. doctor reports the selected backend.
Native replies and forwards are available in the TUI and from send or drafts create:
mail-app-cli send -a "Example Account" -m INBOX --reply-to 100001 \
--to recipient@example.test --subject "Re: Example" --body "Complete reply body"
mail-app-cli drafts create -a "Example Account" -m INBOX --forward-of 100001 \
--to recipient@example.test --subject "Fwd: Example" --body-file ./forward.txt
The body, subject, and recipients are the complete outgoing content. Add --reply-all with --reply-to to create Mail's reply-all relationship. These flags require native mode and an explicit mailbox. Sending a stored draft preserves the existing MIME checks; unsupported rich drafts remain available for editing in Mail.
Exchange accounts in 3.0.0
Use an Exchange account already connected to Mail.app with the same commands as other accounts:
mail-app-cli search "quarterly report" -a "Work Exchange" --limit 50
mail-app-cli attachments list 100001 -a "Work Exchange" -m Inbox
mail-app-cli archive 100001 -a "Work Exchange" -m Inbox --verify
mail-app-cli drafts create -a "Work Exchange" --to colleague@example.test \
--subject "Review" --body-file review.txt --attach report.pdf
Search includes Exchange Inbox and other non-empty mailboxes, recognizes Mail's Exchange mailbox URLs, and treats Inbox and INBOX consistently. Incomplete mailbox searches return an error unless --allow-partial is requested; partial results identify the mailboxes that could not be read.
Moves and archive verification follow the RFC Message-ID when Exchange changes the local ID or stored size. The account, source and destination, sender, subject, and sent time remain checked; ambiguous matches stay unverified. Attachment lookup accepts canonically equivalent Unicode filenames. Saved draft attachment reads use the selected account's special Drafts mailbox even before its local index catches up.
Sending and draft updates accept recognized plain content stored inside Mail's generated HTML wrapper when text and attachment preservation can be proved. Rich formatting, unsupported inline content, signing, encryption, and reply-header reconstruction remain guarded; use Mail to send drafts outside the supported forms. After acknowledged submission, the CLI closes only its unchanged outgoing composition and removes only the unchanged stored draft. An uncertain submission is never automatically retried.
Quick start
mail-app-cli doctor # Mail.app reachable? index readable?
mail-app-cli accounts list
mail-app-cli config set account "Example Account" # optional; with one account it is picked for you
mail-app-cli inbox # newest 25 across enabled accounts
mail-app-cli unread
mail-app-cli show 100001 # body included; mailbox found for you
mail-app-cli seen 100001 100002
mail-app-cli flag 100001
mail-app-cli archive 100001 --dry-run
mail-app-cli archive 100001
mail-app-cli move 100001 --to "Example Receipts"
mail-app-cli search "sample invoice" --limit 20
mail-app-cli send -t recipient@example.test -s "Hello" --body "Hi" --dry-run

Every command has --help. mail-app-cli help output, help exit-codes, help environment, and help agents cover the contract.
Efficient serial triage
Read metadata across explicit mailboxes, fetch only the bodies you need, then mark and move each selected message in one batch:
mail-app-cli messages scan INBOX 'All Mail' Spam -a "Example Account" --since 2026-01-15 --limit 200 --json
mail-app-cli messages scan INBOX 'All Mail' Trash -a "Example Account" --query 'sample invoice' --json
mail-app-cli messages read 100001 100002 -a "Example Account" --timeout 10s --budget 45s --json
mail-app-cli messages batch archive 100001 100002 --mark-read --verify --dry-run --json
mail-app-cli messages batch archive 100001 100002 --mark-read --verify --json
scan always reads live state, returning messages with their observed
mailboxes and a coverage entry for every requested scope. A failed mailbox
or a mailbox with more matches than --limit sets complete:false and exits 5.
--limit 0 removes the limit. An empty query lists messages. These are
sequential observations, not an atomic snapshot; rerun after mutations.
Scan coverage requires the Envelope Index; an unavailable index or unresolved
mailbox is reported as incomplete rather than silently using a limited fallback.
Each coverage entry reports exhausted and remaining. While the result has a
nextCursor, repeat the same arguments with --cursor to read the next page:
mail-app-cli messages scan 'All Mail' -a "Example Account" --limit 5000 --json
mail-app-cli messages scan 'All Mail' -a "Example Account" --limit 5000 --cursor "$NEXT_CURSOR" --json
Pages run newest first. The traversal is finished when a result has no
nextCursor. A cursor skips mailboxes that are already exhausted and retries a
mailbox that failed. It works only with the mailboxes and filters it was issued
for, though --limit may change between pages. Mail that arrives after the
first page is not part of the traversal.
--since filters receipt time, not last-modified time. It cannot find an older
message whose read state or labels changed, so check those with --unread or a
full traversal.
read and show take the body from the message file Mail.app keeps on disk
and ask Mail.app only for metadata. Asking Mail.app to render a body is slow,
and some messages stall it for every later request. contentSource is disk
or mail. A message with no readable file falls back to Mail.app. The disk
text follows Mail.app's rendering: the HTML part when there is one, without
display:none elements, with list markers, and without > reply markers. It
leaves out the placeholder character Mail.app inserts for each inline image,
and it can differ in spacing where a stylesheet changes the layout.
--body-source mail makes Mail.app render the body as before.
read times each phase of a body read in diagnostics. When a read times out,
pending names the operation Mail.app had not answered and lastCompleted the
one before it:
{"id": "100001", "account": "Example Account", "mailbox": "INBOX",
"error": "jxa timed out after 10s during content (9.8s in phase); last completed lookup_by_id",
"diagnostics": {"phases": [{"name": "disk_body", "elapsedMs": 6, "note": "unavailable: no message file on disk"}, {"name": "resolve_account", "elapsedMs": 41}, {"name": "resolve_mailbox", "elapsedMs": 38}, {"name": "lookup_by_id", "elapsedMs": 2}],
"lastCompleted": "lookup_by_id", "pending": "content", "pendingMs": 9829}}
The phases are disk_body, resolve_account, resolve_mailbox,
lookup_by_id, enumerate_ids (only when the direct lookup misses), content
(only when Mail.app renders the body), recipients, and metadata. message not found now means Mail.app answered and the mailbox
does not hold the ID. A Mail.app error is reported with its phase.
read returns one result per selected ID. A missing body or timeout sets
complete:false and exits 5 while retaining successful reads. Each message has
its own timeout within an overall budget. Failed IDs are not retried automatically.
The existing single-message show output is unchanged apart from an optional
contentError when Mail cannot provide a body.
Batch mark, flag, delete, and move reuse a serial bridge in chunks of at most 25
messages. Receipts remain durable between every message phase. Mark/flag
verification stops polling each ID when its requested state is observed;
delete and Gmail archive retain their settling checks. Verified Gmail archives
observe local membership across a 3.85-second default window after an account-scoped
IMAP synchronization request. Source and destination share one indexed snapshot
per observation; --settle 10s requests a longer window. --mark-read marks the
source before relocation; still check destination read status and visible copies
when your workflow requires them.
Output
On a terminal:
$ mail-app-cli inbox --limit 3
ID DATE FROM SUBJECT LOCATION
100003 Jan 15 13:50 Example Hosting Sample maintenance notice Example Account/INBOX
100002 Jan 15 12:40 Example Billing Sample invoice Example Account/INBOX
100001 Jan 15 06:48 • Example Reports Your sample report is ready Example Account/INBOX
• is unread, ⚑ is flagged.
Piped, or with --json:
{
"ok": true,
"schemaVersion": 1,
"data": [
{"id": "100003", "subject": "Sample maintenance notice", "sender": "Example Hosting <updates@example.test>",
"dateReceived": "2026-01-15T06:50:19Z", "read": true, "flagged": false, "mailbox": "INBOX", "account": "Example Account", ...}
],
"summary": "3 messages in inbox",
"meta": {"command": "inbox", "count": 3, "durationMs": 131, "view": "inbox"}
}
Errors go to stderr with a code and a hint:
{"ok": false, "schemaVersion": 1, "error": "message not found: 0", "code": "not_found", "exitCode": 2, "hint": "..."}
| Flag | Effect |
|---|---|
--json |
envelope even on a terminal |
--plain |
table even in a pipe |
--quiet, -q |
bare data, no envelope |
--ids-only |
one ID per line from inbox/unread, search, account, message, draft, thread, smart-query, or recent-search lists; attachments do not support it |
--count |
just the number of items |
--jq EXPR |
on read commands and export messages to stdout, run a jq expression over the envelope (over data with --quiet); strings print raw. Commands that change state, including file exports, reject it. |
--no-color |
no ANSI; NO_COLOR=1 does the same |
Set a default with config set output json or MAIL_APP_CLI_OUTPUT=json.
jq examples
mail-app-cli inbox --jq '.data[] | select(.read == false) | .id'
mail-app-cli mailboxes list --jq '[.data[].unreadCount] | add'
mail-app-cli mailboxes list --jq '.data[] | select(.unreadCount > 0) | "\(.account)/\(.name): \(.unreadCount)"'
mail-app-cli search "important" --jq '.data[] | [.account, .mailbox, .subject, .sender] | @csv'
mail-app-cli attachments list 100002 --jq '.data[] | select(.fileSize > 1048576) | .name'
Or pipe to a real jq: mail-app-cli inbox | jq '.data[].subject'.
Exit codes
| Exit | Code | When |
|---|---|---|
| 0 | success | |
| 1 | usage |
bad flags or arguments, missing account, refused combination |
| 2 | not_found |
message, account, mailbox, rule, draft, signature, attachment |
| 3 | unavailable |
Mail.app missing, automation denied, index unreadable |
| 4 | timeout |
a Mail.app call or its queue wait ran out of time |
| 5 | partial |
cross-mailbox search incomplete without --allow-partial |
| 6 | mutation_failed |
at least one requested change failed or did not verify |
| 7 | internal |
anything else |
Scope: account and mailbox
--account/-a and --mailbox/-m work on every command. Precedence is flag, then MAIL_APP_CLI_ACCOUNT/MAIL_APP_CLI_MAILBOX, then the config file, then defaults: the only enabled account, and INBOX. With several accounts and no default, account-scoped commands exit 1 and list the names.
The mailbox default applies to the commands that read one mailbox: messages list, messages batch selectors, threads, export, import, and rules apply. The unified inbox views (inbox, unread, messages inbox, and messages unread) respect the resolved scope: an account from --account, MAIL_APP_CLI_ACCOUNT, or config limits the view to that account's INBOX; a mailbox from --mailbox, MAIL_APP_CLI_MAILBOX, or config limits it to that mailbox. A mailbox scope needs an account, so the CLI uses the only enabled account when there is one or asks you to choose when there are several. With no configured account or mailbox, these views merge INBOX across enabled accounts. search and sync only narrow to a mailbox when -m is on the command line, and ID-driven verbs never use the default to guess where a message is.
mail-app-cli config set account "Example Account"
mail-app-cli config show
KEY VALUE SOURCE
account Example Account config
mailbox INBOX default
output auto default
send.enabled true default
Message IDs are numeric and global. show, seen, unseen, flag, unflag, archive, delete, move, and attachments look the mailbox up in the Envelope Index, so -a and -m are only needed to override. Pass -m when the index has not seen a message yet. On Gmail, archive acts from INBOX when the message carries that label and from All Mail otherwise (reported as skipped, exit 0), so it never strips a user label; move and delete act from a user label when the message has one.
After archive, delete, or move, Mail.app gives the message a new ID in the destination mailbox. The receipt reports the ID you passed; find the message again with search or recent search before touching it a second time.
Gmail labels
Mail.app's automation interface exposes a message's mailbox, read state, flags, and junk state. It does not expose Gmail labels or Important. archive and move change mailbox membership, so they cannot remove one label from a message and leave it in place. The labels commands call the Gmail API for that.
The labels adapter uses its own OAuth credentials, stored in macOS Keychain. Signing in to Google in Mail.app does not authorize it. Connect each account once, then check the credentials before you rely on them:
mail-app-cli labels auth connect -a "Example Account" --client-secret /private/path/client-secret.json
mail-app-cli labels auth status -a "Example Account" --json
mail-app-cli labels show 12345 -a "Example Account" --json
mail-app-cli labels remove 12345 12346 12347 -a "Example Account" --label IMPORTANT --dry-run --json
mail-app-cli labels remove 12345 12346 12347 -a "Example Account" --label IMPORTANT --json
show, add, and remove accept several message IDs from one Mail.app account. Each message gets its own receipt and a fresh provider read to verify the change, and the run stops at the first failure. The CLI does not create, rename, or delete label definitions. Setup, receipts, and reconciliation are in docs/gmail-labels.md.
Mutations
Disable sending
Sending is enabled by default. To keep reading and managing drafts while blocking
email sending, set a persistent restriction or pass the global --no-send flag:
mail-app-cli config set send.enabled false
mail-app-cli config show
mail-app-cli --no-send tui
mail-app-cli --no-send drafts create -a "Example Account" --to recipient@example.test --subject "For review" --body "Draft text"
The setting is stored as {"send":{"enabled":false}} in
~/.config/mail-app-cli/config.json (or the configured config path). config show
reports its effective value and source. --no-send applies to one invocation and
can appear before or after subcommands; --no-send=false cannot override a stored
restriction. There is no environment variable that overrides this setting.
When disabled, send (including reply, reply-all, and forward) and drafts send
exit with status 1 (usage) and "email sending is disabled" before contacting
Mail. The TUI reports the same error and keeps the composed text available for
saving as a draft. Draft creation, listing, reading, updating, deletion, and
--dry-run previews remain available on both mail backends.
Restore the default with mail-app-cli config unset send.enabled, or explicitly
enable sending with mail-app-cli config set send.enabled true. This controls
sending through mail-app-cli; it does not change Mail.app's own Send button.
Mutation receipts
Every message mutation (seen, unseen, flag, unflag, archive, delete, move, the messages * spellings, messages batch, and threads archive) returns the same receipt and accepts --dry-run and --verify. Other mutations (send, drafts *, rules *) accept --dry-run and return their own shape.
$ mail-app-cli archive 100001 100002 --dry-run
Dry run: would have archived 2 messages
ID STATUS LOCATION DETAIL
100001 dry-run Example Account/INBOX Your sample report is ready
100002 dry-run Example Account/INBOX Sample invoice
{"action": "archive", "dryRun": false, "matched": 2, "attempted": 2, "succeeded": 2, "failed": 0,
"items": [{"id": "100001", "account": "Example Account", "sourceMailbox": "INBOX", "targetMailbox": "All Mail", "status": "succeeded"}]}
--verify re-reads each message afterwards and records verifyStatus. Mutation counts remain separate from verification: a move accepted by Mail.app can be succeeded while its destination is applied_destination_unverified. The receipt records unverified, returns ok: false with code: "mutation_failed", and exits 6 so callers know the requested proof is incomplete. For an archive, move, or verified delete, observed reports sourcePresent, destinationPresent, and destinationRead separately, found by sender, subject, sent date, and size instead of the old local ID. When Mail.app regenerates a Gmail message in INBOX after an archive, verifyStatus is present_in_source and observed.sourceIds holds the new local ID. ok means "this command did what you asked and any requested verification completed", so check it, or check the exit code, before trusting a receipt.
Bulk selection by query, sender, or domain lives under messages batch and needs --yes for archive, delete, and move unless --dry-run is set:
mail-app-cli messages batch archive -a "Example Account" -m INBOX --sender-domain updates.example.test --limit 500 --dry-run
mail-app-cli messages batch archive -a "Example Account" -m INBOX --sender-domain updates.example.test --limit 500 --yes --chunk-size 50 --progress --verify --report-file cleanup.json
mail-app-cli search "sample alert" --ids-only | xargs mail-app-cli delete --dry-run
mail-app-cli messages batch mark --read=false 100003 100004
Batch commands stop after three identical consecutive failures within an account/mailbox. Use --max-consecutive-failures N to change the threshold or 0 to disable it. Stopped receipts distinguish not_attempted items, and requested verification still runs for successful items. --events --json streams durable JSON progress to stderr while the final JSON receipt remains on stdout. Inspect a receipt without accessing Mail using messages status <receipt-file> --json.
Deletes move to the account's actual recoverable Trash. A missing or ambiguous Trash destination, or a source already in Trash, stops that item before changes. messages batch delete <ids...> --mark-read --verify confirms stable identity in Trash, source removal, and the requested read state; source disappearance alone is insufficient. Use messages reconcile <receipt-file> to inspect an uncertain verified deletion without repeating it.
Gmail Inbox moves to All Mail, including supported archive aliases, use the same guarded Archive action as archive. To explicitly remove Important as well, use messages batch archive <ids...> --remove-important --verify. This requires existing Gmail label authorization and preflights every selected account/message before removing labels. The receipt includes separate label results and recovery paths. Without this option, archive preserves Important.
For repeatable selections across accounts, cleanup manifests record exact identities, actions, and required final mailbox memberships. Preview with messages manifest apply cleanup.json --dry-run, apply with messages manifest apply cleanup.json, and inspect fresh outcomes with messages manifest verify cleanup.json.
Selected body reads support --checkpoint <path> and --events. Repeat the same selection and body options to resume completed extraction while refreshing message metadata. Saved reads can follow a regenerated local ID when the original account and a unique RFC Message-ID match the captured sender, subject, and sent date. Changed content is read again; cached disk bodies are reused only after checking their content revision. Ambiguous or different identities remain refused. Checkpoints contain private message bodies and are written with owner-only permissions. See resumable reads for recovery details.
Sending and drafts
mail-app-cli send -a "Example Account" -t recipient@example.test -s "Hello" --body "Message" --attach ~/sample.pdf --signature "Example Account"
mail-app-cli send -t recipient@example.test -s "Hello" --body-file body.md --dry-run
mail-app-cli drafts create -a "Example Account" --to recipient@example.test --subject "Review" --body-file body.md --attach ~/sample.pdf
mail-app-cli drafts list
mail-app-cli drafts update <draft-id> --subject "Updated"
mail-app-cli drafts update <draft-id> --attach ~/another.pdf
mail-app-cli drafts send <draft-id>
mail-app-cli drafts delete <draft-id> --dry-run
Draft --attach accepts one file per flag; repeat it for multiple files. Updates append new attachments and preserve existing ones when changing the subject or body. Files are checked before changes, and saved attachments are verified before a replacement draft removes the original. Mail controls delivery MIME encoding; text attachments can acquire CRLF line endings in transit. --dry-run validates paths and previews the requested files without changing Mail.
Native sends with attachments save the same composition before submission and verify the stored filenames and file bytes. Missing, changed, or incomplete attachments stop the send before submission. This also applies when sending a supported saved draft or forwarding with explicit attachments.
send and drafts create accept --from <address> to select an address configured on the account. Without it, they use the first configured address. Both validate the account and read the compose sender back before sending or saving; an unexpected sender or an address shared across accounts stops the operation. Draft updates preserve the original sender. Dry-run receipts include the account ID and selected sender, and validate the configured identity without composing a message. Sender validation does not establish which delivery route Mail will use.
Outgoing commands require Mail to acknowledge the operation. A failure returns a nonzero exit; an uncertain submission must be checked before retrying. sent and submitted indicate Mail accepted submission, not recipient delivery. Draft creation verifies the saved draft directly through Mail rather than waiting for the search index. It identifies the account’s Drafts folder through Mail’s special mailbox references, including localized and nested folders.
Sending requires Mail to expose one uniquely identified Drafts folder belonging to the selected account. The CLI saves the composition before sending and records that saved copy. After submission, it removes the copy only if it is unchanged and verifies its absence. A submitted_cleanup_pending receipt still means Mail accepted the message; check the retained draft instead of sending again.
drafts send rebuilds supported plain-text drafts and ordinary file attachments as an outgoing message, preserving the sender and To/Cc/Bcc addresses. Standard Mail signature-selection, base-URL, and attachment-preference headers are accepted only with recognized values; content preservation is still verified independently. It rejects rich text, inline content, reply-thread headers, signing/encryption, or other unsupported message semantics before submission; send those drafts in Mail. The original stays until Mail acknowledges submission and is removed only if it is unchanged. A receipt with submitted: true and cleanupPending: true means the message was submitted but the original draft remains; do not resend it.
Search
mail-app-cli search "sample project update"
mail-app-cli search "sample invoice" -a "Example Account" --since 2026-01-01 --sender-domain billing.example.test
mail-app-cli search "sample invoice" -a "Example Account" -m "All Mail"
Every term must match the subject, sender, or Mail's indexed summary. Without -m the search covers each enabled account's Inbox and its other non-empty mailboxes (or only the account named with -a). Mailboxes with unknown counts are included. Exchange and IMAP accounts use Mail's local index when available.
If a mailbox cannot be completely searched, the command exits 5. This includes reaching the automation fallback's scan budget or being unable to read a field needed to determine a match. The same rule applies with -m. --allow-partial returns observed matches as {messages, complete, searchedMailboxes, failedMailboxes}; incomplete mailbox entries include available scan counts, truncation, and read-failure details. Reaching the requested result limit alone is normal success. With --ids-only or --count, those list modifiers operate on messages. A known incomplete search is never replaced by cached success. The recent-message journal can be consulted when live search cannot start; --no-cache disables that fallback.
Other commands
mail-app-cli messages list -a "Example Account" -m INBOX --unread --since 2026-01-01 --limit 10
mail-app-cli messages sent|drafts|flagged|trash|junk
mail-app-cli attachments list 100002
mail-app-cli attachments save 100002 "sample-invoice.pdf" -o ~/Downloads/sample-invoice.pdf
mail-app-cli export messages -a "Example Account" -m INBOX --output inbox.json
mail-app-cli export attachments -a "Example Account" -m INBOX --output ./attachments
mail-app-cli import messages -a "Example Account" -m Archive --file inbox.json --dry-run
mail-app-cli threads list -a "Example Account" -m INBOX
mail-app-cli rules list
mail-app-cli rules create "Example Receipts" -a "Example Account" --from-domain billing.example.test --move-to "Example Receipts" --dry-run
mail-app-cli smart list
mail-app-cli signatures show "Example Account"
mail-app-cli messages vip
mail-app-cli recent search "sample project update"
mail-app-cli sync --wait
sync -a "Example Account" requests synchronization only for that account.
IMAP accounts (including iCloud) use Mail's explicit synchronization operation
followed by a check for new mail; other receiving accounts check for new mail. Without -a, enabled accounts
are requested individually. A completed result means Mail accepted the request.
--wait additionally observes stable local counts, which do not establish that
individual messages or server-side labels are synchronized. Use
messages reconcile receipt.json to recheck archive, move, or verified delete identities.
messages show|mark|flag|archive|delete|move are the 1.x spellings and still work; they now return receipts and accept --dry-run.
For agents
mail-app-cli skill # print the embedded SKILL.md
mail-app-cli skill install # ~/.claude/skills/mail-app-cli/SKILL.md
mail-app-cli commands --json # every command, flag, and agent note
mail-app-cli show --agent --help

help agents is the short version: always --json, check ok, read the exit code, dry-run before acting on more than a couple of messages, and never send without showing the user a --dry-run first.
Migrating from 1.x
| 1.x | 2.0 |
|---|---|
jq '.[].Subject' |
jq '.data[].subject' or --jq '.data[].subject' |
| bare array output | --quiet |
messages archive ID -a A -m M |
archive ID |
messages mark ID --read=false |
unseen ID |
| "Message archived" text | receipt JSON, or one line on a terminal |
| exit 1 for every failure | see the exit-code table |
sync --json |
sync (global --json) |
... | jq length |
... | jq '.data | length' or --count |
| stderr was a bare string | stderr is a JSON error envelope when piped, text on a terminal |
--version printed mail-app-cli version 1.3.0 |
mail-app-cli 2.0.0 |
doctor always exited 0 |
exits 3 when not healthy |
search --no-cache was accepted and ignored |
disables the recent-journal fallback |
Keys are camelCase everywhere. Lists are never null. Warnings that 1.x printed as free text on stderr are notices in the envelope.
Environment
| Variable | Purpose |
|---|---|
MAIL_APP_CLI_ACCOUNT, MAIL_APP_CLI_MAILBOX |
default scope |
MAIL_APP_CLI_OUTPUT |
auto, json, or plain |
MAIL_APP_CLI_CONFIG |
config file path (default ~/.config/mail-app-cli/config.json) |
MAIL_APP_CLI_SKILL_DIR |
where skill install writes |
MAIL_APP_CLI_SEARCH_TIMEOUT |
seconds for automation search (8) |
MAIL_APP_CLI_CONTENT_TIMEOUT |
seconds for --with-content (45) |
MAIL_APP_CLI_DISABLE_ENVELOPE_INDEX |
force Mail.app automation for reads |
NO_COLOR |
disable color |
Caches live in ~/.cache/mail-app-cli/ (accounts and mailboxes 24h, message lists 5 minutes, recent-message journal).
How it works
Native builds read Mail's Envelope Index through embedded read-only SQLite and extract complete cached bodies and attachments from local MIME files. When local data is unavailable, scoped public Apple Events read from Mail. Typed Apple Events also perform composition and changes; Gmail Inbox archive uses Mail's Archive action through public Accessibility APIs. Mail transactions are bounded and serialized across goroutines and processes. The explicit legacy backend uses JavaScript for Automation and AppleScript in bounded process groups.
Development
go build -o mail-app-cli
go vet ./... && go test ./...
UPDATE_SURFACE=1 go test ./cmd -run TestSurfaceSnapshot # after adding or removing commands or flags
docs/cli-ergonomics-plan.md explains the 2.0 design; docs/tui-plan.md covers the terminal UI that builds on it; plans/tars-real-world-reliability.md tracks mutation integrity and stable identity work.
Requirements
- macOS 15 or newer with Mail.app configured
- Go 1.25 or newer to build
This project is a hard fork of intelligrit/mail-app-cli.
Reliable repeated cleanup in 2.4
Verified archive, move, and delete capture message identity without asking Mail to render
a body. --settle extends final observation and --verify-budget bounds the
stage. Archive destinations are recorded before the move so an interrupted
operation retains the scope needed for recovery.
messages reconcile receipt.json --settle 10s --verify-budget 30s --json
rechecks saved archive/move/delete identities without repeating the operation. Receipts
report when and where the final source/destination state was observed, and
whether observation followed a synchronization request. These observations
cover Mail's local state; they do not certify server-side labels or future state.
Archiving from a Gmail Inbox to All Mail uses Mail's native Archive control.
Grant Accessibility access to the application running mail-app-cli in macOS
System Settings. The command briefly opens a separate Mail window in the
background with its preview hidden, selects and checks the individual message,
then closes that window. It does not activate Mail or restore another app's
focus afterward. If it cannot establish the exact owned window, selection, and
Archive button, the command stops before archiving. It expands conversations and
scrolls the owned message list within fixed time and traversal limits to find
the individual message. Conversation headers remain ineligible for Archive;
each selected child must pass the same exact message-identity checks. If Mail
does not expose the controls needed to reach that child safely, the command
stops. An uncertain
Archive response stops the batch; reconcile its receipt before taking further
action. All mailbox changes continue to go through Mail.
messages batch archive 12345 --mark-read --mark-read-on-skip --verify --dry-run
previews the explicit choice to mark an already-archived record read. Without
--mark-read-on-skip, archived records retain their existing state. Requested
destination read state is part of verification.
messages read 12345 --body-alternatives --json exposes independently extracted
MIME renderings. Bodies carry extraction diagnostics for images, nontext parts,
partial files and alternative selection; extraction success does not certify
that every visual or substantive detail is represented. Normal output omits
alternative texts unless requested. No referenced resources are downloaded.
messages scan INBOX Archive -a "Example Account" --limit 200 --checkpoint /absolute/private/history.json --json saves cumulative traversal state. Repeat
the command to resume; use --restart-checkpoint after completion for a fresh
traversal. Filters stay fixed while page size may change. Accumulated observations
are not a live snapshot or changed-state feed, so keep new-mail discovery and
held-identity reconciliation separate. Today aggregate counts do not establish
identity cleanup; use direct source and destination observations.
Documentation
¶
There is no documentation for this package.
Directories
¶
| Path | Synopsis |
|---|---|
|
mail-app-cli
command
|
|
|
internal
|
|
|
appleevents
Package appleevents sends typed Apple Events without compiling or executing scripts.
|
Package appleevents sends typed Apple Events without compiling or executing scripts. |
|
clierr
Package clierr defines the error contract the CLI presents to callers: a short machine code, an exit status, a message, and a hint.
|
Package clierr defines the error contract the CLI presents to callers: a short machine code, an exit status, a message, and a hint. |
|
config
Package config reads and writes the user configuration file and resolves defaults from flags, environment, or file.
|
Package config reads and writes the user configuration file and resolves defaults from flags, environment, or file. |
|
gmail
Package gmail provides a bounded Gmail metadata and label transport.
|
Package gmail provides a bounded Gmail metadata and label transport. |
|
mailax
Package mailax provides the public Accessibility operations needed to archive an individual message in an explicitly owned Mail viewer.
|
Package mailax provides the public Accessibility operations needed to archive an individual message in an explicitly owned Mail viewer. |
|
mailindex
Package mailindex observes Mail's Envelope Index without opening a writable SQLite connection.
|
Package mailindex observes Mail's Envelope Index without opening a writable SQLite connection. |
|
output
Package output is the single place the CLI writes results.
|
Package output is the single place the CLI writes results. |
|
tui
Package tui is the terminal mail client.
|
Package tui is the terminal mail client. |
|
pkg
|
|
|
Package skills embeds the agent-facing SKILL.md so the binary can print and install it without a network or a checkout.
|
Package skills embeds the agent-facing SKILL.md so the binary can print and install it without a network or a checkout. |