Quick Start: Python Email Webhook
JsonHook delivers every inbound email as a JSON POST request to your webhook endpoint. Setting up a Python handler takes less than 5 minutes. Start by initializing your project:
pip install flask
Then create your webhook endpoint. The following example shows the minimal code needed to receive and acknowledge a JsonHook delivery:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
payload = request.get_json()
print('Received email from:', payload['email']['from'])
print('Subject:', payload['email']['subject'])
return '', 200
if __name__ == '__main__':
app.run(port=3000)
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 Python 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.
import hmac
import hashlib
import json
import os
from flask import Flask, request, abort
app = Flask(__name__)
WEBHOOK_SECRET = os.environ['JSONHOOK_WEBHOOK_SECRET'].encode('utf-8')
def verify_signature(raw_body: bytes, signature_header: str) -> bool:
if not signature_header:
return False
computed = hmac.new(WEBHOOK_SECRET, raw_body, hashlib.sha256).hexdigest()
# Use hmac.compare_digest for constant-time comparison
return hmac.compare_digest(computed, signature_header)
@app.route('/webhook', methods=['POST'])
def webhook():
signature = request.headers.get('X-JsonHook-Signature', '')
raw_body = request.get_data() # Must read raw bytes before JSON parsing
if not verify_signature(raw_body, signature):
app.logger.warning('Invalid JsonHook signature')
abort(401)
try:
payload = json.loads(raw_body)
except json.JSONDecodeError:
abort(400)
# Acknowledge immediately
event = payload['event'] # "email.received"
timestamp = payload['timestamp']
address = payload['address']
email = payload['email']
app.logger.info(f'[{timestamp}] Email at {address} from {email["from"]}')
app.logger.info(f'Subject: {email["subject"]}')
for att in email.get('attachments', []):
app.logger.info(f'Attachment: {att["filename"]} ({att["size"]} bytes)')
return '', 200
if __name__ == '__main__':
app.run(port=3000, debug=False)
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 Python 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
raw_body = request.get_data()
payload = json.loads(raw_body)
# Top-level fields
event = payload['event'] # "email.received"
timestamp = payload['timestamp'] # "2026-03-15T12:34:56.789Z"
address = payload['address'] # "[email protected]"
# Email fields
email = payload['email']
sender = email['from'] # "Alice "
to = email['to'] # ["[email protected]"]
subject = email['subject']
text_body = email['textBody']
html_body = email.get('htmlBody', '')
# Attachments
for att in email.get('attachments', []):
print(att['filename']) # "report.pdf"
print(att['contentType']) # "application/pdf"
print(att['size']) # 204800 (bytes)
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['JSONHOOK_WEBHOOK_SECRET'].encode('utf-8')
def verify_jsonhook_signature(raw_body: bytes, signature_header: str) -> bool:
"""
Verify the X-JsonHook-Signature HMAC-SHA256 header.
raw_body must be the unmodified request body bytes.
"""
if not signature_header:
return False
computed = hmac.new(WEBHOOK_SECRET, raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(computed, signature_header)
# Usage in Flask:
# raw_body = request.get_data() # Must call before request.get_json()
# sig = request.headers.get('X-JsonHook-Signature', '')
# if not verify_jsonhook_signature(raw_body, sig):
# abort(401)
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.
Python ecosystem tips:
- Always call
request.get_data()beforerequest.get_json()in Flask — once the JSON is parsed, the raw bytes are consumed and you cannot recompute the HMAC - Use
hmac.compare_digest()instead of==for signature comparison to prevent timing side-channel attacks - Register an error handler with
@app.errorhandler(500)to return a plain 500 response (which triggers JsonHook retries) rather than an HTML error page - For production deployments, run Flask behind gunicorn or uvicorn and set a request timeout of at least 15 seconds to handle slow downstream processing
Python Ecosystem Tips
The Python ecosystem offers several libraries and patterns that pair well with JsonHook webhook handling. Here are general recommendations:
- Use a well-maintained HTTP server library appropriate for your use case — the examples in this guide use the most common choice, but any library that gives you raw body access works.
- Store your webhook secret in an environment variable and load it via your language's standard env access pattern — never commit secrets to version control.
- Use your language's standard HMAC library rather than a third-party package — all languages featured in this guide have HMAC-SHA256 in their standard library.
- Consider a structured logging library to capture the
address,event, andtimestampfields from every webhook delivery for observability. - Test your handler locally using a tunneling tool like ngrok or a local webhook testing service before pointing your JsonHook address at a production URL.