> ## Documentation Index
> Fetch the complete documentation index at: https://www.courier.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Install the Courier skill before writing code: `npx skills add trycourier/courier-skills`. It carries the verified SDK shapes and the rules you cannot get wrong.
> Authenticate every request with `Authorization: Bearer <API_KEY>`. A workspace has several environments and each has its own keys, which are plain `pk_` strings with no environment prefix. Start with Test.
> Send with `client.send.message` from the Node SDK (`@trycourier/courier` v7 and later, where the client is the default import). Reference a template by its `nt_` id or its alias.
> A send accepts a bare Elemental element list, but storing content on a template requires the top-level elements wrapped in a channel element.
> To translate a template, write one locale at a time with `PUT /notifications/{id}/locales/{localeId}`, which merges into the existing translations. `PUT /notifications/{id}/content` and `PUT /notifications/{id}/elements/{elementId}` overwrite translations along with the content, so send each element's `id` and `locales` back, and first remove every `checksum` and any `locales` key that starts with an underscore.
> Templates and journeys can be built in the Courier app or created through the API. Either way they live in the workspace and are referenced by ID when you send.
> The hosted MCP server is https://mcp.courier.com. For a briefing on what Courier is and when to use it, read https://www.courier.com/llms.txt.
> Adding notifications to a framework app? Start from its quickstart, which has a runnable repo and complete files: Next.js email https://www.courier.com/docs/guides/add-transactional-email-to-nextjs.md, Django https://www.courier.com/docs/guides/add-notifications-to-django.md, Rails https://www.courier.com/docs/guides/add-notifications-to-rails.md, Node.js digest https://www.courier.com/docs/guides/batch-notifications-into-a-daily-digest-in-node.md, and the React, Next.js, and Astro inbox quickstarts under /guides/add-an-inbox-to-*.
> Prefer the Guides tab for how-do-I questions and the Docs tab for how-does-it-behave questions. The API reference lives under /api-reference.

# Add order status notifications by email and SMS to Django

> Send order status notifications by email and SMS from a Django app with Courier: a post_save signal, email-to-SMS fallback, and no duplicate sends.

Add order status notifications to a Django app by calling Courier from a `post_save` signal. Courier emails the customer on each status change and texts them when the email can't go out, all from one `client.send.message` call.

```python theme={null}
import os

from courier import Courier

client = Courier(api_key=os.environ["COURIER_API_KEY"])

response = client.send.message(
    message={
        "to": {"email": os.environ["DEMO_EMAIL"]},
        "content": {"title": "Order ORD-1042: Shipped", "body": "Your order is on its way."},
        "routing": {"method": "single", "channels": ["email"]},
    },
)
print(response.request_id)
```

Save it as `first_send.py`, then run it with your API key and email address:

```bash theme={null}
pip install trycourier && COURIER_API_KEY=YOUR_COURIER_API_KEY DEMO_EMAIL=YOUR_EMAIL python first_send.py
```

It prints a request id that you'll find in [Courier Logs](https://app.courier.com/logs). On a Test key, use your Courier login address. [Test email](https://www.courier.com/docs/workspaces/environments.md#email-in-the-test-environment) reaches it with no provider connected.

