Skip to content

Mail / iCloud compatibility

This document covers the optional IMAP read/mutation and SMTP submission clients. Mail is independent from Calendar CalDAV and Contacts CardDAV.

Protocol Host Port Encryption Username
IMAP imap.mail.me.com 993 Required implicit verified TLS Mail address local part first, then full address fallback
SMTP submission smtp.mail.me.com 587 Mandatory verified STARTTLS Full iCloud Mail address

Both protocols use an app-specific password. The client does not support POP. Apple does not document all related behavior. Examples include IMAP capabilities, mailbox names, SPECIAL-USE mappings, MOVE, UIDPLUS, CONDSTORE, authentication details, and SMTP Sent copies. The client negotiates these properties or fails closed. It does not use fixed assumptions.

The client uses fixed socket destinations. IMAP requires exactly imap.mail.me.com:993. SMTP requires exactly smtp.mail.me.com:587. TLS uses system trust, fixed server names, and TLS 1.2 or later. The client does not enable protocol debug writers.

Each tool attempt opens a new socket. It closes the authenticated session after the operation. Selected mailboxes, IDLE connections, IMAP sessions, and SMTP sessions do not remain between calls.

IMAP uses this sequence:

fixed dial -> verified implicit TLS -> greeting -> LOGIN -> capability snapshot
-> LIST or SELECT -> bounded commands -> logout/close

The first LOGIN username is the local part of ICLOUD_MAIL_ADDRESS. The adapter tries the full address once after an explicit authentication rejection. It does not use this fallback after a network, timeout, or generic protocol error. Errors do not identify the attempted identity.

A greeting with BYE, NO, or BAD stops the attempt before LOGIN. The response code of that greeting sets the error code: for example, AUTHENTICATIONFAILED gives authentication. The result does not depend on when the server closes the connection after the greeting.

A transient Mail read can open one replacement session if the first session returned no result. Mutation and SMTP paths never retry. Cancellation closes the active connection.

LIST supplies mailbox names, hierarchy delimiters, and attributes. The server does not infer a mailbox purpose from an English display name. This rule applies to Inbox, Sent, Trash, and other purposes. list_mailboxes sends no STATUS fan-out and returns at most 200 items. It lists a mailbox only when an effective Mail capability reaches it and sets accessModes to read, mutate, and archive as applicable. A mutation-only or archive-only target is not shown as readable.

A message identity is:

(mailbox, UIDVALIDITY, UID)

search_messages returns UIDVALIDITY with each page and message. get_message and each mutation require it. After SELECT, a mismatch returns concurrent_modification. This check occurs before the client gets or changes the message. UID zero and UIDVALIDITY zero are invalid.

search_messages accepts one mailbox and optional search criteria. The criteria are TEXT, From, To, Subject, inclusive since, exclusive before, unseen, and flagged. Search strings have a 512-byte UTF-8 limit. Typed go-imap criteria send them without protocol string concatenation. Dates use YYYY-MM-DD and IMAP internal-date day granularity.

The search reads descending UID ranges in windows of at most 5,000. It starts below UIDNEXT or the exclusive before_uid. It scans at most 50,000 UID values. It never sends an unrestricted mailbox-wide search. A cursor must include the UIDVALIDITY from the previous page.

Results sort by descending UID within one UIDVALIDITY. UID order is append order, not message header-date order. The default result limit is 20. The maximum is 50. nextBeforeUid is the next exclusive cursor.

nextBeforeUid can be present on an empty page. When the scan stops at its 50,000 UID limit, the cursor is the oldest completed scan boundary plus one. That cursor reaches older matches without a new search of the same UID range. When the count or 256 KiB limit removes summaries, the cursor is the oldest returned message. No page is terminal while older searchable UID space remains. An absent cursor and scanLimitReached: false mean the scan reached UID 1.

scanLimitReached means that the search did not read older UID space. truncated means that the count or 256 KiB output limit removed summaries.

Reads use one of three FETCH projections. Each read asks for the smallest one it can use, so a MIME tree never blocks a read that does not need it.

