Quickstarts
Send with Flask
Send email from a Flask view with the usend SDK.
You need a verified domain and an API key.
1. Install
pip install flask usend2. The app
from flask import Flask, jsonify, request
from usend import Usend, UsendError
app = Flask(__name__)
usend = Usend() # reads USEND_API_KEY from the environment
@app.post("/send")
def send():
data = request.get_json(force=True)
try:
email = usend.emails.send({
"from": "Acme <[email protected]>",
"to": [data["email"]],
"subject": "Welcome to Acme",
"html": "<p>Thanks for signing up.</p>",
})
except UsendError as e:
return jsonify(error=str(e)), 502
return jsonify(id=email["id"])3. Run and test
export USEND_API_KEY="us_123456789"
flask --app app run
curl -X POST localhost:5000/send -d '{"email":"[email protected]"}'Webhooks
The SDK verifies signatures; pass the raw body, not parsed JSON:
from usend import verify_webhook
@app.post("/webhooks/usend")
def webhook():
try:
event = verify_webhook(request.get_data(as_text=True), request.headers, WEBHOOK_SECRET)
except Exception:
return "", 400
print(event["type"])
return "", 200See Verify signatures.
Tips
- Sending inside a request blocks the response for one HTTP round trip. For bulk or non-critical mail, hand it to a task queue such as Celery or RQ.
- Keep
fromfixed on your verified domain.
More fields: Send emails.