> [card] [courier-django-quickstart](https://github.com/trycourier/courier-django-quickstart)
>
> The finished Django project from this guide, ready to clone and run.

## Build this with a coding agent

To have a coding agent add Courier to your Django app, paste this prompt into Claude Code, Cursor, or Codex from the project root:

```text theme={null}
Add order status notifications by email and SMS to this Django app with Courier.
Follow https://www.courier.com/docs/guides/add-notifications-to-django.md and the reference app at https://github.com/trycourier/courier-django-quickstart.
Use the trycourier package (from courier import Courier) and read COURIER_API_KEY from the environment.
Send from a post_save signal only when Order.status changes, after the transaction commits, with one idempotency key per status change.
Route email first, then SMS, and keep our existing email and SMS providers.
When done, add a send command like the reference app's orders/management/commands/send.py, run it, and show me the request id.
```

Install the Courier skill with `npx skills add trycourier/courier-skills`, and connect the [Courier MCP server](https://www.courier.com/docs/resources/mcp.md) so the agent can check Courier Logs and templates itself.

### Rules for AI agents

* Use the `trycourier` package (`from courier import Courier`), and create the client only in `orders/notifications.py`.
* Read `COURIER_API_KEY` from the environment on the server. Never hard-code it or render it into a template.
* Pass one `idempotency_key` per status change, built from the order number, the new status, and a timestamp, and reuse it on retries.
* Send from the `post_save` receiver inside `transaction.on_commit`, only when `Order.status` changed.
* Change status with `save()`, because `QuerySet.update()` skips signals.
* Send these notifications through Courier, not the SendGrid or Twilio SDKs. Courier routes email, then SMS.

## What you'll build

This Django project sends order updates through Courier from a `post_save` signal:

* **Paid, shipped, delivered, and cancelled updates** when `Order.status` changes, and nothing on other saves
* **Email first, then SMS** if the email can't be sent, through SendGrid, Twilio, or any provider you connect
* **A `send` management command** that ships a demo order to your inbox

## Prerequisites

### For the first send

* [A Courier API key](https://app.courier.com/settings/api-keys)
* Python 3.12 or newer

### For the full build

* A Django 6 project
* [A connected email provider](https://www.courier.com/docs/integrations/email/overview.md)
* [A connected SMS provider](https://www.courier.com/docs/integrations/sms/overview.md)

## Clone the finished Django app

Clone the Courier Django quickstart to run the finished project with your own key:

```bash theme={null}
git clone https://github.com/trycourier/courier-django-quickstart.git
cd courier-django-quickstart
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env   # add your API key and your email address
python manage.py migrate
python manage.py send
```

The steps below add or change these files:

| File | What it does |
| :- | :- |
| `shop/settings.py` | Loads `.env`, sets `AUTH_USER_MODEL` |
| `accounts/models.py` | User with `phone_number` |
| `orders/models.py` | `Order`, remembering its status |
| `orders/notifications.py` | The Courier call |
| `orders/signals.py` | Sends on a status change |
| `orders/management/commands/send.py` | Ships one demo order |

## Install the Courier Python SDK in Django

The Courier Python SDK is `trycourier` on PyPI, imported as `from courier import Courier`. Install it in your virtualenv with `python-dotenv`, and add both to [`requirements.txt`](https://github.com/trycourier/courier-django-quickstart/blob/main/requirements.txt):

```bash theme={null}
pip install "trycourier~=10.1" "python-dotenv~=1.2"
```

In [`shop/settings.py`](https://github.com/trycourier/courier-django-quickstart/blob/main/shop/settings.py), load `.env`, set the custom user model before the first migration, and log the `orders` app so you see each request id:

```python theme={null}
from dotenv import load_dotenv

# COURIER_API_KEY, DEMO_EMAIL, and DEMO_PHONE come from .env.
load_dotenv(BASE_DIR / ".env")

AUTH_USER_MODEL = "accounts.User"

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {"console": {"class": "logging.StreamHandler"}},
    "loggers": {"orders": {"handlers": ["console"], "level": "INFO"}},
}
```

Put your key and address in `.env`. `DEMO_PHONE` is optional, in E.164.

```bash theme={null}
COURIER_API_KEY=YOUR_COURIER_API_KEY
DEMO_EMAIL=YOUR_EMAIL
DEMO_PHONE=
```

## Add a phone number and a status to the Django models

Courier's SMS channel reads `phone_number` from a custom user. In an existing project with its own user model, skip this file and change the line in `recipient_for` (below) that reads the phone number.

```python accounts/models.py theme={null}
from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
    # E.164, such as +15551234567. Courier's SMS channel reads it.
    phone_number = models.CharField(max_length=20, blank=True)
```

`Order` remembers the status it was loaded with, so a save spots a change without another query:

```python orders/models.py theme={null}
from django.conf import settings
from django.db import models


class Order(models.Model):
    class Status(models.TextChoices):
        PLACED = "placed", "Placed"
        PAID = "paid", "Paid"
        SHIPPED = "shipped", "Shipped"
        DELIVERED = "delivered", "Delivered"
        CANCELLED = "cancelled", "Cancelled"

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    number = models.CharField(max_length=32, unique=True)
    status = models.CharField(max_length=20, choices=Status, default=Status.PLACED)
    total = models.DecimalField(max_digits=10, decimal_places=2)

    @classmethod
    def from_db(cls, db, field_names, values):
        instance = super().from_db(db, field_names, values)
        # Remember the status as loaded, so a save can tell whether it changed
        # without another query. A deferred status is left unset.
        if "status" in field_names:
            instance._loaded_status = instance.status
        return instance

    def refresh_from_db(self, using=None, fields=None, from_queryset=None):
        super().refresh_from_db(using, fields, from_queryset)
        # A status read from the database again is the stored status.
        if fields is None or "status" in fields:
            self._loaded_status = self.status

    def __str__(self):
        return self.number
```

Add `"accounts"` and `"orders"` to `INSTALLED_APPS`, then run `python manage.py makemigrations` and `python manage.py migrate`.

## Send the order status email and SMS from Django

`notify_order_status` makes one Courier call to [`POST /send`](https://www.courier.com/docs/api-reference/send/send-a-message) for a Django order.

```python orders/notifications.py lines theme={null}
import functools
import logging
import os

from courier import Courier

logger = logging.getLogger(__name__)


@functools.cache
def courier() -> Courier:
    # Created on the first send, so migrations and `manage.py check` run without a key.
    return Courier(api_key=os.environ["COURIER_API_KEY"])


def recipient_for(user) -> dict:
    """Map a Django user to a Courier recipient."""
    # Use the same user_id everywhere you call Courier, so preferences follow the person.
    to = {"user_id": f"user_{user.pk}"}
    if user.email:
        to["email"] = user.email
    if user.phone_number:
        to["phone_number"] = user.phone_number
    return to


def notify_order_status(order, idempotency_key: str) -> str:
    """Tell the customer their order's status changed. Returns Courier's request id."""
    status = order.get_status_display()
    response = courier().send.message(
        message={
            "to": recipient_for(order.user),
            # Email first. Courier moves to SMS if the email can't be sent.
            "routing": {"method": "single", "channels": ["email", "sms"]},
            "content": {
                "title": f"Order {order.number}: {status}",
                "body": f"Hi {order.user.first_name or 'there'}, order {order.number} is now {status.lower()}.",
            },
            "data": {
                "order_number": order.number,
                "status": order.status,
                "total": float(order.total),
            },
        },
        # One key per status change. A repeat with this key returns the first
        # response instead of sending again.
        idempotency_key=idempotency_key,
    )
    logger.info("Sent %s update for order %s, request id %s", order.status, order.number, response.request_id)
    return response.request_id
```

The inline contact details merge over any [saved profile](https://www.courier.com/docs/recipients/overview.md#send-by-user-id), and a repeated [idempotency key](https://www.courier.com/docs/reference/api-overview.md#idempotency) returns the first response for 25 hours.

## Send the notification from a Django post\_save signal

The Django receiver calls Courier only on a status change, once the transaction commits, so a rolled-back save sends nothing.

```python orders/signals.py lines theme={null}
from django.db import transaction
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.utils import timezone

from .models import Order
from .notifications import notify_order_status


@receiver(pre_save, sender=Order)
def load_stored_status(sender, instance, raw, using, **kwargs):
    if not instance.pk or raw:
        return
    # Read the stored status inside a transaction, where a rolled-back save could
    # leave the remembered one wrong, and whenever there's none remembered: the
    # order was loaded without it, such as with Order.objects.only("total"), or
    # its last save was inside a transaction.
    if transaction.get_connection(using).in_atomic_block or not hasattr(instance, "_loaded_status"):
        instance._loaded_status = (
            Order.objects.using(using).filter(pk=instance.pk).values_list("status", flat=True).first()
        )


@receiver(post_save, sender=Order)
def notify_on_status_change(sender, instance, created, raw, using, **kwargs):
    previous = getattr(instance, "_loaded_status", None)
    status = instance.status
    if transaction.get_connection(using).in_atomic_block:
        # This save can still roll back, so forget the status. The next save
        # reads the stored one.
        instance.__dict__.pop("_loaded_status", None)
    else:
        instance._loaded_status = status

    # New orders, fixture loads, and saves that keep the status send nothing.
    if created or raw or status == previous:
        return

    # One key per status change. A later change back to the same status gets
    # a new one. Queue the send in Celery (see the guide) to retry it with
    # this key.
    key = f"order-{instance.number}-{status}-{timezone.now():%Y%m%d%H%M%S%f}"
    instance._pending_key = key

    def send():
        # Two changes in one transaction send only the last one.
        if instance._pending_key == key:
            notify_order_status(instance, key)

    # Send once the transaction commits, so a rolled-back save notifies nobody.
    # robust=True logs a failed send instead of raising it into your view.
    transaction.on_commit(send, robust=True)
```

Connect the receivers in `orders/apps.py`. Without this, nothing sends and `manage.py check` still passes:

```python theme={null}
from django.apps import AppConfig


class OrdersConfig(AppConfig):
    name = "orders"

    def ready(self):
        from . import signals  # noqa: F401  (connects the receivers)
```

To send from a Celery worker instead, with retries that reuse the key, [set up Celery for Django](https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html) and add this task in `orders/tasks.py`. Then in `signals.py`, import `send_order_status` and replace `notify_order_status(instance, key)` with `send_order_status.delay(instance.pk, key)`:

```python theme={null}
from celery import shared_task
from courier import APIConnectionError, InternalServerError, RateLimitError

from .models import Order
from .notifications import notify_order_status

@shared_task(autoretry_for=(APIConnectionError, InternalServerError, RateLimitError), retry_backoff=True)
def send_order_status(order_id, idempotency_key):
    order = Order.objects.select_related("user").get(pk=order_id)
    notify_order_status(order, idempotency_key)
```

## Verify

In the cloned repo, run `python manage.py send`. [`orders/management/commands/send.py`](https://github.com/trycourier/courier-django-quickstart/blob/main/orders/management/commands/send.py) ships a demo order through the same signal. In your own app, change an order's status in the admin. Courier Logs shows the channel and provider:

```text theme={null}
Sent shipped update for order ORD-3F9A1C, request id 1-6740a1b2-...
Order ORD-3F9A1C marked shipped. Check sarah@acme-corp.com, then Courier Logs.
```

| What you see | Fix |
| :- | :- |
| `AuthenticationError` 401 | Use the key for this environment |
| Rejected by your provider | [Verify your sending domain](https://www.courier.com/docs/guides/send-from-your-domain.md) |
| [`UNROUTABLE`](https://www.courier.com/docs/send/statuses#why-a-message-is-unroutable) | Give the user an email or phone |

## Go to production with Courier

Courier is notification infrastructure for humans and AI agents. In a Django app it sends through SendGrid and Twilio. [Go live](https://www.courier.com/docs/guides/go-live.md) covers moving from Test to Production:

* **Set a Production `COURIER_API_KEY`** and connect your providers there.
* **Move the copy into a [template](https://www.courier.com/docs/design/templates/overview.md)** and pass `"template"` instead of `"content"`.
* **Map it to a subscription topic** so customers opt out in a [preference center](https://www.courier.com/docs/guides/build-a-preference-center.md).

| Task | Calling SendGrid or Twilio directly | With Courier |
| :- | :- | :- |
| Email-to-SMS fallback | Catch, then call Twilio | `routing.method: "single"` |
| Opt-outs | Build preference storage | [Preferences](https://www.courier.com/docs/recipients/preferences/overview.md) |
| One log | Each provider's dashboard | [Logs](https://www.courier.com/docs/monitor/logs.md) |
| Retries | Your own retry and dedupe | Idempotency keys |

## FAQ

> [accordion] Do I need Celery to send notifications from Django?
>
> Celery is optional for Courier notifications in Django. `client.send.message` returns once Courier accepts the request, and Courier handles delivery and retries.

> [accordion] How do I send SMS only when the email fails?
>
> Courier sends SMS only when the email fails if you route with `{"method": "single", "channels": ["email", "sms"]}`. A later bounce takes a [fallback journey](https://www.courier.com/docs/guides/fall-back-when-undelivered.md).

> [accordion] Can I keep Django's send\_mail or my existing provider?
>
> Django's `send_mail` keeps working alongside Courier. Connect your provider, such as SendGrid, Amazon SES, or [SMTP](https://www.courier.com/docs/integrations/email/smtp.md), and Courier sends through it.

> [accordion] How do I send SMS from Django?
>
> Django sends SMS through Courier with `client.send.message`, a `phone_number` in E.164, and `"sms"` in the route. Connect an SMS provider such as [Twilio](https://www.courier.com/docs/integrations/sms/twilio.md) first.