Projection Used by FETCH items
Summary search_messages UID, flags, envelope, internal date, RFC822 size, and MODSEQ when available
Reply headers reply_message Summary items plus the header section for Message-ID, In-Reply-To, References, and Reply-To
Full message get_message Reply-header items plus extended BODYSTRUCTURE

No projection requests a snippet or a whole body section.

Read tools select mailboxes read-only and use PEEK. They must not set Seen.

get_message gets the full-message projection: metadata, BODYSTRUCTURE, and the four curated headers. It selects inline text/plain leaves without attachment or filename semantics. Then, bounded partial PEEK requests get the MIME header and body. It never gets an unbounded BODY.PEEK[].

Search and reply reads do not request BODYSTRUCTURE, so a message with a wide or deep MIME tree still appears in a bounded summary page and can still be replied to. get_message keeps the tree limits: 200 flattened parts, MIME path depth 20, and one part per attachment. A tree above a limit fails that read with payload_too_large after guardedConn applied the 4 MiB inbound session cap.

Parts of multipart/mixed are independent. The client joins each selected plain part in document order with a blank line, within max_body_bytes. When a later part does not fit, the result keeps the earlier bounded text, sets bodyOmitted, and adds a body_truncated warning.

Parts of one multipart/alternative are competing representations. The direct children of that container are the competing branches. The client skips whitespace-only representatives, keeps the first meaningful plain branch, and never appends a leaf from a competing branch.

Branch identity is separate from segment identity. A child multipart/mixed branch can hold several independent plain segments, and the client keeps every one of them in document order. In the nested layout below, “Part A” and “Part B” are both returned, and the HTML branch is suppressed.

multipart/alternative
|-- multipart/mixed
| |-- text/plain: "Part A"
| `-- text/plain: "Part B"
`-- text/html: rendering of A and B

Every multipart/alternative level counts on its own. A nested alternative inside a branch opens one more level, so its own leaves compete with each other while the enclosing mixed siblings stay independent. The client suppresses a part when any shared alternative level already selected a different branch.

