Python, LangGraph & CrewAI Guide

Give a Python AI agent its own email inbox.

No Gmail OAuth refresh-token headaches, no SMTP/IMAP boilerplate, and no proprietary wrapper SDK required. Use plain requests with an account-scoped am_... API key to send, read, thread replies, and handle signed webhooks in Python, LangGraph, OpenAI Agents, or CrewAI.

1. Send and read mail with plain Python requests

Create a free 30-day @theagentmail.net mailbox at theagentmail.net/app, generate an account-scoped API key, and export AGENTMAIL_KEY:

import os
import requests

API = "https://api.theagentmail.net"
HEADERS = {"Authorization": f"Bearer {os.environ['AGENTMAIL_KEY']}"}

# Send an email from the agent's mailbox
requests.post(
    f"{API}/v1/messages",
    headers=HEADERS,
    json={
        "to": ["human@example.com"],
        "subject": "Weekly summary ready",
        "text": "All 14 jobs succeeded. Reply to this email to trigger a rerun.",
    },
    timeout=15,
).raise_for_status()

# Read recent inbound and outbound messages (newest first)
messages = requests.get(f"{API}/v1/messages", headers=HEADERS, timeout=15).json()["data"]
latest = messages[0]
detail = requests.get(
    f"{API}/v1/messages/{latest['id']}",
    headers=HEADERS,
    timeout=15,
).json()["data"]
print(detail["from"], detail["subject"], detail["bodyText"])

2. Drop-in LangChain / LangGraph tools

Because the API key is scoped to a single mailbox, your agent cannot access neighboring inboxes or billing routes even if an inbound email contains a prompt injection.

import os
import requests
from langchain_core.tools import tool

API = "https://api.theagentmail.net"
HEADERS = {"Authorization": f"Bearer {os.environ['AGENTMAIL_KEY']}"}

@tool
def check_inbox(limit: int = 10) -> list[dict]:
    """List recent emails in the agent's AgentMail inbox."""
    res = requests.get(f"{API}/v1/messages", headers=HEADERS, timeout=15)
    res.raise_for_status()
    return res.json()["data"][:limit]

@tool
def read_email(message_id: str) -> dict:
    """Read the full text, headers, and attachments of a single email."""
    res = requests.get(f"{API}/v1/messages/{message_id}", headers=HEADERS, timeout=15)
    res.raise_for_status()
    return res.json()["data"]

@tool
def send_email(to: list[str], subject: str, text: str, in_reply_to: str = "") -> dict:
    """Send an email from the agent's inbox (optional in_reply_to keeps the thread)."""
    payload = {"to": to, "subject": subject, "text": text}
    if in_reply_to:
        payload["inReplyTo"] = in_reply_to
        payload["references"] = in_reply_to
    res = requests.post(f"{API}/v1/messages", headers=HEADERS, json=payload, timeout=15)
    res.raise_for_status()
    return res.json()["data"]

3. Wake your agent in real time with HMAC-signed webhooks (FastAPI)

Instead of polling every minute, register a webhook URL via POST /v1/webhooks (or in the dashboard) and verify X-AgentMail-Signature-256 on arrival:

import hashlib
import hmac
import os
import time
from fastapi import FastAPI, HTTPException, Request

app = FastAPI()
WEBHOOK_SECRET = os.environ["AGENTMAIL_WEBHOOK_SECRET"]

@app.post("/agentmail/webhook")
async def on_email(request: Request):
    raw_body = (await request.body()).decode("utf-8")
    ts = request.headers.get("X-AgentMail-Timestamp", "")
    sig = request.headers.get("X-AgentMail-Signature-256", "")

    if not ts.isdigit() or abs(int(time.time() * 1000) - int(ts)) > 300_000:
        raise HTTPException(status_code=401, detail="Stale timestamp")

    expected = "v1=" + hmac.new(
        WEBHOOK_SECRET.encode(),
        f"{ts}.{raw_body}".encode(),
        hashlib.sha256,
    ).hexdigest()
    if not hmac.compare_digest(expected, sig):
        raise HTTPException(status_code=401, detail="Invalid signature")

    event = await request.json()
    msg = event["data"]
    print(f"New mail for {msg['account_address']} from {msg['from']}: {msg['subject']}")
    return {"ok": True}

Transparent pricing, MIT open source

Your first mailbox is free for 30 days (no card required). Additional or continuing mailboxes are a flat $1/month from a $5 prepaid deposit that never expires (which also unlocks inbound OTP/signup verification emails and 1,000 sends/mo). Or self-host the entire Cloudflare Workers stack under MIT.