Django email API: send transactional email from Django

Updated

There is no Django-specific Inboxili package. Use the official Python package (inboxili) from a service module, as shown below.

Django's send_mail goes through EMAIL_BACKEND, which is SMTP by default. Inboxili is API-only, so you call it from a service function instead.

Settings

settings.py:

import os

INBOXILI_API_KEY = os.environ["INBOXILI_API_KEY"]
INBOXILI_BASE_URL = os.environ.get("INBOXILI_BASE_URL", "https://api.inboxili.com/api/v1")
INBOXILI_FROM_EMAIL = os.environ.get("INBOXILI_FROM_EMAIL", "hello@yourdomain.com")
INBOXILI_FROM_NAME = "Acme"

Install and add a service module

pip install inboxili

mail/inboxili.py:

from django.conf import settings
from inboxili import Inboxili, InboxiliError  # re-exported for callers

_client = None


def client() -> Inboxili:
    global _client
    if _client is None:
        _client = Inboxili(settings.INBOXILI_API_KEY, base_url=settings.INBOXILI_BASE_URL)
    return _client


def send(**message):
    message.setdefault("from_email", settings.INBOXILI_FROM_EMAIL)
    message.setdefault("from_name", settings.INBOXILI_FROM_NAME)
    return client().emails.send(**message)

See the Python integration for the package's options and error types.

Send from a Celery task

from celery import shared_task
from django.contrib.auth import get_user_model
from mail import inboxili


@shared_task(bind=True, max_retries=0)  # a retry after a timeout could send a duplicate
def send_welcome_email(self, user_id):
    user = get_user_model().objects.get(pk=user_id)
    try:
        inboxili.send(
            to=user.email,
            subject="Welcome, {{first_name}}",
            html_body="<p>Hi {{first_name}}, your account is ready.</p>",
            template_data={"first_name": user.first_name or "there"},
        )
    except inboxili.InboxiliError as e:
        # The package already retried HTTP 429 twice. Everything else will fail the same way again.
        raise

Trigger it after the transaction commits so the task never runs against a user row that was rolled back:

from django.db import transaction

transaction.on_commit(lambda: send_welcome_email.delay(user.pk))

Error handling

| status | code | Do | |---|---|---| | 401 | unauthorized | Check the key. | | 403 | forbidden | Check scope and IP rules. | | 422 | validation_error, sender_not_verified, send_failed | Fix the request. | | 429 | rate_limited | The package retries twice; queue and pace bulk sends. |

InboxiliConnectionError (a timeout or network failure) means the outcome is unknown. With no idempotency key, retrying it can send a second email.

Testing

from unittest.mock import patch, MagicMock
from django.test import TestCase, override_settings
from mail import inboxili


@override_settings(INBOXILI_API_KEY="ik_live_test")
class InboxiliTests(TestCase):
    def test_send(self):
        fake = MagicMock()
        fake.emails.send.return_value = MagicMock(message_id="m1")
        with patch("mail.inboxili.client", return_value=fake):
            out = inboxili.send(to="a@b.co", subject="s", html_body="<p>x</p>")
        self.assertEqual(out.message_id, "m1")
        self.assertEqual(fake.emails.send.call_args.kwargs["to"], "a@b.co")

Production notes

  • Keep the key in the environment, not in settings.py.
  • Keep Django's EMAIL_BACKEND for admin error mails, if you use them, but be aware those do not go through Inboxili.
  • Webhooks: use a csrf-exempt view and compute the hex HMAC-SHA256 of request.body with your webhook secret and compare it to the X-Inboxili-Signature header using hmac.compare_digest.

Troubleshooting

| Symptom | Cause | Fix | |---|---|---| | KeyError: INBOXILI_API_KEY at startup | Variable not set where Django runs | Export it for the process (systemd unit, container env), not just your shell. | | 401 unauthorized | Wrong or revoked key | Create a new key in Settings, Developer. | | 422 sender_not_verified | INBOXILI_FROM_EMAIL is not on a verified domain | Verify the domain and add the sender. | | Task ran before the row existed | Task queued inside an uncommitted transaction | Queue with transaction.on_commit. | | send_mail() does not use Inboxili | Django's EMAIL_BACKEND is SMTP; Inboxili has no SMTP endpoint | Call the service function instead. | | Duplicate emails | A task retried after a timeout | Keep max_retries=0 or record a sent flag before retrying. |

Frequently asked questions

Can I use Django's send_mail with Inboxili?
Not directly. send_mail goes through an EMAIL_BACKEND, and Inboxili has no SMTP endpoint. You could write a custom backend that calls the API, but it could not carry attachments, CC or BCC because the API has no fields for them.

Official SDKs

Build with Inboxili

Create a workspace, verify a domain, and make your first API call.

Related