Quick Start: Django Email Webhook
JsonHook delivers every inbound email as a JSON POST request to your webhook endpoint. Setting up a Django handler takes less than 5 minutes. Start by initializing your project:
pip install django && django-admin startproject myproject && cd myproject
Then create your webhook endpoint. The following example shows the minimal code needed to receive and acknowledge a JsonHook delivery:
# views.py
import json
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
@csrf_exempt
@require_POST
def webhook(request):
payload = json.loads(request.body)
email = payload['email']
print(f"Email from: {email['from']} | Subject: {email['subject']}")
return HttpResponse(status=200)
# urls.py
# path('webhook/', views.webhook, name='webhook'),
Point your JsonHook address webhook URL to this endpoint and you will start receiving parsed emails as JSON within seconds of the email arriving.
Full Django Implementation
The quick start example above is enough to get started, but a production implementation should include signature verification, structured error handling, and proper HTTP response codes. The complete example below demonstrates all of these patterns together.
This implementation verifies the X-JsonHook-Signature header to confirm the request genuinely came from JsonHook, parses the full email payload, and returns the appropriate HTTP status codes to trigger or suppress retries.
# views.py
import hmac
import hashlib
import json
import os
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import logging
logger = logging.getLogger(__name__)
WEBHOOK_SECRET = os.environ.get("JSONHOOK_WEBHOOK_SECRET", "").encode()
def verify_signature(raw_body: bytes, sig_header: str) -> bool:
if not sig_header:
return False
computed = hmac.new(WEBHOOK_SECRET, raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(computed, sig_header)
@csrf_exempt
@require_POST
def webhook(request):
sig = request.META.get("HTTP_X_JSONHOOK_SIGNATURE", "")
# request.body contains the raw POST bytes in Django
if not verify_signature(request.body, sig):
logger.warning("Invalid JsonHook signature")
return JsonResponse({"error": "Unauthorized"}, status=401)
try:
payload = json.loads(request.body)
except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON"}, status=400)
email = payload["email"]
timestamp = payload["timestamp"]
address = payload["address"]
logger.info(f"[{timestamp}] Email at {address} from {email['from']}")
logger.info(f"Subject: {email['subject']}")
for att in email.get("attachments", []):
logger.info(f"Attachment: {att['filename']} ({att['size']} bytes)")
return HttpResponse(status=200)
The webhook handler returns 200 immediately after queuing the email for processing. Avoid doing expensive work (database writes, API calls) synchronously inside the handler — process the payload in a background job to stay within JsonHook's 10-second response timeout.
Build Your Django Email Integration
Free API key — start receiving webhooks in 5 minutes.
Get Free API KeyParsing the Webhook Payload
Every JsonHook delivery is an HTTP POST with Content-Type: application/json. The payload follows a consistent schema regardless of the originating email client or provider:
import json
# Django: request.body is the raw bytes, always available in views
payload = json.loads(request.body)
event = payload["event"] # "email.received"
timestamp = payload["timestamp"]
address = payload["address"]
email = payload["email"]
from_addr = email["from"]
to = email["to"] # list of strings
subject = email["subject"]
text_body = email["textBody"]
html_body = email.get("htmlBody", "")
for att in email.get("attachments", []):
print(att["filename"], att["contentType"], att["size"])
Key fields in the payload:
- event — Always
"email.received"for inbound email events - timestamp — ISO 8601 timestamp of when JsonHook received the email
- address — The JsonHook inbound address that received the email (e.g.,
[email protected]) - email.from — Sender address string, e.g.,
"Alice <[email protected]>" - email.to — Array of recipient address strings
- email.subject — Email subject line
- email.textBody — Plain text body of the email (may be empty if HTML-only)
- email.htmlBody — HTML body of the email (may be empty if plain-text-only)
- email.attachments — Array of attachment objects, each with
filename,contentType,size, andcontentId
Verifying Webhook Signatures
JsonHook signs every webhook delivery using HMAC-SHA256. The signature is included in the X-JsonHook-Signature request header as a hex digest. To verify it, compute the HMAC-SHA256 of the raw request body using your address's webhook secret and compare it to the header value.
Your webhook secret is returned when you create an inbound address via the API (POST /api/addresses). Store it as an environment variable — never hard-code it.
import hmac
import hashlib
import os
WEBHOOK_SECRET = os.environ.get("JSONHOOK_WEBHOOK_SECRET", "").encode()
def verify_jsonhook_signature(raw_body: bytes, sig_header: str) -> bool:
"""
Verify X-JsonHook-Signature header.
In Django, access the header via request.META['HTTP_X_JSONHOOK_SIGNATURE'].
request.body gives the raw bytes.
"""
if not sig_header:
return False
computed = hmac.new(WEBHOOK_SECRET, raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(computed, sig_header)
Always verify the signature before processing the payload. Return 401 for invalid signatures so that legitimate retries from JsonHook (which always include a valid signature) are distinguishable from spoofed requests.
Error Handling Best Practices
Reliable webhook handling requires careful attention to error responses. JsonHook uses your HTTP response code to decide whether to retry a delivery:
- Return 200 quickly: Acknowledge receipt immediately and process asynchronously. JsonHook will retry any non-2xx response.
- Return 400 for bad requests: If the payload fails your own validation (not signature — use 401 for that), return 400 to prevent retries of malformed deliveries.
- Return 500 to trigger retries: If your downstream system is temporarily unavailable, returning 500 causes JsonHook to retry with exponential backoff (up to 5 attempts over ~1 hour).
- Never return 200 before verifying the signature: Doing so silently accepts spoofed requests.
Django-specific tips:
- Always add
@csrf_exemptto webhook views — Django's CSRF middleware will reject external POST requests without this decorator - Use Django's
request.META['HTTP_X_JSONHOOK_SIGNATURE']to access the signature header — Django prefixes HTTP headers withHTTP_and uppercases them - Use Celery with Django for async email processing — call
.delay()with the payload dict after returning the 200 response - Configure Django's logging to capture webhook events in structured JSON format for easier debugging and alerting
Django Framework Tips
Django provides several conveniences that make webhook handling cleaner. Here are framework-specific patterns to use when integrating JsonHook:
- Register your webhook route before any authentication middleware — the JsonHook request does not carry user credentials, only the HMAC signature.
- Use raw body access for signature verification. Many Django frameworks parse the body automatically — make sure you are hashing the raw bytes, not the re-serialized parsed object.
- Use a dedicated route or controller file for webhook handlers to keep the codebase organized as you add more inbound address integrations.
- Log the
addressfield from every payload to track which inbound address received the email — useful for multi-address setups. - Consider using Django's built-in request validation or a schema library (e.g., Zod, Pydantic, etc.) to validate the payload structure after signature verification.