Skip to content
Browse the docs

Frameworks and agents · Published 2026-09-28 · Updated 2026-11-09 · AgentiSend

Send email from Flask

A Flask POST route that checks the address, sends one receipt per order with an idempotency key, and returns the message id or the code and fix of a refusal.

To send email from Flask, add one POST route that checks the address, calls AgentiSend with an idempotency key derived from the order, and returns the message id, or the refusal's code and fix. The app below is that route. It is run by the test suite against a local AgentiSend server's repository, through Flask's own test_client(): one receipt, the same request again replaying it, a malformed address answered before any request is made, and the same order's receipt to a second address refused by the API.

Install

pip install flask

The agentisend package is standard library only, so pip install agentisend adds no other dependency.

Environment

The app reads AGENTISEND_API_KEY (a sending_access key) and MAIL_FROM (an address on a domain you verified) from the environment, and AGENTISEND_BASE_URL when you point it at a local server. They come from os.environ, not Flask's app.config.

The route

"""Flask: one POST route that sends an order receipt.

    POST /send  {"email": "ada@example.com", "order_id": "1042"}
    200         {"id": "..."}                     accepted
    400         {"error": "..."}                  not one address; the API was not called
    4xx/5xx     {"code": "...", "fix": "..."}     the API refused, and says what to do

Environment: AGENTISEND_API_KEY (a key with sending_access), MAIL_FROM (an
address on a domain you have verified), and optionally AGENTISEND_BASE_URL.
Run: flask --app app run
"""

from __future__ import annotations

import os
import re

from flask import Flask, jsonify, request

from agentisend import AgentiSend, AgentiSendError, idempotency_key

agentisend = AgentiSend()  # reads AGENTISEND_API_KEY and AGENTISEND_BASE_URL
MAIL_FROM = os.environ["MAIL_FROM"]

# One address, no spaces, a dot in the domain. The API checks properly; this
# only stops a form typo from costing a request.
ADDRESS = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")

app = Flask(__name__)


@app.post("/send")
def send():
    body = request.get_json(silent=True) or {}
    email = str(body.get("email", "")).strip()
    order_id = str(body.get("order_id", "")).strip()
    if not ADDRESS.match(email):
        return jsonify(error="email must be one address, like you@example.com"), 400
    if not order_id:
        return jsonify(error="order_id is required"), 400

    try:
        sent = agentisend.send_email(
            {
                "from": MAIL_FROM,
                "to": email,
                "subject": f"Receipt for order {order_id}",
                "text": f"Thanks for your order. Order {order_id} is paid.",
            },
            # One receipt per order, whoever asks and however often: a retry
            # after a timeout replays the first send instead of mailing twice.
            idempotency=idempotency_key("receipt", order_id),
        )
    except AgentiSendError as err:
        return jsonify(code=err.code, fix=err.fix), err.status
    return jsonify(id=sent["id"])
examples/flask/app.py, run by the test suite against a local AgentiSend server

Try it

flask --app app run
curl -X POST localhost:5000/send \
  -H 'content-type: application/json' \
  -d '{"email":"you@example.com","order_id":"1042"}'

The idempotency key

Every send carries Idempotency-Key: receipt/<order>, derived from what the message is and never from when it was asked for. A retry after a timeout gets the first send's id back instead of a second receipt. The same key with a different body is refused with idempotency_payload_mismatch: an order has one receipt, and a request that tries to send it somewhere else is told so rather than sent.

What comes back when it goes wrong

The route answers with the API's status and forwards code and fix, so the caller reads what to do rather than a number. The error catalogue lists every code.

Next

Examples

Prompt for your coding agent

1. Install

npm install agentisend

2. Environment

AGENTISEND_API_KEY
MAIL_FROM
AGENTISEND_BASE_URL=https://api.agentisend.com

3. Send call

"""Flask: one POST route that sends an order receipt.

    POST /send  {"email": "ada@example.com", "order_id": "1042"}
    200         {"id": "..."}                     accepted
    400         {"error": "..."}                  not one address; the API was not called
    4xx/5xx     {"code": "...", "fix": "..."}     the API refused, and says what to do

Environment: AGENTISEND_API_KEY (a key with sending_access), MAIL_FROM (an
address on a domain you have verified), and optionally AGENTISEND_BASE_URL.
Run: flask --app app run
"""

from __future__ import annotations

import os
import re

from flask import Flask, jsonify, request

from agentisend import AgentiSend, AgentiSendError, idempotency_key

agentisend = AgentiSend()  # reads AGENTISEND_API_KEY and AGENTISEND_BASE_URL
MAIL_FROM = os.environ["MAIL_FROM"]

# One address, no spaces, a dot in the domain. The API checks properly; this
# only stops a form typo from costing a request.
ADDRESS = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")

app = Flask(__name__)


@app.post("/send")
def send():
    body = request.get_json(silent=True) or {}
    email = str(body.get("email", "")).strip()
    order_id = str(body.get("order_id", "")).strip()
    if not ADDRESS.match(email):
        return jsonify(error="email must be one address, like you@example.com"), 400
    if not order_id:
        return jsonify(error="order_id is required"), 400

    try:
        sent = agentisend.send_email(
            {
                "from": MAIL_FROM,
                "to": email,
                "subject": f"Receipt for order {order_id}",
                "text": f"Thanks for your order. Order {order_id} is paid.",
            },
            # One receipt per order, whoever asks and however often: a retry
            # after a timeout replays the first send instead of mailing twice.
            idempotency=idempotency_key("receipt", order_id),
        )
    except AgentiSendError as err:
        return jsonify(code=err.code, fix=err.fix), err.status
    return jsonify(id=sent["id"])

4. Parameter reference

POST /emails
attachments array<object>
bcc any
cc any
expires_at string
from string
headers object
html string
replyTo any
reply_to any
scheduledAt string
scheduled_at string
subject string
tags any
template object
template_id string
template_values object
text string
timezone string
to any required
topicId string
topic_id string
Idempotency-Key header
Resend-Idempotency-Key header

5. Rules

Read the API key on the server. Do not send it to the browser.
Send an Idempotency-Key derived from the thing being done, not from the clock.
A refusal is JSON with code, message, fix and docs_url. Follow fix.

6. Verify

GET /emails/{id}
The id is the one the send call returned.