# Send iMessage with Python

> Send and receive iMessages from Python using the Blooio REST API, `requests`, Flask webhooks, attachments, group chats, sender selection, and delivery-status tracking.

Source: https://blooio.com/guides/send-imessage-python

## Overview

Apple does not expose a public iMessage API. Blooio provides a REST API that Python applications can use to send and receive iMessages through standard HTTP calls.

Use API keys only from trusted backend environments. Do not expose API keys in browser-based applications.

## Prerequisites

- Python 3.7 or later
- `pip`
- A Blooio API key from [app.blooio.com](https://app.blooio.com)
- An active Blooio number

Install the example dependencies:

```bash
pip install requests flask
```

API base URL:

```text
https://api.blooio.com/v2/api
```

## Quick Start

Send a message to an E.164-formatted phone number. The `chatId` path parameter must be URL-encoded.

```python
import requests
from urllib.parse import quote

API_KEY = "your-api-key"
BASE = "https://api.blooio.com/v2/api"

to = quote("+15551234567")

response = requests.post(
    f"{BASE}/chats/{to}/messages",
    headers={"Authorization": f"Bearer {API_KEY}"},
    json={"text": "Hello from Python!"},
)

response.raise_for_status()
print(response.json())
```

For example, `+15551234567` becomes `%2B15551234567` in the URL path. A successful response can include a message ID and an initial `queued` status.

## Sending Messages

### Text Messages

```python
import requests
from urllib.parse import quote

API_KEY = "your-api-key"
BASE = "https://api.blooio.com/v2/api"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

def send_text(to: str, text: str):
    chat_id = quote(to)

    response = requests.post(
        f"{BASE}/chats/{chat_id}/messages",
        headers=HEADERS,
        json={"text": text},
    )

    response.raise_for_status()
    return response.json()

result = send_text("+15551234567", "Meeting at 3pm tomorrow")
print(result)
```

### Attachments

Add an `attachments` array to the request body. Attachments can be URLs or objects with a URL and name.

```python
def send_with_attachment(to: str, text: str, file_url: str):
    chat_id = quote(to)

    response = requests.post(
        f"{BASE}/chats/{chat_id}/messages",
        headers=HEADERS,
        json={
            "text": text,
            "attachments": [file_url],
        },
    )

    response.raise_for_status()
    return response.json()

send_with_attachment(
    "+15551234567",
    "Here's the invoice",
    "https://example.com/invoice.pdf",
)
```

### Group Messages

For a multi-recipient group, use a comma-separated list of recipients as the URL-encoded `chatId`. Blooio creates or reuses an unnamed group for that recipient combination.

```python
def send_to_group(recipients: list, text: str):
    chat_id = quote(",".join(recipients))

    response = requests.post(
        f"{BASE}/chats/{chat_id}/messages",
        headers=HEADERS,
        json={"text": text},
    )

    response.raise_for_status()
    return response.json()

result = send_to_group(
    ["+15551234567", "+15559876543", "+15550001111"],
    "Team standup in 10 minutes",
)
print(result)
```

A group send response can include a `group_id`.

### Select a Sender Number

Use the `from_number` request-body field to select a specific sender from your Blooio number pool.

```python
def send_from_number(to: str, text: str, from_number: str):
    chat_id = quote(to)

    response = requests.post(
        f"{BASE}/chats/{chat_id}/messages",
        headers=HEADERS,
        json={
            "text": text,
            "from_number": from_number,
        },
    )

    response.raise_for_status()
    return response.json()

send_from_number(
    "+15551234567",
    "Hello!",
    "+15559999999",
)
```

## Receiving Messages with Flask Webhooks

Create a public webhook endpoint to receive inbound messages and message-status events.

```python
from flask import Flask, request

app = Flask(__name__)

@app.route("/webhook", methods=["POST"])
def handle_message():
    payload = request.json

    event = payload.get("type")
    data = payload.get("data", {})

    sender = data.get("sender")
    text = data.get("text")
    message_id = data.get("message_id")
    protocol = data.get("protocol")

    print(f"[{event}] {sender}: {text}")
    return "", 200

if __name__ == "__main__":
    app.run(port=5000)
```

Register a webhook with:

```text
POST /v4/webhooks
```

Example request body:

```json
{
  "url": "https://yourserver.com/webhook"
}
```

Each webhook subscription receives every event type. Switch on the top-level `type` field in the webhook handler.

For local development, expose the Flask server with:

```bash
ngrok http 5000
```

### Webhook Event Fields

| Field | Description |
|---|---|
| `type` | Event type, such as `message.received` |
| `data.message_id` | Blooio message identifier |
| `data.sender` | Contact phone number or email on inbound events |
| `data.recipient` | Your Blooio number on inbound events |
| `data.text` | Message body |
| `data.protocol` | `imessage`, `sms`, or `rcs` |
| `data.attachments` | Attached files or media |

This guide includes the following event types:

- `message.received`
- `message.sent`
- `message.delivered`
- `message.failed`
- `message.read`

## Build an Auto-Responder

Use inbound webhook events to reply to the sender.

```python
from flask import Flask, request
import requests as http
from urllib.parse import quote

app = Flask(__name__)

API_KEY = "your-api-key"
BASE = "https://api.blooio.com/v2/api"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

@app.route("/webhook", methods=["POST"])
def echo():
    payload = request.json

    if payload.get("type") != "message.received":
        return "", 200

    data = payload["data"]
    sender = data["sender"]
    text = data.get("text", "")

    chat_id = quote(sender)
    response = http.post(
        f"{BASE}/chats/{chat_id}/messages",
        headers=HEADERS,
        json={"text": f"You said: {text}"},
    )
    response.raise_for_status()

    return "", 200

if __name__ == "__main__":
    app.run(port=5000)
```

This pattern can call an AI model before replying. Automated messaging should be used only for consent-based person-to-person business conversations where the recipient expects to hear from the sender.

## Checking Delivery Status

Poll the message-status endpoint using the original chat ID and message ID, or use message-status webhooks.

```python
from urllib.parse import quote

def check_status(chat_id: str, message_id: str):
    encoded = quote(chat_id)

    response = requests.get(
        f"{BASE}/chats/{encoded}/messages/{message_id}/status",
        headers=HEADERS,
    )

    response.raise_for_status()
    return response.json()

result = send_text("+15551234567", "Hello!")
status = check_status("+15551234567", result["message_id"])
print(status)
```

Endpoint:

```text
GET /chats/{chatId}/messages/{messageId}/status
```

Status progression:

```text
queued → pending → sent → delivered
```

Failed messages have a `failed` status and can include an `error` field. Status responses can identify the protocol as `imessage`, `rcs`, or `sms`.

## Error Handling

| HTTP status | Meaning | Suggested action |
|---|---|---|
| `400` | Invalid phone-number format or missing required fields | Validate fields and URL-encode the E.164 `chatId` |
| `401` | Invalid or missing Bearer token | Check the `Authorization` header |
| `429` | Rate limited | Retry with exponential backoff |
| `503` | No active sender number | Confirm that at least one Blooio number is active |

The guide states a default rate limit of 60 requests per minute.

```python
import time
import requests
from urllib.parse import quote

def send_with_retry(to: str, text: str, max_retries: int = 3):
    chat_id = quote(to)

    for attempt in range(max_retries):
        response = requests.post(
            f"{BASE}/chats/{chat_id}/messages",
            headers=HEADERS,
            json={"text": text},
        )

        if response.status_code in (200, 202):
            return response.json()

        if response.status_code == 429:
            wait = 2 ** attempt
            time.sleep(wait)
            continue

        if response.status_code == 401:
            raise ValueError("Invalid API key — check your Bearer token")

        response.raise_for_status()

    raise RuntimeError("Maximum retries exceeded")
```

## Safe Sending

Blooio is a consent-based P2P business messaging platform, not an unsolicited mass-outreach service.

Appropriate use cases include:

- Customer support
- Appointment confirmations
- Conversations with booked leads
- Opted-in sales follow-up

Do not use the API for unsolicited mass outreach. Messaging safety controls, organization outbound limits, recipient opt-outs, and Apple policies apply to all plans.

Blooio supports dedicated or shared iMessage numbers with automatic RCS-to-SMS fallback through the same API and webhook surface.

## Frequently Asked Questions

### Can Python send iMessages directly?

No. Apple does not provide a public iMessage API. Python applications can use Blooio's REST API to send and receive iMessages through standard HTTP calls.

### Is there a free iMessage API for Python?

iMessage is a proprietary Apple protocol rather than a free public API. Blooio provides a free trial with 20 messages and no credit card required. See [pricing](https://blooio.com/pricing.md) for current plans and limits.

### Can Python use AppleScript to send iMessages?

Python can invoke AppleScript through `subprocess` on a Mac signed in to iMessage. That approach works locally on macOS, cannot run as a typical server integration, and can be affected by macOS updates. Blooio's REST API works from Linux, Windows, and macOS backend environments.

## Links

- HTML page: https://blooio.com/guides/send-imessage-python
- Markdown page: https://blooio.com/guides/send-imessage-python.md
- REST API integration: https://blooio.com/integrations/api.md
- Send iMessage programmatically: https://blooio.com/guides/send-imessage-programmatically.md
- Build an iMessage bot: https://blooio.com/guides/imessage-bot.md
- ChatGPT over iMessage: https://blooio.com/guides/chatgpt-imessage.md
- Pricing: https://blooio.com/pricing.md
- API documentation: https://docs.blooio.com
- Get an API key: https://app.blooio.com
- LLM site index: https://blooio.com/llms.txt
