LlamaIndex Integration Guide
Add a governed email mailbox to your LlamaIndex agents. Send, receive, and track email with built-in policy enforcement.
LlamaIndex agents can call any Python function as a tool. The problem is that email calls made from those tools have no governance layer: no deduplication, no cooldown windows, no suppression checks, no audit trail.
This guide shows how to give a LlamaIndex agent a managed mailbox. Every email the agent proposes runs through the Molted policy engine before it leaves - 20+ rules evaluated in under a second. The agent keeps sending through a familiar FunctionTool interface; policy runs at the infrastructure layer and cannot be bypassed by any instruction passed to the LLM.
Prerequisites
- A Molted account with an API key (sign up at molted.email/signup)
- A verified sending domain (see Domains)
- LlamaIndex installed:
pip install llama-index llama-index-llms-openai - Requests installed:
pip install requests
If your framework can connect to a remote MCP server, you can skip the hand-written tools in this guide: point it at https://mcp.molted.email/mcp with your API key as a bearer token, and the agent gets send_email, reply, read_inbox, get_thread, check_suppression and the rest of Molted's tools, with the same policy checks. See MCP Server. The tools below call the REST API directly, which works with any framework.
1. Create a mailbox for your agent
Each LlamaIndex agent should have its own mailbox. In the portal, press ⌘K and type new mailbox - or use the CLI or the API:
molted mailboxes create --address agent@yourdomain.com --display-name "Outbound Agent"curl -X POST https://mailbox.molted.email/v1/agent/mailboxes \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"address": "agent@yourdomain.com",
"displayName": "Outbound Agent"
}'The response's id is the mailbox id: pass it as mailboxId on each send. The examples below read it from MOLTED_MAILBOX_ID, your API key from MOLTED_API_KEY. The examples call https://mailbox.molted.email, which fills in your tenant from the key, so they need no tenant id. A send without a mailboxId goes out from your default mailbox.
2. Define the send tool
LlamaIndex tools are plain Python functions wrapped with FunctionTool.from_defaults. The function signature and docstring become the tool definition the LLM sees.
import os
from typing import Optional
import requests
from llama_index.core.tools import FunctionTool
def send_email(
to: str,
subject: str,
body: str,
dedupe_key: Optional[str] = None,
) -> str:
"""Send an email to a contact.
The email is checked against policy rules before it is delivered.
If blocked, the function returns the reason - do not retry a blocked send.
Args:
to: Recipient email address.
subject: Email subject line.
body: Email body in plain text or HTML.
dedupe_key: Unique key to prevent duplicate sends. Defaults to recipient+subject.
"""
api_key = os.environ["MOLTED_API_KEY"]
payload = {
"mailboxId": os.environ["MOLTED_MAILBOX_ID"],
"recipientEmail": to,
"templateId": "_default",
"dedupeKey": dedupe_key or f"{to}-{subject}",
"payload": {
"subject": subject,
"html": body,
"text": body,
},
}
response = requests.post(
"https://mailbox.molted.email/v1/agent/request-send",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json=payload,
timeout=10,
)
data = response.json()
if not response.ok:
return f"Send failed (HTTP {response.status_code}): {data.get('message') or data.get('error')}"
if data.get("status") == "blocked":
return (
f"Email blocked by policy. Reason: {data.get('reason')}. "
f"Decision trace: {data.get('requestId')}. Do not retry."
)
return (
f"Email queued successfully. "
f"requestId={data.get('requestId')}, status={data.get('status')}"
)
send_email_tool = FunctionTool.from_defaults(fn=send_email)The tool returns the policy decision back to the agent. When a send is blocked, the agent sees the reason and can decide how to proceed rather than silently failing or retrying.
3. Add a status-check tool (optional)
Agents can read the delivery events of a prior send using the requestId from the send response (GET /v1/agent/messages/:requestId/events, the same as molted events get <requestId>):
import os
import requests
from llama_index.core.tools import FunctionTool
def check_email_status(request_id: str) -> str:
"""Check the delivery events (sent, delivered, bounced, ...) of a previously queued email.
Args:
request_id: The requestId returned when the email was sent.
"""
response = requests.get(
f"https://mailbox.molted.email/v1/agent/messages/{request_id}/events",
headers={"Authorization": f"Bearer {os.environ['MOLTED_API_KEY']}"},
timeout=10,
)
events = response.json().get("events", [])
if not events:
return "No delivery events yet."
# Oldest first: e.g. "sent", then "delivered" or "bounced"
return "\n".join(f"{e['created_at']} {e['event_type']}" for e in events)
check_status_tool = FunctionTool.from_defaults(fn=check_email_status)4. Build the agent
Wire the tools into a ReActAgent or FunctionCallingAgent. Both work the same way - use FunctionCallingAgent for models that natively support tool use (GPT-4o, Claude, Gemini):
import os
from llama_index.core.agent import ReActAgent
from llama_index.llms.openai import OpenAI
from tools.send_email import send_email_tool
from tools.check_email_status import check_status_tool
llm = OpenAI(model="gpt-4o", api_key=os.environ["OPENAI_API_KEY"])
agent = ReActAgent.from_tools(
tools=[send_email_tool, check_status_tool],
llm=llm,
verbose=True,
system_prompt=(
"You are an email outreach agent. You send policy-compliant emails through "
"a managed mailbox. Every send is checked against policy rules before delivery. "
"If a send is blocked, report the reason - do not retry. "
"Use 'welcome-{email}' as the dedupeKey for welcome emails to prevent duplicates."
),
)
response = agent.chat(
"Send a trial welcome email to alice@example.com. "
"Let her know her 14-day trial starts today and she can reply with questions."
)
print(response)Using FunctionCallingAgent
For function-calling models, FunctionCallingAgent avoids the ReAct chain-of-thought overhead:
from llama_index.core.agent import FunctionCallingAgent
from llama_index.llms.openai import OpenAI
from tools.send_email import send_email_tool
from tools.check_email_status import check_status_tool
llm = OpenAI(model="gpt-4o")
agent = FunctionCallingAgent.from_tools(
tools=[send_email_tool, check_status_tool],
llm=llm,
verbose=True,
)
response = agent.chat("Send a churn-prevention email to bob@example.com.")
print(response)5. AgentWorkflow (newer API)
LlamaIndex's AgentWorkflow API (introduced in v0.11+) lets you compose multi-step agentic pipelines with explicit state management. It works the same way:
import os
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai import OpenAI
from tools.send_email import send_email_tool
from tools.check_email_status import check_status_tool
llm = OpenAI(model="gpt-4o")
agent = FunctionAgent(
tools=[send_email_tool, check_status_tool],
llm=llm,
system_prompt=(
"You are an outreach agent. Send emails through the governed mailbox. "
"If a send is blocked, report the block reason to the caller. Do not retry."
),
)
import asyncio
async def main():
response = await agent.run(
"Send a reactivation email to carol@example.com who hasn't logged in for 30 days."
)
print(response)
asyncio.run(main())6. Multi-agent setup
For pipelines with multiple agents sending email, give each agent its own API key and register each one with its key. With bindKey: true the key is bound to that agent for good: every send the key makes is attributed to it in the decision trace, and the agent's own config (such as its humanizer setting) applies. Rate limits stay per mailbox and tenant, not per agent.
import os
import requests
# One key per agent, created in the portal or with `molted auth keys create`
agents = [
{"agentName": "onboarding-agent", "key": os.environ["ONBOARDING_AGENT_KEY"]},
{"agentName": "churn-agent", "key": os.environ["CHURN_AGENT_KEY"]},
{"agentName": "billing-agent", "key": os.environ["BILLING_AGENT_KEY"]},
]
agent_ids = {}
for agent in agents:
response = requests.post(
"https://mailbox.molted.email/v1/agent/register",
headers={
"Authorization": f"Bearer {agent['key']}",
"Content-Type": "application/json",
},
json={"agentName": agent["agentName"], "bindKey": True},
)
data = response.json()
agent_ids[agent["agentName"]] = data["id"]
print(f"Registered {agent['agentName']}: agentId={data['id']}, key binding: {data['apiKeyBinding']}")Each agent's send tool then uses its own key. Per-agent config is set with PUT /v1/agent/agents/:agentId/config (or molted agents update-config); turning the humanizer on there is a human decision, see Agent Coordination.
7. TypeScript / LlamaIndex.TS
LlamaIndex also has a TypeScript SDK. The integration pattern is the same:
import { FunctionTool } from "llamaindex";
export const sendEmailTool = FunctionTool.from(
async ({
to,
subject,
body,
dedupeKey,
}: {
to: string;
subject: string;
body: string;
dedupeKey?: string;
}) => {
const response = await fetch(
"https://mailbox.molted.email/v1/agent/request-send",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MOLTED_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
mailboxId: process.env.MOLTED_MAILBOX_ID,
recipientEmail: to,
templateId: "_default",
dedupeKey: dedupeKey ?? `${to}-${subject}`,
payload: { subject, html: body, text: body },
}),
}
);
const data = await response.json();
if (data.status === "blocked") {
return `Email blocked: ${data.reason}. Decision trace: ${data.requestId}. Do not retry.`;
}
return `Email queued: requestId=${data.requestId}, status=${data.status}`;
},
{
name: "send_email",
description:
"Send an email to a contact. Checked against policy rules before delivery. If blocked, returns the reason - do not retry.",
parameters: {
type: "object",
properties: {
to: { type: "string", description: "Recipient email address" },
subject: { type: "string", description: "Email subject line" },
body: { type: "string", description: "Email body in plain text or HTML" },
dedupeKey: {
type: "string",
description: "Unique key to prevent duplicate sends",
},
},
required: ["to", "subject", "body"],
},
}
);import { OpenAI, ReActAgent } from "llamaindex";
import { sendEmailTool } from "./tools/sendEmail";
const llm = new OpenAI({ model: "gpt-4o" });
const agent = new ReActAgent({
tools: [sendEmailTool],
llm,
});
const response = await agent.chat({
message: "Send a welcome email to alice@example.com.",
});
console.log(response.response);8. Handle policy blocks
Common block reasons and how agents should respond:
| Reason | What it means | Recommended agent behavior |
|---|---|---|
duplicate | This dedupeKey was already used by an earlier request. Dedupe is permanent, whatever became of that request | Do not retry with the same key. To send the same email again on purpose, use a new key |
suppressed | The recipient is suppressed (unsubscribed, hard-bounced, or complained) | Skip this contact, do not retry |
cooldown | The recipient was emailed too recently | Try later, or report it |
hourly_limit_exceeded, daily_limit_exceeded, monthly_limit_exceeded | A send quota is used up | Pause and report; retry after the window with a new dedupeKey |
no_consent | The tenant turned on requireConsentForMarketing and the recipient has no consent on file | Do not send; record consent first |
lease_conflict | Another agent holds a lease on this contact | Wait for the lease to end (see Agent Coordination) |
trial_not_activated | The account has no active plan yet | Ask a human to activate billing |
A blocked request has used up its dedupeKey: once the cause is fixed, retry with a new one. Every reason is listed in Errors.
Add explicit block-handling instructions to your agent's system prompt so the LLM knows what to do:
system_prompt = """
You are an email outreach agent. When a send is blocked:
- 'duplicate': email was already sent recently. Report to the user. Do not retry.
- 'suppressed': contact has opted out. Skip and move to next contact.
- 'hourly_limit_exceeded' or 'daily_limit_exceeded': mailbox rate limit hit. Stop all sends and report.
- 'cooldown': cooldown in effect. Report when it will lift. Do not retry now.
- Any other block: report the reason and requestId. Do not retry without explicit instruction.
"""What gets enforced
When your agent calls send_email, the mailbox evaluates 20+ policy rules before anything leaves:
- Suppression - has this recipient opted out or hard-bounced?
- Deduplication - has any earlier request used the same
dedupeKey? (Dedupe is permanent.) - Cooldown - is there an active per-recipient cooldown?
- Rate limits - has the mailbox hit its per-minute, per-hour, or per-day budget?
- Negative-signal budget - have bounces and complaints in the last 24 hours used up the tenant's budget?
- Consent - only when the tenant turned on
requireConsentForMarketing: does the contact have consent on file?
If all rules pass, the email is delivered. If any rule fires, the send is blocked and the decision trace records exactly which rule triggered and why. No instruction passed to the LLM - and no tool call the agent makes - can override these checks.
Related
- Quickstart - send your first policy-checked email
- LangChain Integration Guide - LangChain-specific setup
- CrewAI Integration Guide - multi-agent crew setup
- Policy Simulation - test policy rules against draft sends
- Reactive Agent Guide - build agents that respond to inbound email
- Autonomy Levels - require human approval for high-risk sends