# Send an audio message Source: https://messages.dev/docs/api-reference/audio-messages/send-audio-message POST /v1/audio-messages Sends an audio file as a native iMessage audio message (waveform balloon with a play button on the receiver) instead of a generic file pill. Two-step flow: upload an audio file via `POST /v1/files`, then pass the returned file ID as `audio_message`. Common formats are accepted — m4a, mp3, wav, caf, aiff. Audio is transcoded server-side, so you don't need to pre-encode. iMessage only — SMS lines are rejected. Some lines don't support audio messages; sending from one of those returns `400 advanced_features_required`. Like `POST /v1/messages`, the contact-first restriction applies: the recipient must have messaged your line first. Like all writes, this is asynchronous: returns a delivery ID with `status: "pending"`. Track via `GET /outbox` or webhooks. # List chats Source: https://messages.dev/docs/api-reference/chats/list-chats GET /v1/chats Returns chats for a line, ordered by most recent message. Supports cursor-based pagination. # Get file Source: https://messages.dev/docs/api-reference/files/get-file GET /v1/files Returns a `302` redirect to the file's storage URL. Use the `id` query parameter with a `file_` prefixed ID. # Upload file Source: https://messages.dev/docs/api-reference/files/upload-file POST /v1/files Uploads a file for use as a message attachment. Send the raw file bytes as the request body with the appropriate `Content-Type` header. Use the `X-Filename` header to set the filename. Returns a file object with an `id` to reference when sending messages. # List lines Source: https://messages.dev/docs/api-reference/lines/list-lines GET /v1/lines Returns your iMessage lines (phone numbers and Apple IDs). If the API key is restricted to specific lines, only those are returned. # List messages Source: https://messages.dev/docs/api-reference/messages/list-messages GET /v1/messages Returns messages in a chat, ordered by most recent first. Supports cursor-based pagination. # Send a message Source: https://messages.dev/docs/api-reference/messages/send-message POST /v1/messages Sends an iMessage or SMS. Returns a delivery ID with `status: "pending"`. Use `GET /outbox` or webhooks to track delivery. **Contact-first restriction**: outside the sandbox, the recipient must have messaged your line first. If they haven't, the request returns `403 contact_has_not_messaged`. **Group chats**: pass a chat ID (`cht_...`) returned from `GET /v1/chats` as `to`. Group chats also follow the contact-first rule: at least one inbound message must have been received in the chat. **Replies**: pass `reply_to` (a `msg_...` ID or raw iMessage GUID) to thread a reply to a specific message. **Attachments**: upload a file via `POST /v1/files` and pass its `file_...` ID in the `attachments` array. At least one of `text` or `attachments` is required. To send an audio message that renders as a native voice-memo balloon, use `POST /v1/audio-messages` instead. To send a vCard contact card, upload the `.vcf` file and pass its file ID in `attachments` (no `text` needed). # Get delivery status Source: https://messages.dev/docs/api-reference/outbox/get-outbox-item GET /v1/outbox Returns the current delivery status of a write operation. Use this to poll for completion after sending a message, reaction, etc. # Overview Source: https://messages.dev/docs/api-reference/overview Base URL, authentication, and conventions for the REST API The messages.dev REST API is a JSON over HTTPS API. Every endpoint is reachable from any language with an HTTP client. ## Recommended: use the TypeScript SDK For TypeScript and Node.js, the [`@messages-dev/sdk`](/docs/sdk) package is the recommended integration path. It wraps every endpoint in this reference with a typed client, handles cursor pagination, throws typed errors, and ships a `verifyWebhook()` helper that gets the HMAC signature scheme right (`HMAC(${timestamp}.${body})` with replay protection). ```bash theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} npm install @messages-dev/sdk ``` ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); // reads MESSAGES_API_KEY await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: "Hello from Messages.dev!", }); ``` See the [SDK reference](/docs/sdk) for the full surface area. If you're not on TypeScript — or you just want to know what's on the wire — the rest of this page documents the underlying REST API directly. ## Base URL ``` https://api.messages.dev/v1 ``` Your base URL is shown in your [dashboard](https://app.messages.dev). ## Authentication Authenticate every request with a bearer token: ```bash theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} Authorization: Bearer sk_live_... ``` Create API keys from your [dashboard](https://app.messages.dev/api-keys). See [Authentication](/docs/concepts/authentication) for scopes and line restrictions. ## Requests All request bodies are JSON encoded as UTF-8 with `Content-Type: application/json`. The API supports CORS for `GET`, `POST`, `DELETE`, and `OPTIONS`. ## Responses Single resources return the object directly: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "id": "msg_01h...", "text": "hello", "created_at": 1712188800000 } ``` List endpoints return an envelope with cursor pagination fields: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "data": [ ... ], "has_more": false, "next_cursor": null } ``` Errors return a consistent envelope: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "error": { "type": "invalid_request_error", "code": "missing_required_parameter", "message": "..." }, "request_id": "req_..." } ``` ## Conventions * Field names use `snake_case`. * IDs are prefixed by resource type: `msg_`, `cht_`, `ln_`, `rxn_`, `obx_`, `wh_`, `ind_`, `rcp_`, `file_`. * Timestamps are Unix milliseconds (UTC). * Every response includes a `request_id`. Include it when reporting issues. ## Pagination List endpoints are cursor-paginated. When `has_more` is `true`, pass `next_cursor` as the `cursor` query parameter on the next request: ```bash theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl "https://api.messages.dev/v1/messages?cursor=eyJp..." \ -H "Authorization: Bearer sk_live_..." ``` ## Asynchronous writes Write endpoints (`POST /messages`, `/audio-messages`, `/reactions`, `/typing`, `/receipts`) accept the request and return an outbox record with status `pending`: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "id": "obx_...", "status": "pending", "request_id": "req_..." } ``` Messages.dev delivers it over iMessage or SMS and reports back. Track delivery by: * **Webhooks** (recommended): subscribe to `message.sent`. Outgoing messages share the same shape as inbound ones (`is_from_me: true`). * **Polling**: `GET /outbox?id=obx_...` — status transitions through `pending` → `claimed` → `sent` (or `failed`, with the failure reason in `error`). ## Sending: contact-first Outside the sandbox, you can only send to a contact (or group chat) **after** they have messaged your line first. Sending to a cold contact returns `403 contact_has_not_messaged`. See [Send a message](/docs/guides/send-message) for the full flow. ## Errors The API maps to standard HTTP status codes (`2xx` success, `4xx` client error, `5xx` server error). See [Errors](/docs/concepts/errors) for the full taxonomy and error codes. ## Rate limits API keys are rate limited per hour. When exceeded, the API returns `429` with a `Retry-After` header indicating the seconds to wait. See [rate limit errors](/docs/concepts/errors#rate_limit_error-429) for details. ## DELETE with a request body `DELETE /webhooks` takes the resource ID in the **request body**, not the URL: ```bash theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X DELETE https://api.messages.dev/v1/webhooks \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{"id": "wh_abc123"}' ``` # List reactions Source: https://messages.dev/docs/api-reference/reactions/list-reactions GET /v1/reactions Returns all reactions on a specific message. # Send a reaction Source: https://messages.dev/docs/api-reference/reactions/send-reaction POST /v1/reactions Sends a reaction on a message. Returns a delivery ID with `status: "pending"`. # List read receipts Source: https://messages.dev/docs/api-reference/receipts/list-read-receipts GET /v1/receipts Returns read receipts for a chat. # Send read receipt Source: https://messages.dev/docs/api-reference/receipts/send-read-receipt POST /v1/receipts Marks a chat as read. Returns a delivery ID with `status: "pending"`. # Get typing indicators Source: https://messages.dev/docs/api-reference/typing/get-typing-indicators GET /v1/typing Returns current typing indicators for a chat. # Send typing indicator Source: https://messages.dev/docs/api-reference/typing/send-typing-indicator POST /v1/typing Sends a typing indicator to a chat. Returns a delivery ID with `status: "pending"`. # Create webhook Source: https://messages.dev/docs/api-reference/webhooks/create-webhook POST /v1/webhooks Creates a new webhook subscription for a line. The server generates an HMAC secret returned once on creation (also visible in the dashboard). ### Delivery format ```http POST /your-endpoint HTTP/1.1 Content-Type: application/json X-Webhook-Signature: X-Webhook-Timestamp: X-Webhook-Delivery-Id: dlv_ { "event": "message.received", "data": { ... }, "timestamp": , "delivery_id": "dlv_..." } ``` ### Signature `X-Webhook-Signature` is the lowercase hex HMAC-SHA256 of `${timestamp}.${rawBody}` using the webhook secret. Verifiers should use the `X-Webhook-Timestamp` header (or the `timestamp` field in the body) to construct the signed payload, and reject deliveries whose timestamp is more than 5 minutes off (replay protection). The `@messages-dev/sdk` package's `verifyWebhook()` helper performs all of this for you, including timing-safe comparison. # Delete webhook Source: https://messages.dev/docs/api-reference/webhooks/delete-webhook DELETE /v1/webhooks Deletes a webhook subscription. The webhook ID is passed in the request body (not in the URL path). # List webhooks Source: https://messages.dev/docs/api-reference/webhooks/list-webhooks GET /v1/webhooks Returns all active webhooks for a line. # CLI Source: https://messages.dev/docs/cli Send and receive iMessages from your terminal The `messages-dev` CLI is the fastest way to poke at the API by hand, pipe a shell pipeline into a message, or stream live events into a local dev server. It is a single self-contained binary built from the same SDK that powers the TypeScript client. ## Install ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -fsSL https://www.messages.dev/install.sh | sh ``` The script detects your OS and architecture (macOS arm64/x64, Linux arm64/x64), downloads the matching binary from the latest GitHub release, verifies its SHA-256 checksum, and installs it to `~/.messages/bin/`. It prints the line you need to add to your shell rc. Pin a specific release with `MESSAGES_CLI_VERSION=v0.2.0` or change the install location with `MESSAGES_INSTALL=/opt/messages`. If you already have Node.js, you can install via npm instead: ```bash npm theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} npm install -g @messages-dev/cli ``` ```bash pnpm theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} pnpm add -g @messages-dev/cli ``` ```bash bun theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} bun add -g @messages-dev/cli ``` On macOS the curl-installed binary is not yet signed with an Apple Developer ID. The first time you run it, Gatekeeper may block it; right-click the binary in Finder and choose **Open** once, or run `xattr -d com.apple.quarantine ~/.messages/bin/messages-dev`. The npm install does not have this issue. ## Authenticate Two options. Pick the one that fits your context. ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} # Interactive: stores credentials in ~/.messages/config.json messages-dev login # Headless / CI: short-circuit login by exporting an API key export MESSAGES_API_KEY=sk_live_... ``` `MESSAGES_API_KEY` always wins over the config file. Create a key in the [dashboard](https://app.messages.dev) under **API Keys**. ## Send your first message ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} messages-dev login messages-dev lines list messages-dev send +14155551234 "hi from the terminal" ``` If you have exactly one active line, `--from` is optional. Otherwise pass `--from ` to disambiguate. You can also pipe text in over stdin: ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} echo "deploy finished in $(date +%T)" | messages-dev send +14155551234 ``` ## Commands Run `messages-dev --help` for full flag detail on any of these. | Command | What it does | | ------------------------------------- | ------------------------------------------------------------------------------------------------ | | `login` / `logout` | Sign in interactively; remove stored credentials | | `send [text]` | Send a text, attachment, or audio message. Reads stdin when `[text]` is omitted. | | `react ` | Send a tapback. `love`, `like`, `dislike`, `laugh`, `emphasize`, `question`, or a literal emoji. | | `typing ` | Send a typing indicator. `--off` clears it. | | `read ` | Mark a chat as read. | | `lines list` | List the lines on your account. | | `chats list --line ` | List chats on a line. | | `messages list --line --chat ` | List messages in a chat. Cursor-paginated. | | `messages get --line --chat` | Fetch a single message. | | `reactions list --message ` | List reactions on a message. | | `receipts list --line --chat` | List read receipts in a chat. | | `outbox get ` | Inspect an outbound item by `obx_…` id. | | `files upload ` | Upload a file, print its `file_…` id. | | `files get ` | Print a download URL, or stream bytes with `--download`. | | `webhooks list` / `create` / `delete` | Manage webhook subscriptions. | | `listen` | Stream events live; with `--forward-to`, post HMAC-signed webhooks to a local URL. | ## Output and exit codes By default every command renders human-readable output. Pass `--json` (or set `MESSAGES_OUTPUT=json` once for the whole shell) to switch to structured output on stdout. Errors always go to stderr; with `--json` they take the shape `{"error":{"code":"…","message":"…"}}`. | Exit code | Meaning | | --------- | ------------------------------------- | | `0` | OK | | `1` | Generic failure | | `2` | Usage error (bad flags, missing args) | | `3` | Not authenticated | | `4` | Not found | | `5` | Validation error | ## Recipes ### Pipe stdin into a message Anything that produces text on stdout can become an iMessage: ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} git log -1 --pretty=%B | messages-dev send +14155551234 tail -n 50 /var/log/app.log | messages-dev send oncall@icloud.com ``` ### Forward live events to a local webhook handler `listen --forward-to` turns the CLI into a poor-man's tunnel for webhook development. It subscribes to your account's event stream and POSTs each event to your local URL with the same HMAC headers production webhooks use, so you can develop and test webhook handlers without ngrok or a tunnel. ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} messages-dev listen --forward-to http://localhost:3000/webhooks ``` The CLI prints a session HMAC secret on first run; verify deliveries against that, or pin one with `MESSAGES_LISTEN_SECRET=…`. Filter to specific events or scope to a single line: ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} messages-dev listen --event message.received --event message.failed messages-dev listen --line ln_abc123 ``` ### Upload an attachment, then send it ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} file_id=$(messages-dev files upload ./photo.jpg --json | jq -r .id) messages-dev send +14155551234 "look at this" --attach "$file_id" ``` Or in one go without `jq` by upgrading the recipient flow to your code's needs: ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} messages-dev send +14155551234 "look at this" \ --attach "$(messages-dev files upload ./photo.jpg)" ``` (The non-JSON `files upload` output prints the bare `file_…` id, suitable for direct substitution.) ### Tapback the latest message in a thread ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} last_id=$(messages-dev messages list \ --line +14155551234 --chat +14150000000 --limit 1 --json \ | jq -r '.data[0].id') messages-dev react "$last_id" love ``` ## Troubleshooting **`command not found: messages-dev`** — the install directory is not on your PATH. Add `export PATH="$HOME/.messages/bin:$PATH"` to your shell rc, or run the binary by full path. **macOS blocks the binary on first run** — Gatekeeper. See the warning under [Install](#install). The npm-installed CLI does not hit this. **`not_authenticated` errors** — you signed in on a different machine, or your API key was revoked. `MESSAGES_API_KEY` takes precedence over `~/.messages/config.json`; if you have a stale key exported, the file is ignored. Run `messages-dev login` or `unset MESSAGES_API_KEY`. **Pin or roll back a version** — the install script honors `MESSAGES_CLI_VERSION`: ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -fsSL https://www.messages.dev/install.sh | MESSAGES_CLI_VERSION=v0.2.0 sh ``` ## See also The same API as the CLI, in your code. Long-term event delivery once you outgrow `listen --forward-to`. # Authentication Source: https://messages.dev/docs/concepts/authentication API keys and authenticating requests ## Getting an API key API keys are created from your [Messages.dev dashboard](https://app.messages.dev). 1. Go to **API Keys** in the sidebar 2. Click **Create Key** 3. Give it a name and copy the key. It starts with `sk_live_` and is only shown once Store your API key securely. It won't be displayed again after creation. If you lose it, revoke it and create a new one. ## Authenticating requests ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); const client = createClient({ apiKey: "sk_live_..." }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl https://api.messages.dev/v1/lines \ -H "Authorization: Bearer sk_live_..." ``` ## Scopes Each API key has **scopes** that control which endpoints it can access. | Scope | Grants access to | | ----------------- | ------------------------------------ | | `messages:read` | GET /messages | | `messages:write` | POST /messages, POST /audio-messages | | `chats:read` | GET /chats | | `lines:read` | GET /lines | | `reactions:read` | GET /reactions | | `reactions:write` | POST /reactions | | `typing:read` | GET /typing | | `typing:write` | POST /typing | | `receipts:read` | GET /receipts | | `receipts:write` | POST /receipts | | `webhooks:read` | GET /webhooks | | `webhooks:write` | POST, DELETE /webhooks | | `outbox:read` | GET /outbox | | `files:read` | GET /files | | `files:write` | POST /files | ## Line restrictions API keys can be restricted to specific lines. A line-restricted key can only read and write data for its allowed lines. Requests to other lines return `403`. This is useful when you have multiple integrations or want to limit blast radius. You can configure line restrictions when creating a key in the dashboard. All API keys automatically have access to the [sandbox line](/docs/concepts/sandbox), regardless of line restrictions. ## Errors | Scenario | Status | Code | | -------------------------- | ------ | --------------------- | | No `Authorization` header | 401 | `missing_api_key` | | Invalid or revoked key | 401 | `invalid_api_key` | | Key lacks required scope | 403 | `insufficient_scope` | | Key can't access this line | 403 | `line_not_accessible` | # Errors Source: https://messages.dev/docs/concepts/errors Error taxonomy and response shape ## Error response shape All errors follow a consistent structure: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "error": { "type": "invalid_request_error", "code": "missing_required_parameter", "message": "The 'from' field is required.", "param": "from" }, "request_id": "req_a1b2c3d4e5f6" } ``` | Field | Description | | ------------ | --------------------------------------------------------- | | `type` | Error category (see below) | | `code` | Machine-readable error code | | `message` | Human-readable explanation | | `param` | The parameter that caused the error (when applicable) | | `request_id` | Unique ID for debugging. Include this in support requests | ## Error types ### `authentication_error` (401) The request could not be authenticated. | Code | Meaning | | ----------------- | ------------------------------------------------------- | | `missing_api_key` | No `Authorization` header provided | | `invalid_api_key` | Key format is wrong, key is revoked, or key has expired | ### `authorization_error` (403) The API key is valid but lacks permission. | Code | Meaning | | ------------------------ | -------------------------------------------------------------------------------------- | | `insufficient_scope` | The key doesn't have the required scope for this endpoint | | `line_not_accessible` | The key is line-scoped and can't access the requested line | | `sandbox_not_activated` | Your sandbox hasn't been activated yet. Text the activation code to the sandbox number | | `sandbox_requires_owner` | The sandbox key isn't tied to a Messages.dev account | ### `invalid_request_error` (400) The request is malformed or missing required data. A small number of `invalid_request_error` codes are returned with `403` instead of `400` because they describe a per-line policy violation, not a malformed payload — see [`contact_has_not_messaged`](#contact-first) below. | Code | Status | Meaning | | ---------------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------- | | `missing_required_parameter` | 400 | A required query parameter or body field is missing | | `invalid_parameter_value` | 400 | A parameter has an invalid value (e.g. wrong ID prefix or more than one attachment) | | `invalid_json` | 400 | The request body is not valid JSON | | `empty_file` | 400 | `POST /v1/files` was called with a zero-byte body | | `advanced_features_required` | 400 | The line you're sending from doesn't have advanced features enabled (required for audio messages, reactions, typing, read receipts) | | `sandbox_contact_mismatch` | 400 | You can only send to your paired phone number on the sandbox line | | `contact_has_not_messaged` | 403 | The recipient (or group chat) hasn't messaged your line first — see below | #### Contact-first Outside the sandbox, the recipient must message your line first before you can send to them. Sending into a cold contact returns `contact_has_not_messaged` with HTTP 403. The same rule applies to group chats: at least one inbound message must have been received in the chat before you can post to it. ### `not_found_error` (404) The requested resource doesn't exist. | Code | Meaning | | ----------------------- | --------------------------------------------------------- | | `line_not_found` | No line exists with the given handle | | `chat_not_found` | No chat found for the given identifier on this line | | `message_not_found` | No message found with the given ID (including `reply_to`) | | `outbox_item_not_found` | No outbox item found with the given ID | | `webhook_not_found` | No webhook found with the given ID | | `file_not_found` | No file found with the given `file_...` ID | ### `rate_limit_error` (429) Too many requests. Back off and retry after the `Retry-After` header value. | Code | Meaning | | ------------------------ | ------------------------------------------------------------------ | | `rate_limit_exceeded` | Hourly API rate limit exceeded | | `sandbox_quota_exceeded` | Daily sandbox limit of 50 messages reached. Resets at midnight UTC | See [Limits](/docs/scaling/limits) for the per-line message guidance that sits above the API request rate. ## HTTP status codes | Status | Meaning | | ------ | -------------------------------------------------------------------- | | 200 | Success | | 201 | Resource created | | 204 | No content (OPTIONS preflight) | | 400 | Bad request | | 401 | Unauthorized | | 403 | Forbidden | | 404 | Not found | | 429 | Rate limited (hourly API rate limit or daily sandbox quota exceeded) | # Sandbox Source: https://messages.dev/docs/concepts/sandbox Free sandbox line for testing with 50 messages per day Every Messages.dev account includes a **sandbox line**: a shared iMessage number you can use immediately to send and receive up to 50 messages per day. ## How it works The sandbox is a Messages.dev-owned iMessage line that all users share. To keep messages private, each user pairs their personal phone number with their account through an activation code. ### Activation 1. Go to the **Lines** page in your [dashboard](https://app.messages.dev) 2. Scan the QR code with your phone, or copy the activation code and text it to the sandbox number 3. Once the message is received, your sandbox is activated and your phone number is paired After activation, you can send messages to your paired phone and receive webhooks for incoming messages, just like a dedicated line. ### Limits | | | | -------------------- | --------------------------------------------------------- | | **Messages per day** | 50 | | **Reset time** | Midnight UTC | | **Recipient** | Your paired phone number only | | **Features** | Send, receive, reactions, typing, read receipts, webhooks | The daily limit is per account, not per API key. All your API keys share the same 50-message sandbox budget. ## Sending messages Use the sandbox line handle as the `from` field and your paired phone number as `to`: ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: "Hello from the sandbox!", }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/messages" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "+15559876543", "text": "Hello from the sandbox!" }' ``` ## Receiving messages Register a webhook on the sandbox line to receive notifications when your paired phone sends messages back: 1. Go to **Webhooks** in the dashboard 2. Select the sandbox line and enter your endpoint URL 3. Webhooks are scoped to your account; you only receive events for your paired phone number ## Upgrading to a dedicated line The sandbox is designed for testing and evaluation. For production use: * Set up a dedicated iMessage line with no daily limits * See the [quickstart guide](/docs/quickstart) for setup instructions ## Errors | Status | Code | Meaning | | ------ | -------------------------- | --------------------------------------------------------------------------------------- | | 403 | `sandbox_not_activated` | Your sandbox hasn't been activated yet. Text the activation code to the sandbox number. | | 400 | `sandbox_contact_mismatch` | You can only send to your paired phone number on the sandbox line. | | 429 | `sandbox_quota_exceeded` | Daily limit of 50 messages reached. Resets at midnight UTC. | # Webhooks Source: https://messages.dev/docs/concepts/webhooks Real-time event notifications via HTTPS ## Overview Webhooks push events to your server as they happen, no polling required. Register a URL, choose which events you care about, and Messages.dev will POST to it in real time. ## Events | Event | Description | | ------------------ | ----------------------------------- | | `message.received` | A new incoming message on the line. | | `message.sent` | An outgoing message was delivered. | | `reaction.added` | Someone reacted to a message. | | `reaction.removed` | Someone removed their reaction. | Inbound `typing.started` / `typing.stopped` and `receipt.read` are not delivered today — Apple's underlying APIs surface those events on the macOS side but our daemon doesn't expose them yet. Subscribing to them is currently rejected. They will return when the underlying detection layer ships. Every event delivers a JSON body with the same envelope (`event`, `data`, `timestamp`, `delivery_id`) and the same set of headers (see [Payload format](#payload-format)). The shape of `data` depends on the event: ### `message.received` and `message.sent` `data` matches the `Message` resource and adds `line_handle` (your line's phone number / Apple ID, included so you can route inbound events without a side lookup). | Field | Type | Notes | | ------------------ | ----------------- | ------------------------------------------------------------------- | | `id` | `string` | `msg_…` | | `line_id` | `string` | `ln_…` | | `line_handle` | `string` | The line's phone number or Apple ID. | | `chat_id` | `string` | `cht_…` — the conversation. | | `guid` | `string` | iMessage GUID. Use as `reply_to` or to react. | | `sender` | `string` | Phone number / Apple ID of who sent it. | | `text` | `string \| null` | `null` when the message is attachment-only. | | `attachments` | `Attachment[]` | Files attached to the message. Voice memos include `transcription`. | | `is_from_me` | `boolean` | `true` for `message.sent`, `false` for `message.received`. | | `is_audio_message` | `boolean \| null` | `true` for native voice memos. | | `sent_at` | `number` | Unix ms. | | `synced_at` | `number` | Unix ms when synced to messages.dev. | | `reply_to_guid` | `string \| null` | iMessage GUID of the parent if this is a reply. | ### `reaction.added` and `reaction.removed` `data` matches the `Reaction` resource and adds `chat_id` (so you can route the event to a thread without an extra `getMessage` call) and `line_handle`. | Field | Type | Notes | | ------------- | --------- | ----------------------------------------------------------------- | | `id` | `string` | `rxn_…` | | `message_id` | `string` | `msg_…` — the message being reacted to. | | `chat_id` | `string` | `cht_…` — the conversation the message lives in. | | `line_handle` | `string` | The line that received (or sent) the reaction. | | `type` | `string` | `love` / `like` / `dislike` / `laugh` / `emphasize` / `question`. | | `sender` | `string` | Phone number / Apple ID of who reacted. | | `is_from_me` | `boolean` | True if your line was the reactor. | | `added` | `boolean` | `true` for `reaction.added`, `false` for `reaction.removed`. | | `sent_at` | `number` | Unix ms. | | `synced_at` | `number` | Unix ms. | ## Creating a webhook The easiest way to create a webhook is from the **Webhooks** page in your [dashboard](https://app.messages.dev). Click **Add Webhook**, enter your URL, select the events you care about, and copy the signing secret. The dashboard is the recommended way to manage webhooks. It shows the signing secret once on creation and makes it easy to enable, disable, or delete webhooks without writing code. You can also create webhooks via the API: ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); const webhook = await client.createWebhook({ from: "+15551234567", url: "https://your-server.com/webhooks", events: ["message.received", "message.sent"], }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/webhooks" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "url": "https://your-server.com/webhooks", "events": ["message.received", "message.sent"] }' ``` Each webhook is scoped to a single line. Create one per line if you have multiple lines. ## Payload format ```http theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} POST /webhooks HTTP/1.1 Content-Type: application/json X-Webhook-Signature: a1b2c3d4e5f6... X-Webhook-Timestamp: 1710000000123 X-Webhook-Delivery-Id: dlv_abc... { "event": "message.received", "data": { "id": "msg_abc123", "line_id": "ln_xyz", "line_handle": "+15551234567", "chat_id": "cht_def456", "sender": "+15559876543", "text": "Hey there!", "is_from_me": false, "is_audio_message": false, "attachments": [], "sent_at": 1710000000000 }, "timestamp": 1710000000123, "delivery_id": "dlv_abc..." } ``` Each delivery includes three headers in addition to `Content-Type`: | Header | Description | | ----------------------- | -------------------------------------------------------------------------------- | | `X-Webhook-Signature` | Hex HMAC-SHA256 over `${timestamp}.${rawBody}` | | `X-Webhook-Timestamp` | Unix ms at delivery time. Reject if more than 5 minutes off (replay protection). | | `X-Webhook-Delivery-Id` | Unique `dlv_...` ID for the delivery. Useful for idempotency on your side. | ### Voice memos Inbound tap-to-record voice memos arrive on the same `message.received` event. The message has `is_audio_message: true` and the audio attachment carries the auto-generated transcription text from iMessage: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "event": "message.received", "data": { "id": "msg_abc123", "line_id": "ln_xyz", "line_handle": "+15551234567", "chat_id": "cht_def456", "sender": "+15559876543", "text": null, "is_from_me": false, "is_audio_message": true, "attachments": [ { "filename": "Audio Message.caf", "mime_type": "audio/x-caf", "size": 24576, "url": "https://files.messages.dev/...", "transcription": "Hey, can you grab milk on the way home?" } ], "sent_at": 1710000000000 }, "timestamp": 1710000000123 } ``` `transcription` may be `null` on the first delivery if Apple hasn't finished on-device transcription yet (typically \<2s after receipt). It is also `null` for non-voice-memo audio attachments (e.g. a drag-and-dropped MP3), which arrive with `is_audio_message: false`. ## Verifying signatures Every webhook delivery is signed with HMAC-SHA256 over the string `${timestamp}.${rawBody}` using your webhook secret. The SDK handles signature verification, timing-safe comparison, and replay protection automatically: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { verifyWebhook } from "@messages-dev/sdk"; app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], "your_webhook_secret", ); console.log(event.event, event.data); res.sendStatus(200); }); ``` If the signature is invalid (or the timestamp is more than 5 minutes off), `verifyWebhook` throws a `SignatureVerificationError`. The default tolerance window can be overridden via the `tolerance` option (in milliseconds). If you're not using the SDK, verify manually. Build the signed payload as `${timestamp}.${rawBody}` — using `${rawBody}` alone will always fail. The timestamp is available both as the `X-Webhook-Timestamp` header and as the `timestamp` field inside the parsed body: ```javascript Node.js theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createHmac, timingSafeEqual } from "crypto"; function verifyWebhook(rawBody, headers, secret, toleranceMs = 5 * 60_000) { const signature = headers["x-webhook-signature"]; const timestamp = Number(headers["x-webhook-timestamp"]); if (!signature || !timestamp) return false; if (Math.abs(Date.now() - timestamp) > toleranceMs) return false; const expected = createHmac("sha256", secret) .update(`${timestamp}.${rawBody}`) .digest("hex"); const a = Buffer.from(signature); const b = Buffer.from(expected); return a.length === b.length && timingSafeEqual(a, b); } ``` ```python Python theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import hmac import hashlib import time def verify_webhook(raw_body: bytes, headers, secret: str, tolerance_ms: int = 5 * 60_000) -> bool: signature = headers.get("x-webhook-signature") timestamp = int(headers.get("x-webhook-timestamp", "0")) if not signature or not timestamp: return False if abs(int(time.time() * 1000) - timestamp) > tolerance_ms: return False signed_payload = f"{timestamp}.".encode() + raw_body expected = hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature) ``` Always verify the signature before processing a webhook payload. This prevents attackers from sending forged events to your endpoint. ## Testing webhooks locally ### Use the CLI for live local development The fastest way to iterate on a webhook handler locally is the [`messages-dev` CLI](/docs/cli). [`listen --forward-to`](/docs/cli#forward-live-events-to-a-local-webhook-handler) subscribes to your account's event stream and POSTs each real event to a local URL with the same HMAC headers production deliveries use, so you don't need to register a webhook, run ngrok, or expose a public URL while you build: ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} messages-dev listen --forward-to http://localhost:3000/webhooks ``` The CLI prints a per-session HMAC secret on first run. Use it as the secret in your [`verifyWebhook()`](#verifying-signatures) call, or pin one with `MESSAGES_LISTEN_SECRET=…`. Because the deliveries are genuinely signed, your verification code runs unchanged. If you'd rather exercise the production delivery path end-to-end, expose your local server with [ngrok](https://ngrok.com), [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/), or any other tunnel and [register a real webhook](#creating-a-webhook) pointing at the public URL. Same payload, same headers — only the source of the deliveries changes. ### Synthesize signed deliveries in tests For unit tests, where you want to drive the handler without a network round trip, the SDK exports two helpers that build *real* signed deliveries you can POST at your handler — no test-mode bypass needed. Your `verifyWebhook()` code path runs unchanged because the signature is genuine. `buildWebhookDelivery(event, data, secret)` is the high-level helper: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { buildWebhookDelivery } from "@messages-dev/sdk"; const { body, headers } = await buildWebhookDelivery( "message.received", { id: "msg_test", lineId: "ln_test", lineHandle: "+15551234567", chatId: "cht_test", guid: "guid-test", sender: "+15559876543", text: "hello from a test", attachments: [], isFromMe: false, sentAt: Date.now(), syncedAt: Date.now(), }, process.env.WEBHOOK_SECRET!, ); await fetch("http://localhost:3000/webhooks", { method: "POST", body, headers, }); ``` For more control — building a full body yourself, signing on a different language, etc. — use the lower-level `signWebhook(secret, timestamp, rawBody)` helper which returns the lowercase hex HMAC-SHA256 of `${timestamp}.${rawBody}`. This covers the unit-test inner loop: no `isEmulator` flag, no skipping signature verification, just real signed deliveries on demand. For end-to-end local dev with live events from your account, prefer `messages-dev listen --forward-to` above. ## Deleting a webhook You can delete webhooks from the **Webhooks** page in your [dashboard](https://app.messages.dev), or in code: ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.deleteWebhook({ id: "wh_abc123" }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X DELETE https://api.messages.dev/v1/webhooks \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{"id": "wh_abc123"}' ``` When using the REST API directly, the webhook ID is passed in the **request body**, not in the URL path. # Attachments Source: https://messages.dev/docs/guides/attachments Send images, files, and other attachments You can send images, videos, documents, and other files as iMessage attachments. Incoming messages with attachments include metadata and a download URL for each file. ## Send an attachment Upload a file first, then reference it by ID when sending a message: ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); const file = await client.uploadFile({ from: "+15551234567", file: Buffer.from(imageData), filename: "photo.jpg", mimeType: "image/jpeg", }); await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: "Check out this photo!", attachments: [file.id], }); await client.sendMessage({ from: "+15551234567", to: "+15559876543", attachments: [file.id], }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/files?from=+15551234567" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: image/jpeg" \ -H "X-Filename: photo.jpg" \ --data-binary @photo.jpg curl -X POST "https://api.messages.dev/v1/messages" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "+15559876543", "text": "Check out this photo!", "attachments": ["file_abc123"] }' ``` | Field | Required | Description | | ------------- | -------- | ---------------------------------------------------------- | | `to` | Yes | Recipient phone number or Apple ID | | `text` | No | Optional message text (can be omitted when sending a file) | | `attachments` | No | Array of file IDs (max 1) from the upload endpoint | At least one of `text` or `attachments` must be provided. ## Supported file types iMessage supports most common file types. The recipient's device determines how the attachment is displayed: | Type | Examples | Display | | --------- | ---------------------------------------- | ----------------------- | | Images | `.jpg`, `.png`, `.gif`, `.heic`, `.webp` | Inline preview | | Videos | `.mp4`, `.mov` | Inline player | | Audio | `.mp3`, `.m4a`, `.aac` | Audio player | | Documents | `.pdf`, `.docx`, `.xlsx` | File icon with preview | | Other | Any file type | Generic file attachment | ## Receive attachments Incoming messages with attachments include an `attachments` array with metadata and a download URL for each file: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "event": "message.received", "data": { "id": "msg_abc123", "sender": "+15559876543", "text": null, "attachments": [ { "filename": "IMG_1234.jpg", "mime_type": "image/jpeg", "size": 245760, "url": "https://storage.convex.cloud/..." } ], "sent_at": 1710000005000 } } ``` Handle attachments in your webhook: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { verifyWebhook } from "@messages-dev/sdk"; app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], "your_webhook_secret", ); if (event.event === "message.received") { if (event.data.attachments?.length) { for (const att of event.data.attachments) { console.log(`Received: ${att.filename} (${att.mimeType}, ${att.size} bytes)`); console.log(`Download: ${att.url}`); } } if (event.data.text) { console.log(`Text: ${event.data.text}`); } } res.sendStatus(200); }); ``` You can also retrieve attachment URLs when listing messages: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const messages = await client.listMessages({ from: "+15551234567", to: "+15559876543", }); for (const msg of messages.data) { for (const att of msg.attachments) { console.log(att.url); console.log(att.filename); console.log(att.mimeType); } } ``` # Audio Messages Source: https://messages.dev/docs/guides/audio-messages Send native iMessage audio messages with a waveform balloon Send an audio clip and the recipient sees the native iMessage audio message balloon — waveform, play button, scrubber — not a generic file pill. ## Send an audio message Two-step flow: upload the audio file via `POST /v1/files`, then send it by file ID. Common formats are accepted — m4a, mp3, wav, caf, aiff. ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { readFileSync } from "node:fs"; import { createClient } from "@messages-dev/sdk"; const client = createClient(); // 1. Upload the audio file const file = await client.uploadFile({ file: readFileSync("clip.m4a"), mimeType: "audio/mp4", filename: "clip.m4a", }); // 2. Send it as an audio message await client.sendAudioMessage({ from: "+15551234567", to: "+15559876543", audioMessage: file.id, }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} # 1. Upload the audio file curl -X POST "https://api.messages.dev/v1/files" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: audio/mp4" \ -H "X-Filename: clip.m4a" \ --data-binary @clip.m4a # Response: { "id": "file_...", ... } # 2. Send it as an audio message curl -X POST "https://api.messages.dev/v1/audio-messages" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "+15559876543", "audio_message": "file_..." }' ``` File IDs are reusable — upload a clip once and send it to many recipients without re-uploading. ## Parameters | Field | Required | Description | | -------------- | -------- | -------------------------------------------------------------------- | | `from` | Yes | Sender line handle. | | `to` | Yes | Recipient phone number, Apple ID, or chat ID (`cht_...`). | | `audioMessage` | Yes | File ID (`file_...`) of an audio file uploaded via `POST /v1/files`. | | `replyTo` | No | Message ID or GUID to reply to. | ## Requirements iMessage only — audio messages are not supported on SMS lines. Some lines don't support audio messages; sending from one of those returns `400 advanced_features_required`. ## Supported formats Common audio formats are accepted: * `m4a` / `aac` * `mp3` * `wav` * `caf` * `aiff` The audio is transcoded server-side, so you don't need to pre-encode. ## Receive an audio message Inbound voice memos are delivered through the standard `message.received` [webhook](/docs/concepts/webhooks). The message payload sets `is_audio_message: true` and the audio attachment includes a `transcription` field with the text that iMessage auto-generates on-device: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "event": "message.received", "data": { "id": "msg_abc123", "chat_id": "cht_def456", "sender": "+15559876543", "text": null, "is_from_me": false, "is_audio_message": true, "attachments": [ { "filename": "Audio Message.caf", "mime_type": "audio/x-caf", "size": 24576, "url": "https://files.messages.dev/...", "transcription": "Hey, can you grab milk on the way home?" } ], "sent_at": 1710000000000 }, "timestamp": 1710000000123 } ``` Download the audio bytes from `attachments[0].url` and use `transcription` to read what was said without running speech-to-text yourself. `transcription` is generated by Apple on the receiving Mac and may be `null` on the first delivery if it hasn't finished yet (usually within a couple of seconds). Non-voice-memo audio attachments (e.g. a drag-and-dropped MP3) arrive with `is_audio_message: false` and no transcription. ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { verifyWebhook } from "@messages-dev/sdk"; app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], process.env.WEBHOOK_SECRET!, ); if (event.event === "message.received" && event.data.isAudioMessage) { const voice = event.data.attachments?.[0]; console.log(`${event.data.sender} said: ${voice?.transcription ?? "(no transcript yet)"}`); } res.sendStatus(200); }); ``` # Contact Cards Source: https://messages.dev/docs/guides/contact-cards Send vCards as iMessage contact cards Send a contact card and the recipient sees a rich contact preview they can tap to save directly to their contacts, with call / text / email action buttons. ## Send a contact card Pass the contact fields directly to `sendContactCard` — the SDK generates the vCard, uploads it, and attaches it to a message in one call. ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); await client.sendContactCard({ from: "+15551234567", to: "+15559876543", firstName: "Jane", lastName: "Doe", phones: [{ type: "cell", value: "+15559876543" }], emails: [{ value: "jane@acme.com" }], org: "Acme Corp", title: "Head of Engineering", }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} # 1. Upload the vCard file curl -X POST "https://api.messages.dev/v1/files" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: text/vcard" \ -H "X-Filename: jane-doe.vcf" \ --data-binary @jane-doe.vcf # Response: { "id": "file_...", ... } # 2. Send it as an attachment curl -X POST "https://api.messages.dev/v1/messages" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "+15559876543", "attachments": ["file_..."] }' ``` Include at least one `phones` or `emails` entry. iOS uses them to render the tappable action buttons (call, text, email) on the contact preview. ## Supported fields | Field | Type | Description | | ----------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `firstName`, `lastName` | `string` | Required. Used for both `N` and `FN` in the vCard. | | `phones` | `{ value, type? }[]` | One or more phone numbers. `type` defaults to `cell`. | | `emails` | `{ value, type? }[]` | One or more email addresses. `type` is optional. | | `org` | `string` | Organization / company. | | `title` | `string` | Job title. | | `url` | `string` | Website. | | `address` | `{ street?, city?, region?, postalCode?, country?, type? }` | Mailing address. | | `bday` | `string` | Birthday, ISO `YYYY-MM-DD`. | | `note` | `string` | Free-text note. Reserved characters (`;`, `,`, newlines) are escaped automatically. | | `photo` | `string` | File ID (`file_...`) of a JPEG or PNG uploaded via `POST /v1/files`. The SDK fetches it and embeds it inline in the vCard. | | `photoType` | `"JPEG" \| "PNG"` | Override photo mime type when auto-detection from the file's magic bytes can't determine it. | | `text` | `string` | Optional message text sent alongside the card. | | `replyTo` | `string` | Message ID or GUID to reply to. | | `filename` | `string` | Override the uploaded `.vcf` filename. Default: `-.vcf`. | ## Add a contact photo Upload the photo via `POST /v1/files` first, then pass the returned file ID as `photo`. The SDK downloads it, sniffs the image type (JPEG / PNG), and embeds it inline in the vCard. ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { readFileSync } from "node:fs"; import { createClient } from "@messages-dev/sdk"; const client = createClient(); const photo = await client.uploadFile({ file: readFileSync("jane.jpg"), mimeType: "image/jpeg", filename: "jane.jpg", }); await client.sendContactCard({ from: "+15551234567", to: "+15559876543", firstName: "Jane", lastName: "Doe", phones: [{ type: "cell", value: "+15559876543" }], photo: photo.id, }); ``` Keep photos small (under 100KB) for the best delivery experience. Large photos inflate the vCard significantly once base64-encoded. ## Advanced: custom vCard If you need fields that `sendContactCard` doesn't expose (exotic `TYPE` combinations, custom `X-` extensions, multiple addresses), build the vCard yourself and send it via the file + attachment flow: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); const vcard = [ "BEGIN:VCARD", "VERSION:3.0", "N:Doe;Jane;;;", "FN:Jane Doe", "TEL;TYPE=CELL:+15559876543", "EMAIL:jane@acme.com", "END:VCARD", ].join("\r\n"); const file = await client.uploadFile({ file: new Blob([vcard], { type: "text/vcard" }), filename: "jane-doe.vcf", mimeType: "text/vcard", }); await client.sendMessage({ from: "+15551234567", to: "+15559876543", attachments: [file.id], }); ``` ## vCard format reference For reference when building custom vCards, a full-featured example: ``` BEGIN:VCARD VERSION:3.0 N:Doe;Jane;;; FN:Jane Doe ORG:Acme Corp TITLE:Head of Engineering TEL;TYPE=CELL:+15559876543 TEL;TYPE=WORK:+15551112222 EMAIL:jane@acme.com URL:https://acme.com ADR;TYPE=WORK:;;123 Main St;San Francisco;CA;94105;US NOTE:Met at WWDC 2025 END:VCARD ``` ### Common fields | Field | Example | Description | | ---------------------------- | ------------------------------ | ----------------------------------- | | `N` | `Doe;Jane;;;` | Last; First; Middle; Prefix; Suffix | | `FN` | `Jane Doe` | Full display name | | `TEL;TYPE=CELL` | `+15559876543` | Mobile phone | | `TEL;TYPE=WORK` | `+15551112222` | Work phone | | `EMAIL` | `jane@acme.com` | Email address | | `ORG` | `Acme Corp` | Organization | | `TITLE` | `Head of Engineering` | Job title | | `URL` | `https://acme.com` | Website | | `ADR;TYPE=WORK` | `;;123 Main St;City;ST;ZIP;US` | Address | | `NOTE` | `Met at WWDC 2025` | Free-text note | | `BDAY` | `1990-06-15` | Birthday | | `PHOTO;ENCODING=b;TYPE=JPEG` | `` | Inline photo | The MIME type for vCard files is `text/vcard`, the file extension is `.vcf`, and lines are joined with `\r\n`. # Group Chats Source: https://messages.dev/docs/guides/group-chats Send and receive messages in iMessage group chats iMessage group chats are first-class on Messages.dev. They show up in [`GET /v1/chats`](/docs/api-reference/chats/list-chats) with `is_group: true` and a populated `participants` array, and you address them by their `cht_...` ID. Apple does not let third-party software create new group chats. Messages.dev syncs group chats that already exist on your line — typically because someone added your line to a group, or your line was on the original `addParticipants` call from another iMessage client. ## Discover group chats ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); const { data: chats } = await client.listChats({ from: "+15551234567" }); const groups = chats.filter((c) => c.isGroup); for (const g of groups) { console.log(g.id, g.name ?? "(unnamed)", g.participants); } ``` ## Send into a group chat Pass the chat's `cht_...` ID as `to`: ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.sendMessage({ from: "+15551234567", to: "cht_abc123", text: "Hey team!", }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/messages" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "cht_abc123", "text": "Hey team!" }' ``` Reactions, typing indicators, attachments, audio messages, and replies all work the same way — anywhere a 1-on-1 endpoint accepts a phone number, it also accepts a `cht_...` chat ID. ## Contact-first applies to groups too A group chat must have at least one inbound message before you can send into it. If you call `POST /v1/messages` against a chat that has only outbound history (or none at all), you get: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "error": { "type": "invalid_request_error", "code": "contact_has_not_messaged", "message": "Cannot send to a chat that has not received an inbound message first.", "param": "to" } } ``` In practice this means the chat needs to be a real, two-way conversation — either a group you were added to, or one you started elsewhere where another participant has since replied. ## Receive group messages Inbound group messages flow through the standard `message.received` webhook. The payload's `chat_id` points to the group, and `sender` identifies the specific participant who sent it: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "event": "message.received", "data": { "id": "msg_abc123", "chat_id": "cht_abc123", "sender": "+15559876543", "text": "Coffee?", "is_from_me": false, "is_audio_message": false, "attachments": [], "sent_at": 1710000000000 }, "timestamp": 1710000000123 } ``` To list a group's history or look up participants, use [`GET /v1/messages?to=cht_...`](/docs/api-reference/messages/list-messages) and [`GET /v1/chats`](/docs/api-reference/chats/list-chats). # Reactions Source: https://messages.dev/docs/guides/reactions Send and receive iMessage reactions iMessage reactions are the emoji responses native to iMessage: love, like, dislike, laugh, emphasize, and question. You can send them on any message and receive them via webhooks. ## Send a reaction To react to a message, you need the message's `id` or `guid` (both are returned when listing messages) and the recipient's handle: ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); await client.sendReaction({ from: "+15551234567", to: "+15559876543", messageId: "msg_abc123", type: "love", }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/reactions" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "+15559876543", "message_id": "msg_abc123", "type": "love" }' ``` You can pass either a `msg_` prefixed ID or a raw iMessage GUID as the `message_id`. ### Reaction types | Type | Emoji | | ----------- | ----- | | `love` | ❤️ | | `like` | 👍 | | `dislike` | 👎 | | `laugh` | 😂 | | `emphasize` | ‼️ | | `question` | ❓ | ## Receive reactions via webhooks Subscribe to `reaction.added` and `reaction.removed` events to get notified when someone reacts to a message: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { verifyWebhook } from "@messages-dev/sdk"; app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], "your_webhook_secret", ); if (event.event === "reaction.added") { console.log(`${event.data.sender} reacted with ${event.data.type}`); } if (event.event === "reaction.removed") { console.log(`${event.data.sender} removed their ${event.data.type} reaction`); } res.sendStatus(200); }); ``` ## List reactions on a message ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const reactions = await client.listReactions({ messageId: "msg_abc123", }); for (const reaction of reactions.data) { console.log(`${reaction.sender}: ${reaction.type} (${reaction.added ? "added" : "removed"})`); } ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl "https://api.messages.dev/v1/reactions?message_id=msg_abc123" \ -H "Authorization: Bearer sk_live_..." ``` ## Finding the message ID Both the `id` and `guid` fields are returned on every message object. You can use either one when sending reactions: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const messages = await client.listMessages({ from: "+15551234567", to: "+15559876543", limit: 1, }); await client.sendReaction({ from: "+15551234567", to: "+15559876543", messageId: messages.data[0].id, type: "love", }); ``` # Read Receipts Source: https://messages.dev/docs/guides/read-receipts Mark conversations as read and track read status Read receipts let the other person know you've seen their message. You can send them programmatically and receive them via webhooks when someone reads your message. ## Mark a chat as read ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); await client.sendReadReceipt({ from: "+15551234567", to: "+15559876543", }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/receipts" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "+15559876543" }' ``` This marks the entire conversation as read. The other person will see a "Read" indicator under their last message. ## Receive read receipts via webhooks Subscribe to `receipt.read` events to know when someone has read your messages: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { verifyWebhook } from "@messages-dev/sdk"; app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], "your_webhook_secret", ); if (event.event === "receipt.read") { console.log(`${event.data.handle} read the chat at ${new Date(event.data.last_read_at)}`); } res.sendStatus(200); }); ``` ## List read receipts Check the read status of a chat: ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const receipts = await client.listReadReceipts({ from: "+15551234567", to: "+15559876543", }); for (const receipt of receipts.data) { console.log(`${receipt.handle} last read at ${new Date(receipt.lastReadAt)}`); } ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl "https://api.messages.dev/v1/receipts?from=+15551234567&to=+15559876543" \ -H "Authorization: Bearer sk_live_..." ``` ## Common pattern: auto-read on webhook Automatically mark conversations as read when you process incoming messages: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient, verifyWebhook } from "@messages-dev/sdk"; const client = createClient(); app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], "your_webhook_secret", ); if (event.event === "message.received") { await handleMessage(event.data); await client.sendReadReceipt({ from: event.data.line_id, to: event.data.sender, }); } res.sendStatus(200); }); ``` # Receive Messages Source: https://messages.dev/docs/guides/receive-messages Get notified when new messages arrive Incoming messages, reactions, and delivery events arrive as signed HTTPS POSTs to a URL you control. You write the handler once and it runs unchanged in dev and in production. ## 1. Handle the event ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { verifyWebhook } from "@messages-dev/sdk"; app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], process.env.WEBHOOK_SECRET!, ); if (event.event === "message.received") { console.log(`${event.data.sender}: ${event.data.text}`); } res.sendStatus(200); }); ``` `verifyWebhook` handles HMAC-SHA256 verification, timing-safe comparison, and replay protection, then returns a typed discriminated-union event. If you're not using the SDK, see the manual verification snippets in [Webhooks › Verifying signatures](/docs/concepts/webhooks#verifying-signatures). ## 2. Stream events to your handler (local dev) The fastest way to drive your handler while you're building is the [`messages-dev` CLI](/docs/cli). It POSTs each real account event to a local URL with the same headers a registered webhook would, so you don't need a public URL or a webhook registration. [Install the CLI and authenticate](/docs/cli#install), then: ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} messages-dev listen --forward-to http://localhost:3000/webhooks ``` The CLI prints a per-session HMAC secret on first run. Set it as `WEBHOOK_SECRET` in your handler, or pin one with `MESSAGES_LISTEN_SECRET=…` so it doesn't rotate between runs. Without `--forward-to`, `messages-dev listen` prints events to your terminal as they happen. Useful for tailing a line while you debug. ## 3. Register a webhook (production) When you're ready to deploy, go to the **Webhooks** page in your [dashboard](https://app.messages.dev), click **Add Webhook**, enter your public HTTPS endpoint, and copy the signing secret into your environment as `WEBHOOK_SECRET`. The handler from step 1 is unchanged. You can also [create webhooks via the API](/docs/concepts/webhooks#creating-a-webhook) if you need to provision them programmatically. ## Next steps * [Webhooks](/docs/concepts/webhooks) — full event list, payload shapes, and replay-protection rules. * [CLI reference](/docs/cli) — `listen` filtering flags, output modes, and other recipes. Prefer to use [ngrok](https://ngrok.com), Cloudflare Tunnel, or another tunnel for local dev? Expose your local server on a public URL and register a regular webhook pointing at it. Same payload, same handler code — see [Webhooks](/docs/concepts/webhooks) for setup. # Send a Message Source: https://messages.dev/docs/guides/send-message Send an iMessage and track delivery ## Send a message ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: "Hello from Messages.dev!", }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/messages" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "+15559876543", "text": "Hello from Messages.dev!" }' ``` | Field | Required | Description | | ------------- | ----------- | ------------------------------------------------------------------------------------------------------ | | `from` | Yes | The line handle to send from | | `to` | Yes | Recipient phone number, Apple ID, or chat ID (`cht_...` for [group chats](/docs/guides/group-chats)) | | `text` | Conditional | Message text. Required unless `attachments` is set. | | `attachments` | Conditional | Array of file IDs (max 1) from [`POST /v1/files`](/docs/guides/attachments). Required unless `text` is set. | | `reply_to` | No | Message ID (`msg_...`) or iMessage GUID to thread the message as a reply. | ## Reply to a specific message Pass the original message's `id` or `guid` as `replyTo` to thread your reply underneath it in the recipient's conversation: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: "Got it!", replyTo: "msg_abc123", }); ``` ## Group chats Pass a chat ID (`cht_...`) returned by [`listChats`](/docs/api-reference/chats/list-chats) as `to`: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.sendMessage({ from: "+15551234567", to: "cht_abc123", text: "Hey team!", }); ``` The contact-first rule below applies to group chats too — the chat must have at least one inbound message before you can send into it. See [Group chats](/docs/guides/group-chats) for the full flow. ## Contact-first restriction To keep lines healthy with Apple's spam detection, you can only send to a contact (or group chat) **after** they have messaged your line first. Trying to send first returns: ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "error": { "type": "invalid_request_error", "code": "contact_has_not_messaged", "message": "Cannot send to a contact who has not messaged this line first.", "param": "to" } } ``` The sandbox line is exempt once activated — your paired phone number is treated as having messaged in. For production lines, drive inbound traffic via marketing channels (a tap-to-text link, a vCard with your line saved as a contact, etc.) before you can reply. ## Track delivery Register a webhook for `message.sent` and your server will receive a POST when the message is delivered: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { verifyWebhook } from "@messages-dev/sdk"; app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], "your_webhook_secret", ); if (event.event === "message.sent") { console.log(`Delivered: ${event.data.id}`); } res.sendStatus(200); }); ``` | Status | Meaning | | --------- | ----------------------------------------- | | `pending` | Queued for delivery | | `claimed` | Being processed | | `sent` | Delivered | | `failed` | Delivery failed (check the `error` field) | ## Errors | Status | Code | Cause | | ---------------------------------------------------- | ---------------------------- | ---------------------------------------------------------------------- | | 400 | `missing_required_parameter` | Missing `from`, `to`, or both `text` and `attachments` | | 400 | `invalid_parameter_value` | `attachments` is malformed (e.g. wrong ID prefix or more than 1 entry) | | 401 | `missing_api_key` | No `Authorization` header | | 403 | `insufficient_scope` | Key lacks `messages:write` scope | | 403 | `line_not_accessible` | Key can't access this line | | 403 | `contact_has_not_messaged` | The recipient (or chat) hasn't messaged your line first | | 404 | `line_not_found` | Invalid line handle | | 404 | `chat_not_found` | The `cht_...` ID doesn't exist on this line | | 404 | `file_not_found` | An attachment file ID doesn't exist | | 404 | `message_not_found` | `reply_to` references a message that doesn't exist | | With the SDK, errors are thrown as typed exceptions: | | | ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient, InvalidRequestError } from "@messages-dev/sdk"; try { await client.sendMessage({ from: "+15551234567", to: "+1555...", text: "Hi" }); } catch (err) { if (err instanceof InvalidRequestError) { console.error(err.code, err.param); } } ``` # Typing Indicators Source: https://messages.dev/docs/guides/typing-indicators Send and receive typing indicators Typing indicators show the "..." bubble in the recipient's iMessage conversation. You can send them to signal that your bot or integration is composing a response, and receive them via webhooks when someone is typing to you. ## Send a typing indicator ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); await client.startTyping({ from: "+15551234567", to: "+15559876543", }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/typing" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "+15559876543" }' ``` The indicator appears for a few seconds. To stop it before it expires naturally: ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.stopTyping({ from: "+15551234567", to: "+15559876543", }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/typing" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "+15559876543", "state": "off" }' ``` ## Common pattern: type while processing Show a typing indicator while your bot generates a response, then send the message: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const client = createClient(); await client.startTyping({ from: "+15551234567", to: "+15559876543", }); const reply = await generateReply(incomingMessage); await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: reply, }); ``` ## Receive typing indicators via webhooks Subscribe to `typing.started` and `typing.stopped` events: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { verifyWebhook } from "@messages-dev/sdk"; app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], "your_webhook_secret", ); if (event.event === "typing.started") { console.log(`${event.data.handle} is typing...`); } if (event.event === "typing.stopped") { console.log(`${event.data.handle} stopped typing`); } res.sendStatus(200); }); ``` ## Get current typing status Check who is currently typing in a chat: ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const indicators = await client.listTypingIndicators({ from: "+15551234567", to: "+15559876543", }); for (const ind of indicators.data) { if (ind.isTyping) { console.log(`${ind.handle} is typing`); } } ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl "https://api.messages.dev/v1/typing?from=+15551234567&to=+15559876543" \ -H "Authorization: Bearer sk_live_..." ``` # Introduction Source: https://messages.dev/docs/introduction The iMessage API for agents Messages.dev is the iMessage API for agents. Send and receive messages, attachments, audio messages, reactions, typing indicators, and read receipts over a simple REST API or [TypeScript SDK](/docs/sdk). Text, attachments, and threaded replies. Group chats supported. Get notified instantly via signed webhooks when messages arrive. Native iMessage waveform balloons, with on-device transcription on inbound voice memos. Send rich vCards the recipient can save with one tap. Send and receive iMessage reactions (love, like, laugh, emphasize, etc.). Send typing indicators and mark conversations as read. ## What you can do | Capability | How | Reference | | --------------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------- | | Send text | `POST /v1/messages` | [Send a message](/docs/guides/send-message) | | Send attachments (images, video, docs) | `POST /v1/files` then `POST /v1/messages` | [Attachments](/docs/guides/attachments) | | Send native audio messages | `POST /v1/files` then `POST /v1/audio-messages` | [Audio messages](/docs/guides/audio-messages) | | Send vCard contact cards | `client.sendContactCard(...)` | [Contact cards](/docs/guides/contact-cards) | | Reply to a specific message | `reply_to` field on `POST /v1/messages` | [Send a message](/docs/guides/send-message#reply-to-a-specific-message) | | Send into group chats | Pass a `cht_...` chat ID as `to` | [Group chats](/docs/guides/group-chats) | | Send reactions | `POST /v1/reactions` | [Reactions](/docs/guides/reactions) | | Send typing indicators | `POST /v1/typing` | [Typing indicators](/docs/guides/typing-indicators) | | Mark a chat as read | `POST /v1/receipts` | [Read receipts](/docs/guides/read-receipts) | | Receive messages, reactions, typing, receipts | Webhooks (HMAC-signed) | [Webhooks](/docs/concepts/webhooks) | | Receive voice memos with transcription | `message.received` with `is_audio_message: true` | [Audio messages › Receive](/docs/guides/audio-messages#receive-an-audio-message) | | Track delivery | `GET /v1/outbox` or `message.sent` webhook | [Send a message › Track delivery](/docs/guides/send-message#track-delivery) | **Contact-first.** Outside the sandbox, the recipient must message your line before you can send to them. See [Send a message › Contact-first restriction](/docs/guides/send-message#contact-first-restriction). ## How it works 1. **Sign up** at [app.messages.dev](https://app.messages.dev) and create an API key 2. **Activate your sandbox**: text an activation code to the sandbox number to pair your phone 3. **Send** messages, reactions, and typing indicators via the [TypeScript SDK](/docs/sdk) (recommended) or the REST API directly 4. **Receive** incoming messages and events in real time via webhooks The TypeScript SDK is the recommended way to integrate. It wraps every endpoint with a typed client, handles cursor pagination, throws typed errors, and verifies webhook signatures correctly out of the box. For local development and one-off scripting, the [`messages-dev` CLI](/docs/cli) is the fastest path. [`listen --forward-to `](/docs/cli#forward-live-events-to-a-local-webhook-handler) streams live events into a local handler with the same HMAC headers production webhooks use, so you can build and test webhook handlers without ngrok or a registered webhook. ```typescript TypeScript (recommended) theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); // reads MESSAGES_API_KEY await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: "Hello from Messages.dev!", }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/messages" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{"from": "+15551234567", "to": "+15559876543", "text": "Hello from Messages.dev!"}' ``` Not on TypeScript? Every example in these docs ships a `curl` tab too — the SDK is a convenience layer, not a requirement. ```json theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} { "event": "message.received", "data": { "id": "msg_abc123", "sender": "+15559876543", "text": "Hey, got your message!", "sent_at": 1710000005000 } } ``` ## Key concepts | Concept | Description | | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Lines** | Your iMessage phone numbers or Apple IDs. Each line is a separate iMessage account. [Scale across multiple lines](/docs/scaling/multiple-lines) once one isn't enough. | | **Chats** | Conversations on a line, identified by the recipient's phone number or Apple ID. | | **Webhooks** | HTTPS callbacks that notify your server when events happen (new message, delivery confirmation, etc.). | | **API keys** | Bearer tokens you create in the [dashboard](https://app.messages.dev). Keys have configurable scopes and optional line restrictions. | ## Get started Send your first message in 5 minutes Recommended for TypeScript / Node.js `messages-dev` — send from your terminal and stream live events into a local handler. Best path for local dev. Use the API directly from any language ## Going to production Per-line throughput and daily volume guidance. Scale by spreading users across more lines. # Quickstart Source: https://messages.dev/docs/quickstart Send your first iMessage in 5 minutes ## 1. Create an account & get your API key Sign up at [app.messages.dev](https://app.messages.dev), then go to **API Keys** in the sidebar and click **Create Key**. Copy the key. It starts with `sk_live_` and is only shown once. Store your API key somewhere safe. It won't be displayed again. If you lose it, revoke it from the dashboard and create a new one. ## 2. Activate your sandbox Go to the **Lines** page in your dashboard. You'll see a sandbox card with a QR code and an activation code. Scan the QR code with your phone (it opens a pre-filled text message) or manually text the code to the sandbox number. Once your message is received, your sandbox is activated and your phone number is paired. You get **50 free messages per day**. The sandbox is a shared iMessage line for testing. For production use, set up a dedicated line. ## 3. Install the SDK (optional) ```bash npm theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} npm install @messages-dev/sdk ``` ```bash pnpm theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} pnpm add @messages-dev/sdk ``` ```bash yarn theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} yarn add @messages-dev/sdk ``` ```bash bun theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} bun add @messages-dev/sdk ``` The SDK is optional. You can use any HTTP client or `curl` instead. All examples below show both. ## 4. Send a message Every message is sent **from** a line. If you activated the sandbox, use the sandbox line handle and your paired phone number. You can find your line handle on the **Lines** page in the dashboard. ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: "Hello from Messages.dev!", }); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl -X POST "https://api.messages.dev/v1/messages" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "from": "+15551234567", "to": "+15559876543", "text": "Hello from Messages.dev!" }' ``` That's it. Your first message is on its way. ## 5. Receive messages ### Local development: use the CLI The fastest way to receive messages while you're building is the [`messages-dev` CLI](/docs/cli). It streams events from your account and POSTs them at a local URL with the same HMAC headers production webhooks use, so you can develop and test your handler without ngrok, a public URL, or a registered webhook. [Install the CLI and authenticate](/docs/cli#install), then: ```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} messages-dev listen --forward-to http://localhost:3000/webhooks ``` The CLI prints a per-session HMAC secret on first run. Use it as your webhook secret in development, or pin one with `MESSAGES_LISTEN_SECRET=…`. Prefer the standard webhook path? Expose your local server with [ngrok](https://ngrok.com), Cloudflare Tunnel, or any tunnel of your choice and register a real webhook pointing at the public URL. The handler code below is identical either way. See [Receive Messages](/docs/guides/receive-messages) for the full breakdown. Then handle incoming events on your server exactly as you would in production: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { verifyWebhook } from "@messages-dev/sdk"; app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], process.env.WEBHOOK_SECRET!, ); if (event.event === "message.received") { console.log(`${event.data.sender}: ${event.data.text}`); } res.sendStatus(200); }); ``` ### Production: register a webhook For production, [register a webhook](/docs/concepts/webhooks#creating-a-webhook) so messages.dev delivers events directly to your public URL. The handler code above is unchanged; only the secret and the source of the deliveries differ. See [Webhooks](/docs/concepts/webhooks) for the full event list, payload shapes, and signature verification details. ## 6. List your lines (optional) If you need to look up your line handles programmatically: ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.listLines(); ``` ```bash curl theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} curl https://api.messages.dev/v1/lines \ -H "Authorization: Bearer sk_live_..." ``` ## Next steps Delivery tracking and error handling Webhooks for real-time message delivery Full SDK reference: pagination, error handling, types All endpoints # Limits Source: https://messages.dev/docs/scaling/limits Per-line throughput and daily volume guidance Apple doesn't publish iMessage rate limits, but the signals their spam detection watches are well understood. Messages.dev is built around **inbound-first** conversations because that's the pattern that stays comfortably under those signals. The numbers below are the safe operating points we recommend per line. Only the API request rate is enforced by Messages.dev. The per-line message numbers are guidance reflecting Apple's unpublished thresholds — exceeding them won't return a 429, it raises the risk of Apple silently throttling or banning the underlying line. ## Per-line limits | Limit | Value | | ------------------------------------------- | ------------------ | | Throughput per line | 1 message / second | | Inbound-initiated unique contacts / day | 1,000 | | Replies inside a 24h conversation window | unlimited | | Outbound to contacts > 24h since last reply | 200 / day | | Max unanswered messages to a single contact | 5 | | Healthy outbound : inbound ratio | ≤ 10 : 1 | | API requests / hour per key | 1,000 | A conversation is **inbound-initiated** when the recipient texted your line first. Replies inside 24 hours of their last message are effectively unconstrained. Once the 24-hour window lapses, follow-ups count against the 200 / day reach-out budget. ## Signals Apple watches Treat the table above as the safe envelope for these levers. Drift on any of them and the ceilings effectively shrink: * **Send-to-receive ratio.** A line that mostly talks and rarely listens looks like a spammer. Keep it within roughly 10:1. * **Unanswered messages to a single contact.** Stop after about 5 messages with no reply on the same thread. * **Daily volume.** Volume itself isn't the problem; volume combined with low recipient diversity or a poor reply ratio is. * **Recipient diversity.** Lots of brand-new recipients in a short window reads as a blast. * **Spam reports.** A handful of "Report Junk" taps on a single line can trigger restrictions within hours, with no appeals process. ## What happens when you hit a limit There are two failure modes, and they look different: 1. **Messages.dev API limit (1,000 req / hour per key).** You get a [`rate_limit_error`](/docs/concepts/errors#rate-limit-error-429) with a `Retry-After` header. Back off until that many seconds have passed. 2. **Apple-side throttling.** Silent. Sends start slowing down, getting delayed, or stop delivering altogether. There's no error code and no appeal — the only fix is to back off, fix the upstream pattern (ratio, unanswered messages, daily volume), and let the line cool down. If a line is consistently flirting with the per-line numbers, the answer isn't to push harder on that line. It's to scale horizontally across more lines. ## Warming up a new line A brand-new line has no history with Apple, and its first \~2 weeks are when it's most likely to get flagged. Ramp gradually: low volume the first few days, increase as the line accumulates real two-way conversations, and expect to operate well under the per-line numbers above until the line is established. Don't assume a fresh line can immediately match an older line's volume. ## Next Add more lines and spread users across them when one line isn't enough. # Multiple lines Source: https://messages.dev/docs/scaling/multiple-lines Scale by adding lines and spreading users across them A single line has a ceiling (see [Limits](/docs/scaling/limits)). The way to scale beyond it is to add more lines and spread your users across them. ## When to add a line Add a second (or third, or tenth) line when: * Sustained traffic on an existing line is approaching the per-line numbers. * A single-line outage would be unacceptable — you want a line that can take over if one gets flagged or its underlying Apple ID needs to re-auth. * You're running multiple distinct products or brands and want clean separation between them. ## Spread users across lines Each user should be assigned to one line, and the assignment should be **stable**: the same user always lands on the same line so their conversation history stays continuous. How you assign users is up to you. The send API requires you to specify `from` on every call, so the routing decision lives in your code: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); // Pick a line for this user. Whatever logic you use, keep it stable // so the same user always ends up on the same line. const line = pickLineForUser(userId); await client.sendMessage({ from: line, to: userPhone, text: "Hey!", }); ``` A few practical notes: * **Keep traffic balanced.** If one line carries 80% of users, you've still only got the throughput of that one line. * **Monitor each line independently.** The outbound:inbound ratio, daily volume, and unanswered-message counts from [Limits](/docs/scaling/limits) apply per line, not aggregated across your account. * **Treat new lines as new lines.** A line that's been in use for 6 months isn't comparable to one provisioned yesterday. Ramp new ones up gradually. You can scope an API key to specific lines using the `lineIds` field when creating the key. This is useful if different parts of your stack should only be able to send from a subset of lines. ## Backup lines via contact cards A contact card can carry more than one phone number. If you deliver a vCard with both your primary line and a backup line, the user saves **both** to their contacts. If your primary line is ever throttled, unreachable, or being warmed back up, the user already has the backup saved and can text it directly: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.sendContactCard({ from: "+15550000001", to: userPhone, firstName: "Acme", lastName: "Support", phones: [ { type: "cell", value: "+15550000001" }, // primary { type: "main", value: "+15550000002" }, // backup ], }); ``` Send this once during onboarding (or any other moment where it's natural for the user to save your contact). From then on, both numbers live in their address book and they can fall back to the backup if your primary line goes quiet. See [Contact cards](/docs/guides/contact-cards) for the full vCard reference. # TypeScript SDK Source: https://messages.dev/docs/sdk Official TypeScript/Node.js client library ## Install ```bash npm theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} npm install @messages-dev/sdk ``` ```bash pnpm theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} pnpm add @messages-dev/sdk ``` ```bash yarn theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} yarn add @messages-dev/sdk ``` ```bash bun theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} bun add @messages-dev/sdk ``` ## Initialize ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; const client = createClient(); ``` The client automatically reads `MESSAGES_API_KEY` from your environment. To pass a key explicitly: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const client = createClient({ apiKey: "sk_live_..." }); ``` ## Send a message ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: "Hello from Messages.dev!", }); ``` ## Receive messages via webhooks Create a webhook from the **Webhooks** page in your [dashboard](https://app.messages.dev) and copy the signing secret. Then handle incoming events on your server: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { verifyWebhook } from "@messages-dev/sdk"; app.post("/webhooks", async (req, res) => { const event = await verifyWebhook( req.body, req.headers["x-webhook-signature"], "your_webhook_secret", ); switch (event.event) { case "message.received": console.log(`New message from ${event.data.sender}: ${event.data.text}`); break; case "message.sent": console.log(`Message delivered: ${event.data.id}`); break; } res.sendStatus(200); }); ``` If the signature is invalid, `verifyWebhook` throws a `SignatureVerificationError`. ## List messages ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const messages = await client.listMessages({ from: "+15551234567", to: "+15559876543", }); ``` ## Reactions ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.sendReaction({ from: "+15551234567", to: "+15559876543", messageId: "msg_abc123", type: "love", }); const reactions = await client.listReactions({ messageId: "msg_abc123", }); ``` ## Typing indicators ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.startTyping({ from: "+15551234567", to: "+15559876543", }); await client.stopTyping({ from: "+15551234567", to: "+15559876543", }); ``` ## Read receipts ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.sendReadReceipt({ from: "+15551234567", to: "+15559876543", }); const receipts = await client.listReadReceipts({ from: "+15551234567", to: "+15559876543", }); ``` ## Files Upload files to send as message attachments: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const file = await client.uploadFile({ from: "+15551234567", file: Buffer.from(imageData), filename: "photo.jpg", mimeType: "image/jpeg", }); await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: "Check this out!", attachments: [file.id], }); const { url } = await client.getFileUrl({ id: "file_abc123" }); ``` ## Delivery tracking ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.getOutboxItem({ id: "obx_xyz789" }); ``` ## Lines ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const lines = await client.listLines(); for (const line of lines.data) { console.log(line.handle, line.service, line.isActive); } ``` ## Chats ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const chats = await client.listChats({ from: "+15551234567", }); for (const chat of chats.data) { console.log(chat.identifier, chat.name, chat.lastMessageAt); } ``` ## Webhooks ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} await client.createWebhook({ from: "+15551234567", url: "https://example.com/webhooks", events: ["message.received", "message.sent"], }); const webhooks = await client.listWebhooks({ from: "+15551234567", }); await client.deleteWebhook({ id: "wh_abc123" }); ``` ## Pagination List methods return a page object with `data`, `hasMore`, and `nextCursor`. Use `for await...of` to iterate through all results: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const page = await client.listMessages({ from: "+15551234567", to: "+15559876543", limit: 10, }); if (page.hasMore) { const nextPage = await client.listMessages({ from: "+15551234567", to: "+15559876543", cursor: page.nextCursor, }); } const messages = await client.listMessages({ from: "+15551234567", to: "+15559876543", }); for await (const message of messages) { console.log(message.text); } ``` ## Error handling All errors extend `MessagesError` and include the error type, code, and message from the API: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient, AuthenticationError, AuthorizationError, InvalidRequestError, NotFoundError } from "@messages-dev/sdk"; try { await client.sendMessage({ from: "+15551234567", to: "+15559876543", text: "Hello!", }); } catch (err) { if (err instanceof AuthenticationError) { console.error("Bad API key:", err.code); } else if (err instanceof AuthorizationError) { console.error("Forbidden:", err.code); } else if (err instanceof InvalidRequestError) { console.error("Bad request:", err.code, err.param); } else if (err instanceof NotFoundError) { console.error("Not found:", err.code); } } ``` Every error includes: | Property | Type | Description | | ----------- | --------------------- | ---------------------------------------------- | | `type` | `string` | Error category (e.g. `authentication_error`) | | `code` | `string` | Machine-readable code (e.g. `invalid_api_key`) | | `message` | `string` | Human-readable explanation | | `param` | `string \| undefined` | The parameter that caused the error | | `status` | `number` | HTTP status code | | `requestId` | `string` | Unique request ID for debugging | ## Configuration All options are passed to `createClient`: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} const client = createClient({ apiKey: "sk_live_...", baseUrl: "https://api.messages.dev", timeout: 30_000, maxRetries: 2, }); ``` ## TypeScript The SDK is written in TypeScript and exports types for all resources: ```typescript theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}} import { createClient } from "@messages-dev/sdk"; import type { Line, Chat, Message, Reaction, Webhook, OutboxItem, WebhookEvent, } from "@messages-dev/sdk"; ```