multipart/alternative
|-- multipart/mixed
| |-- text/plain: "Intro text"
| `-- multipart/alternative
| |-- text/plain: "bonjour"
| `-- text/plain: "bonjour latin1 twin"
`-- text/html

The result keeps “Intro text” and the preferred inner leaf “bonjour”. The competing inner leaf “bonjour latin1 twin” is not fetched, and neither is the HTML branch.

A part that is malformed or too large adds body_decode_failed or body_too_large; the client continues with the other independent parts.

The result contains selected envelope and header metadata. It also contains decoded plain text and attachment metadata. It never contains raw MIME, raw headers, Received or authentication headers, HTML, or attachment payloads. BODYSTRUCTURE supplies attachment metadata without content retrieval. The client treats attached message/rfc822 parts and their descendants as attachments. It does not inspect them for body text.

If no plain text exists, the result has metadata with html_only or no_plain_text, unless allow_html_fallback is true. This opt-in also treats empty or whitespace-only decoded plain text as unavailable. Without this opt-in, the first meaningful plain text remains selected; when none is meaningful, the first decoded part is returned even if blank. Malformed or oversized plain parts are omitted with warnings and do not trigger fallback. The opt-in fetches only the first inline HTML part. A local converter excludes script, style, template, head, and comment content, decodes entities, and bounds nodes, depth, input bytes, and output. The result sets bodySource: "html_fallback" and reports html_truncated or html_malformed. It never fetches a link, image, style sheet, or attachment.

If wire or decoded text is too large, the client omits the body and adds a bounded warning. Unsafe decoding has the same result. The client can truncate an otherwise valid body at a valid UTF-8 boundary. This truncation keeps the result within 256 KiB. Metadata that cannot fit returns payload_too_large.

internal/mail/imapadapter isolates the beta go-imap client. Before the library creates recursive BODYSTRUCTURE values, guardedConn applies these limits:

Resource Limit
Inbound bytes per session 4 MiB
One protocol line 1 MiB
Protocol parenthesis depth 24
Protocol lists 512
Quoted protocol string 8,194 bytes

The modeled layer applies these additional limits:

Resource Limit
MIME parts / nesting 200 / 20
Curated header section 64 KiB
Selected text wire bytes 512 KiB
Decoded plain text 100 KiB default, 200 KiB maximum
Addresses / attachments 100 / 100
One metadata string 4 KiB
Serialized result 256 KiB

set_message_flags accepts exactly one add or remove operation. It also accepts one to three unique values from Seen, Flagged, and Answered. It cannot replace FLAGS, set Deleted or Recent, or create arbitrary keywords.

The session selects the mailbox for read and write. It checks UIDVALIDITY and the existence of the message. Without CONDSTORE, the adapter sends one delta-only +FLAGS.SILENT or -FLAGS.SILENT. It never sends a full replacement. The result reports conditionalUpdate: false. Then, it tries to get the resulting flags.

When the IMAP server advertises CONDSTORE, set_message_flags requires expected_modseq. The adapter then sends one UID STORE with UNCHANGEDSINCE and proves the outcome from the wire. go-imap v2 discards a tagged OK response code, so the adapter reads the tagged status of exactly the STORE it sent through its inbound protocol guard. The tag comes from that command line, so a response for another command is never evidence.

The adapter reports a conditional success only when both proofs hold:

  • The tagged OK for that command carried no MODIFIED code.
  • The server returned one FETCH for that UID with the requested flag delta and a MODSEQ.

The outcome matrix is closed:

Server response Result
Tagged OK, no MODIFIED, FETCH with the exact delta Success, conditionalUpdate: true
Tagged OK [MODIFIED <uid set>] that names this UID concurrent_modification
Tagged OK, no MODIFIED, no FETCH for this UID outcome_unknown
Tagged OK, FETCH missing, duplicated, for another UID, or without MODSEQ outcome_unknown
Tagged OK, FETCH flags that contradict the requested delta concurrent_modification
Tagged NO or BAD, unparsable status, or two STORE commands outcome_unknown

A MODSEQ increase alone never proves success: RFC 7162 section 3.1.3 requires the server to update MODSEQ after any successful guarded STORE, and a competing writer can change it too. The RFC 7162 section 3.1.3 Example 10 exchange, where an unsolicited matching FETCH arrives together with OK [MODIFIED uid], is never a success.

A CONDSTORE server never receives an unconditional delta STORE. The adapter sends no second STORE for one request and never retries a guarded STORE.

Without CONDSTORE, the adapter sends one unconditional delta STORE and fetches the final flags. If the fetched flags do not contain or omit exactly the requested delta, the result is concurrent_modification with reconciliation guidance, never a definitive success. A matching fetch reports conditionalUpdate: false, which explicitly means no atomic concurrency guarantee. An ambiguous dispatched write still returns outcome_unknown.

move_message first verifies that LIST contains exactly one selectable match for the destination. It then selects the source for read and write. It checks UIDVALIDITY and the source UID.

The destination cannot have the SPECIAL-USE \\Trash or \\Junk attribute. This check ignores attribute case. Use trash_message for intentional deletion.

  • When the server advertises MOVE, the client uses native UID MOVE.
  • Otherwise, it requires UIDPLUS. It sends UID COPY, adds Deleted to that UID, and then sends UID EXPUNGE for that UID.
  • It never uses plain EXPUNGE or mailbox-wide EXPUNGE.
  • It waits for definitive completion before the next step. It never retries or compensates automatically.

A transport ambiguity during native MOVE or COPY returns outcome_unknown. A definitive failure after COPY or Deleted returns a bounded partial_failure. An ambiguous later step returns outcome_unknown. Reconciliation identifies the mailboxes and state that the caller must inspect.

trash_message requires exactly one selectable LIST mailbox with SPECIAL-USE \Trash. It then applies the same move policy. Zero or multiple Trash targets fail closed. The tool has no permanent-delete action. It rejects a source that is already in that Trash mailbox.

The server registers SMTP send only when all send gates are active. Mail must be enabled, global read-only must be false, and configuration must request Mail send. The recipient policy must also be valid. Mail mutation is not required.

The path is:

smtp.mail.me.com:587 -> EHLO -> mandatory STARTTLS -> verified TLS -> EHLO
-> AUTH PLAIN -> MAIL FROM -> every RCPT TO -> DATA

There is no plaintext-authentication fallback. The envelope and MIME From value is exactly ICLOUD_MAIL_FROM when it is set, and ICLOUD_MAIL_ADDRESS otherwise. AUTH always uses ICLOUD_MAIL_ADDRESS; iCloud SMTP decides whether the account may send from the configured address. The configured sender must be ASCII; Unicode senders are rejected at startup. The message is UTF-8 plain text. The client generates Date and Message-ID locally. To and Cc occur in headers. Bcc occurs only in the envelope.

The client rejects HTML, attachments, raw MIME, custom headers, and display-name recipients. It also rejects groups, caller-selected From, header newlines, and NUL.

The local policy validates all To, Cc, and Bcc addresses before connection. It permits only exact configured addresses, preserving local-part case and folding only the ASCII domain. The literal complete policy * permits all addresses. Recipients must be unique, with a limit of 50.

to, cc, and bcc are each optional. The three arrays must contain at least one recipient in total. Subject has a 998-byte limit. Body has a 100 KiB limit. The complete encoded message has a 256 KiB limit. Inbound SMTP responses have a total 1 MiB limit for each session.

The client tries each RCPT command unless an ambiguous failure makes more commands unsafe. The failure can come from the protocol or transport. A definitive RCPT rejection prevents DATA. The client sends RSET when possible. Thus, it never submits an accepted subset.

Submission outcomes are:

  • accepted only after a definitive successful final DATA response.
  • rejected when at least one RCPT receives a definitive rejection. A definitive DATA rejection has the same result.
  • A structured tool error for validation, authorization, authentication, protocol, size, or availability failures before DATA. These paths include local policy, STARTTLS, AUTH, and MAIL FROM failures. The client submits no message on these paths.
  • outcome_unknown if connection loss or cancellation occurs after DATA may have reached the server and no definitive final response is available.

The client never retries SMTP. After outcome_unknown, inspect Sent and the recipients before another send.

reply_message requires Mail read and Mail send. It checks the source mailbox against mail.read resource scopes before calling the Mail service. A denied source causes no message lookup, recipient resolution, or SMTP connection. Mutation and archival mailbox scopes do not grant source read access. It reads the source by (mailbox, UIDVALIDITY, UID) and rejects a changed UIDVALIDITY before SMTP. The default mode replies to Reply-To, else From. reply_all adds To and Cc, but never Bcc. The client excludes its own address and deduplicates the final recipients.

The reply reads curated headers and envelope metadata only. It never fetches a message body part, so a large or malformed source body cannot slow or fail a reply.

The source must have a valid Message-ID. In-Reply-To is that identifier. References starts from the source References header. When that header is absent, it starts from the source In-Reply-To header, as RFC 5322 section 3.6.4 specifies. The source Message-ID is appended exactly once. A valid chain longer than 20 entries keeps the most recent 19 ancestors and the immediate parent; the client does not reject a long thread. The client rejects malformed values before SMTP. It adds Re: to the subject only when absent. It does not accept caller-supplied headers, mark the message Answered, move it, or append a Sent copy. The same recipient policy, STARTTLS, no-retry, and idempotency rules apply.

send_message accepts an optional idempotency_key. The first caller claims the key before SMTP dispatch. Identical content reuses the active or retained result and the same Message-ID. Changed content for the same key returns conflict before dispatch. The fingerprint binds the sender, recipient groups, subject, body, reply headers, and archive_sent. Omission and explicit false are equivalent. Changing the archival preference conflicts, even while the original call is active.

The cache is process-local. Pending claims never expire. A completed accepted or definitive rejected outcome is retained for 15 minutes after completion. An outcome_unknown outcome stays until process exit. Pending and uncertain outcomes are never reclaimed to make space. The cache has 128 keys. A full cache rejects a new claim with conflict before SMTP and gives non-sensitive reconciliation guidance; existing keys still return their retained results. A cancelled duplicate caller does not release the original claim. While a claim is pending or retained, a later call receives the recorded result, including outcome_unknown, and does not submit again.

After the 15-minute window, an old key is a new operation. It can submit again with identical or different content, and no conflict is guaranteed. Expiry is not proof that the earlier operation failed. Process restart clears every claim and has the same effect. The cache is not a durable or exactly-once delivery guarantee.

send_message accepts only a JSON boolean for archive_sent, default false. Strings, numbers, null, arrays, and objects fail before service or network access. True requires the separate mail.archive permission and Mail send, not Mail mutation.

After local recipient validation, IMAP discovery resolves one selectable SPECIAL-USE \Sent mailbox. Its name must be valid and allowed by the mail.archive resource scope. This preflight completes before any SMTP connection. Missing, duplicate, invalid, non-selectable, or forbidden Sent targets reject the send without SMTP access. The client never includes a forbidden mailbox name in the error or audit record.

After definitive SMTP acceptance, one APPEND uses the exact prepared message and Message-ID. It uses the preauthorized name without another LIST or replacement target. Both IMAP sessions and SMTP share the original request deadline and send concurrency budget.

The SMTP status remains accepted regardless of the separate archivalStatus:

  • stored: APPEND received definitive success. sentDestination names the authorized mailbox.
  • failed: archival failed definitively, or its connection failed before APPEND.
  • unknown: APPEND might have succeeded, but its acknowledgement is unavailable.
  • not_attempted: archival is enabled, but the caller omitted the option or selected false.

With archival disabled and no archival request, archivalStatus is omitted. SMTP rejection or ambiguity never triggers APPEND. A failed or lost APPEND acknowledgement leaves SMTP acceptance intact, with a bounded archivalError code. No failure path repeats SMTP or APPEND. Identical keyed calls return the retained combined result; changing the option cannot repair archival or trigger another send. Inspect the authorized Sent mailbox before any manual recovery of unknown archival.

sentCopyUnavailable: true means the client did not confirm a stored copy. It is omitted after stored. The provider might independently create a copy; the client does not assume this behavior. A stored copy does not prove recipient delivery.

Three explicit permission tokens control attachments. No domain switch, legacy flag, or omission grants them. Each token needs mail.read.

Token Tools Effect
mail.attachments.read get_attachment Reads one attachment part. Global read-only keeps it.
mail.attachments.send attachments on send_message and reply_message Attaches parts that are already on the server. It also needs mail.send.
mail.drafts stage_attachment, create_draft Stages new files in memory and appends a draft.

The server keeps the rule that it does not access the disk after boot. iCloud stays the only source of mail data. The server keeps no copy of a part after a call. Staged files exist only in process memory.

get_attachment takes the partId that get_message returns. The server selects the mailbox with EXAMINE and checks UIDVALIDITY. It reads BODYSTRUCTURE to confirm that the part is a leaf. A container part, message/rfc822, or an unknown part_id fails before content retrieval. The server then fetches the MIME header and the body with BODY.PEEK, so the Seen flag does not change.

The encoded part must not exceed 3 MiB. A part that BODYSTRUCTURE reports as larger fails before content retrieval. The server removes only the Content-Transfer-Encoding. It never converts the charset of the returned bytes, so size and sha256 describe the original file.

With format: "auto", the result depends on the type:

  • PNG, JPEG, GIF, and WebP up to 600 KiB return as MCP image content.
  • A larger PNG, JPEG, or GIF returns as a resized JPEG below 600 KiB. Decode starts only after a check of 12,000 pixels per edge, 25 megapixels, and 96 MiB of estimated decode memory. The estimate uses an upper bound of the bytes per pixel for the color model. An interlaced PNG also counts its pass image, and a progressive JPEG counts its coefficient buffers. The estimate does not include garbage collection delay, so the measured peak can be higher. One image decode or Word text extraction runs at a time in the process.
  • text/*, JSON, and XML return as bounded text after charset decoding. HTML uses the same converter as the HTML body fallback.
  • A Word .docx returns its paragraph text. The reader accepts at most 5,000 archive entries, 4 MiB of document XML, a compression ratio of 100, a nesting depth of 128 elements, 256 attributes for each element, and 1,000,000 XML tokens. It reads only word/document.xml and never unpacks other entries.
  • Other files up to 600 KiB return as an MCP embedded resource blob.

With format: "original", the bytes return unchanged as image or resource content up to 600 KiB. A larger part fails with payload_too_large. The whole result stays below 960 KiB, so it fits the 1 MiB stdio frame. Long extracted text is shortened to fit and sets textTruncated.

With mail.attachments.send, send_message and reply_message accept up to 10 attachments. Each item names mailbox, uid_validity, uid, and part_id. Each mailbox must be allowed by the mail.read resource scope.

The server first validates the recipients and the text. It then fetches every part over IMAP before any SMTP connection. It uses one read session for each mailbox. The decoded parts must not exceed 2 MiB in total. The message becomes multipart/mixed: the plain-text body first, then one base64 part for each file. For a non-ASCII name, the Content-Disposition filename parameter uses an RFC 2231 extended value, such as filename*=utf-8''r%C3%A9sum%C3%A9.pdf. The Content-Type name parameter keeps an RFC 2047 encoded word for older clients. A received content type that is not a plain type/subtype becomes application/octet-stream. A known file extension can then give a specific type. The encoded message must not exceed 3.5 MiB. A message without attachments keeps its existing encoding and its 256 KiB limit.

The idempotency fingerprint includes the attachment references. A message without attachments keeps its existing fingerprint. The same key with other attachments returns conflict. A failed attachment read, such as a changed UIDVALIDITY, occurs before SMTP and reports status: rejected. A keyed call keeps this definitive outcome for 15 minutes, as for other rejected outcomes. After that window, the same key can send with corrected references.

stage_attachment takes standard padded base64 chunks of at most 524,288 characters. The first chunk sets filename and content_type. A filename must be one name without a path separator or control character. A content type must be a plain lowercase type/subtype. A staged file holds at most 2 MiB. The process holds at most 8 files and 4 MiB. A file expires 30 minutes after its last chunk. The bytes pass through the model, so staging suits small files only.

create_draft appends one plain-text message with staged files and referenced parts. It sets the \Draft and \Seen flags and never contacts SMTP. When ICLOUD_MCP_SMTP_ALLOWED_RECIPIENTS is set, each draft recipient must pass that allowlist, also without mail.send. Without the variable, a draft accepts any valid recipient, because it sends nothing. The result returns the draft identity and the partId of each attachment. send_message can then attach those parts by reference. The user can also open the draft in Mail.

The destination is the one selectable SPECIAL-USE \Drafts mailbox. iCloud marks no mailbox \Drafts, and the server never infers a purpose from a name. Set ICLOUD_MCP_DRAFTS_MAILBOX=Drafts for iCloud. The server uses that name only when no \Drafts mailbox exists. It rejects INBOX and a mailbox with another SPECIAL-USE role. APPEND to Drafts is a write, so the mail.mutate resource scope must allow the Drafts mailbox. Without a mail.mutate entry, the mail.read scope applies, as for other Mail writes. A draft must also stay readable, so the mail.read scope must allow the Drafts mailbox too. The server never appends a draft to a mailbox that the agent cannot read.

APPEND is never retried. An ambiguous result reports outcome_unknown with the Message-ID for reconciliation. Staged files are released only after a stored draft. While a create_draft call uses a staged file, another chunk or draft for that file returns conflict. After a failed draft, the file is usable again.

Path Rate and burst Concurrent sessions Retry
IMAP read 60/minute, burst 10 2 One replacement session for a transient read at most
IMAP mutation 20/minute, burst 3 1 None
SMTP send 20/minute, burst 3 1 None

Each attempt uses the applicable rate budget. All operations have a 25 second MCP tool deadline. The active context also limits each socket deadline.