AI Email Management: Route, Classify, and Monitor Every Message Automatically
Manage email across AI agents: classify inbound, route by intent, monitor reputation, and enforce sending policy — all from one API.
What AI email management actually requires
Managing email with AI is not a feature you bolt onto a send API — it is an infrastructure problem. An agent that manages email needs to receive messages as structured data, classify them before deciding what to do, reply inside existing threads, and stay within sending-reputation boundaries it cannot override. Each of those requires a layer below the agent, not a prompt inside it.
Mails.ai provides that layer: inbound parsing, injection scanning, intent classification, per-agent reputation, and a cold-email firewall — so your agents manage email with constraints they cannot circumvent. For the full overview of how AI email management works end to end, see the AI email management guide.
Classify and route inbound automatically
Every inbound message is parsed from raw MIME into a structured event before your agent sees it, and first-contact mail is optionally classified by intent and urgency. Your routing logic reads typed fields, not raw email:
import { createClient } from "@mailsai/sdk" ;
const mails = createClient({ apiKey: process. env. MAILS_API_KEY });
// Stream classified inbound events
mails. events. stream({
event_types: [ "message.received" , "reply.received" ],
onEvent: async ( event) => {
// Hold for a person: quarantined, not scanned (no score), or 0.5 and up
if ( event. quarantined || typeof event. injection_score !== "number" || event. injection_score >= 0.5) {
return flagForReview( event);
}
// Route by classified intent — no LLM call needed for routing
switch ( event. intent) {
case "ask_question":
await supportAgent. handle( event);
break;
case "schedule_demo":
await calendarAgent. handle( event);
break;
default:
await triageAgent. handle( event);
}
},
});Intent classification runs on the infrastructure side, so routing decisions are made before your model runs — faster and cheaper than passing every message through an LLM to decide where it goes.
Python integration: manage inbound routing and replies
AI email management works the same way in Python — the API is plain HTTPS + JSON, so your Flask or FastAPI handler receives fully parsed events and routes them without touching MIME or headers:
import hmac, hashlib, os, time, requests
from flask import Flask, request, jsonify
app = Flask( __name__)
WEBHOOK_SECRET = os. environ[ "MAILS_WEBHOOK_SECRET"]
API = "https://api.mails.ai/v1"
HEADERS = { "Authorization": f"Bearer {os . environ[ 'MAILS_API_KEY']}"}
AGENT_HANDLERS = {
"ask_question": "support",
"request_info": "support",
"schedule_demo": "calendar",
}
def verified( raw: bytes, header: str) -> bool:
# X-Mails-Signature: t=<unix>,v1=<hex> (a second v1 while a secret rotates)
parts = [ p. split( "=" , 1) for p in header. split( "," ) if "=" in p]
t = next(( v for k, v in parts if k == "t"), "")
if not t. isdigit() or abs( time. time() - int( t)) > 300:
return False # reject stale or replayed deliveries
expected = hmac. new(
WEBHOOK_SECRET. encode(), f"{t} .". encode() + raw, hashlib. sha256
). hexdigest()
return any( hmac. compare_digest( expected, v) for k, v in parts if k == "v1")
@app. post( "/api/manage" )
def manage_email():
if not verified(
request. get_data(), request. headers. get( "X-Mails-Signature", "")
):
return jsonify({ "error": "invalid signature"}), 401
event = request. get_json()
if event[ "type"] not in ( "message.received" , "reply.received" ):
return jsonify({ "status": "ignored"}), 200
score = event. get( "injection_score") # None when it was not scanned
if event. get( "quarantined") or score is None or score >= 0.5:
flag_for_review( event) # a person decides; a failed scan scores 0.5
return jsonify({ "status": "held"}), 200
# Route by classified intent — no LLM call needed
agent = AGENT_HANDLERS. get( event. get( "intent"), "triage")
reply = your_agents[ agent]. respond(
event[ "data"][ "body_text_excerpt"], thread_id= event[ "thread_id"]
)
# Reply in the thread: the API sets In-Reply-To, References and "Re:"
requests. post( f"{API} /messages/ {event [ 'source_message_id']}/reply" ,
headers= HEADERS, json={ "body_text": reply})
return jsonify({ "status": "ok"}), 200For the async FastAPI variant with full HMAC verification, see inbound email API webhooks for Python agents.
Reply in threads, not new conversations
When an agent replies, the response lands inside the existing conversation in the recipient’s mail client. Thread reconstruction is automatic — your code passes the message ID it is replying to, and the API handles Message-ID chains, In-Reply-To headers, and References headers:
// Agent replies in the same thread — threading is automatic
if ( event. source_message_id) {
await mails. messages. reply( event. source_message_id, {
body_text: generatedReply,
});
}
// The reply appears in the recipient's existing conversation,
// not as a separate email.Monitor reputation per agent
In a multi-agent setup, one misbehaving agent should not take down everyone else’s deliverability. Mails.ai scores reputation per agent: bounce rates, complaint rates, and send volume are tracked independently. If one agent crosses the 0.3% complaint threshold, it auto-suspends while your other agents keep sending, unless the workspace’s mail as a whole crosses the line too, which suspends every agent.
Cold and bulk outreach is blocked in the send call itself — an agent that is prompted into prospecting gets a 422 cold_email_prohibited response and nothing is transmitted. This is not configurable, because a shared sending estate only stays deliverable if no agent on it can send unsolicited mail.
Injection scanning: the first layer of AI email management
Before any routing or reply happens, every inbound message is scanned for prompt-injection patterns across six categories: boundary manipulation, system-prompt override, data exfiltration, role hijacking, tool invocation, and jailbreaks. The result is a numeric injection_score (0.0–1.0) on every event — your AI email management logic branches on a number, not on a prompt that is itself the attack vector:
// Recommended injection-score thresholds for managed inbound.
// Mail that was not scanned has no score, and a scan that could not run scores
// exactly 0.5: both go to a person.
const { injection_score, quarantined, thread_id } = event;
if ( quarantined) {
await quarantine( event); // 0.95 or more: keep it from the agent entirely
} else if ( typeof injection_score !== "number" || injection_score >= 0.5) {
await flagForReview( event); // human review queue
} else if ( injection_score > 0.3) {
await processWithCaution( event); // log but still route
} else {
await routeToAgent( event); // normal management path
}This layer runs on the infrastructure side — it is not a prompt filter you add inside the agent. For the full security architecture, see the security overview.
Test the full management flow without sending mail
Test keys (mk_test_…) run the entire path — parsing, injection scanning, classification, threading, webhook delivery — and transmit nothing. You can simulate inbound messages to verify your routing logic, test edge cases in classification, and confirm reply threading before any real mail moves.
Pricing
Every plan includes MIME parsing, injection scanning, thread reconstruction, and the per-agent reputation system. Intent classification is included on paid plans at no extra charge. Free covers one agent with 3,000 emails and 3,000 inbound replies a month — no card required. Pro is $20/month for five agents, Scale is $99/month for unlimited agents. For the full agent identity and inbox setup, see AI email agent. For the inbound parsing layer in detail, see email parsing API. For building a Python-based email handler, see send email from a Python AI agent. For workflow automation across agents, see AI email automation services. For the underlying stack — DNS, deliverability, warm-up, and reputation — see email infrastructure for AI agents. For the full platform overview, see AI email platform. For the formal definition, see AI email management in the glossary.
Frequently asked questions
How is AI email management different from a traditional email client with AI features?
Can I route messages to different agents based on content?
What happens if one agent damages sending reputation?
Does the injection scanner work on every inbound message?
injection_score (0.0–1.0) arrives on the event so your code branches on a number, not a prompt.Can I manage email across multiple agents from a single account?
What does it cost?
Give your first agent an inbox
Free covers 3,000 emails and 3,000 inbound replies a month, with no card. Upgrade when your agents get busy.
Get your API key