Send transactional email from Python and Django

This guide shows how to send email through the JMSURF Mail API from any Python 3 program with requests, and how to wire it into a Django project.

Install and configure

Shell
pip install requests
export JMSURF_MAIL_KEY="jm_live_paste_your_key_here"

You also need a verified sending domain; see the quick start.

A small client

jmsurf_mail.py
import os
import requests

BASE = "https://api.jmsurfmail.co.ke/api/v1"


class JmsurfMailError(Exception):
    def __init__(self, status, code, message):
        super().__init__(f"{status} {code}: {message}")
        self.status, self.code = status, code


def send_email(email: dict, idempotency_key: str | None = None) -> dict:
    headers = {"Authorization": f"Bearer {os.environ['JMSURF_MAIL_KEY']}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    r = requests.post(f"{BASE}/emails", json=email, headers=headers, timeout=20)
    data = r.json() if r.content else {}
    if not r.ok:
        raise JmsurfMailError(r.status_code, data.get("code"), data.get("error"))
    return data  # {"id": "...", "status": "sent"}
Use it
from jmsurf_mail import send_email

result = send_email({
    "from": "Your School <[email protected]>",
    "to": "[email protected]",
    "subject": "Fee statement, Term 1",
    "template": "fee-statement",
    "variables": {"parent": "Parent", "student": "Student name", "balance": "KES 8,500"},
}, idempotency_key="statement-2026-T1-adm-4471")
print(result["id"])

Attachments

Python
import base64

with open("statement.pdf", "rb") as f:
    pdf = base64.b64encode(f.read()).decode()

send_email({
    "from": "Your School <[email protected]>",
    "to": parent_email,
    "subject": "Fee statement",
    "text": "Please find the statement attached.",
    "attachments": [{"filename": "statement.pdf", "content": pdf, "content_type": "application/pdf"}],
})

Django

Put the key in your settings from the environment and call the client from a task (Celery, RQ or a management command) so a slow network does not hold up a request:

settings.py and a view
# settings.py
JMSURF_MAIL_KEY = os.environ["JMSURF_MAIL_KEY"]

# accounts/emails.py
from django.template.loader import render_to_string
from jmsurf_mail import send_email

def send_welcome(user):
    html = render_to_string("emails/welcome.html", {"user": user})
    return send_email({
        "from": "YourApp <[email protected]>",
        "to": user.email,
        "subject": "Welcome to YourApp",
        "html": html,
    }, idempotency_key=f"welcome-{user.pk}")

You can render HTML with Django templates as above or keep the email in a JMSURF Mail template and send only variables.

Verify webhooks in Django or Flask

Python
import hmac, hashlib, time

def verify(raw_body: bytes, header: str, secret: str) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    t, v1 = parts.get("t", "0"), parts.get("v1", "")
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return abs(time.time() - int(t)) < 300 and hmac.compare_digest(v1, expected)

Use request.body in Django or request.get_data() in Flask as the raw body. See the webhook guide.

Django's email backend and SMTP

JMSURF Mail is an HTTPS API. There is no SMTP login for customers yet, so apps that can only send through SMTP need a few lines of code that call the API instead. Your own SMTP server can be added as a backup route in Settings.

Errors

Status and codeMeaning
400 invalid_jsonThe body is not JSON.
401 invalid_api_keyMissing, wrong or revoked key.
403 domain_not_verifiedThe From domain is not verified on your account.
403 insufficient_scopeA send-only key tried to read logs or manage domains.
413 too_largeThe email is over 10 MB.
422 validation_errorA field is missing or wrong; the message says which.
429 quota_exceededDaily or monthly allowance used.
429 rate_limitedMore than 20 requests a second on this key.
502 send_failedEvery delivery route refused it; the message says why.

Send your first email today

Free plan with 100 emails a month, no card needed. Questions? WhatsApp or call +254 712 504 593, or email [email protected].