MOLTED EMAIL

CrewAI Integration Guide

Give your CrewAI agents a governed email mailbox. Send, receive, and track email with built-in policy enforcement.

CrewAI agents can send email by calling any HTTP endpoint through a custom tool. The problem is that nothing governs what they send: no deduplication, no cooldown windows, no suppression checks, no audit trail for the crew's decisions.

This guide shows how to give CrewAI agents a managed mailbox. Every email proposed by any agent in your crew runs through the Molted policy engine first - 20+ rules evaluated in under a second. Policy runs at the infrastructure layer, so no agent in the crew can override it regardless of what instructions it receives.

Prerequisites

  • A Molted account with an API key (sign up at molted.email/signup)
  • A verified sending domain (see Domains)
  • CrewAI installed: pip install crewai
  • 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 crew

Each crew should have its own mailbox (or one per agent role if you want separate policies). In the portal, press ⌘K and type new mailbox - or use the CLI or the API:

CLI
molted mailboxes create --address agent@yourdomain.com --display-name "Sales Crew"
curl
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": "Sales Crew"
  }'

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

CrewAI tools are Python classes that inherit from BaseTool. The send tool wraps the Molted send endpoint and surfaces the policy decision back to the agent.

tools/send_email.py
import os
import requests
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
from typing import Optional


class SendEmailInput(BaseModel):
    to: str = Field(..., description="Recipient email address")
    subject: str = Field(..., description="Email subject line")
    body: str = Field(..., description="Email body in plain text or HTML")
    dedupe_key: Optional[str] = Field(
        None,
        description="Unique key to prevent duplicate sends. Defaults to recipient+subject.",
    )


class SendEmailTool(BaseTool):
    name: str = "send_email"
    description: str = (
        "Send an email to a contact. The email is checked against policy rules "
        "before it is delivered. If blocked, the tool returns the reason — "
        "do not retry a blocked send."
    )
    args_schema: type[BaseModel] = SendEmailInput

    def _run(self, to: str, subject: str, body: str, dedupe_key: Optional[str] = None) -> str:
        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')}"
        )

The tool returns the policy decision to the agent. When a send is blocked, the agent sees the reason and can inform its crew rather than silently failing or retrying.

3. Add a check-status tool (optional)

Agents can read the delivery events of a previous send (GET /v1/agent/messages/:requestId/events, the same as molted events get <requestId>):

tools/check_email_status.py
import os
import requests
from crewai.tools import BaseTool
from pydantic import BaseModel, Field


class CheckStatusInput(BaseModel):
    request_id: str = Field(..., description="The requestId returned when the email was sent")


class CheckEmailStatusTool(BaseTool):
    name: str = "check_email_status"
    description: str = "Check the delivery events (sent, delivered, bounced, ...) of a previously queued email."
    args_schema: type[BaseModel] = CheckStatusInput

    def _run(self, request_id: str) -> str:
        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)

4. Wire the tools into a crew

crew.py
import os
from crewai import Agent, Task, Crew, Process
from tools.send_email import SendEmailTool
from tools.check_email_status import CheckEmailStatusTool

send_email = SendEmailTool()
check_status = CheckEmailStatusTool()

# An agent that writes and sends outreach emails
outreach_agent = Agent(
    role="Outreach Specialist",
    goal="Send personalized, policy-compliant emails to prospects",
    backstory=(
        "You craft personalized outreach emails and send them through the "
        "company mailbox. Every email you send is checked against policy rules "
        "before delivery. If a send is blocked, you report the reason to the "
        "crew manager and do not retry."
    ),
    tools=[send_email, check_status],
    verbose=True,
)

# A manager agent that orchestrates the outreach
manager_agent = Agent(
    role="Outreach Manager",
    goal="Coordinate the outreach campaign and track delivery",
    backstory=(
        "You manage the outreach campaign. You receive leads, assign sends to "
        "the outreach specialist, and track which emails were delivered, blocked, "
        "or pending."
    ),
    verbose=True,
)

send_task = Task(
    description=(
        "Send a trial welcome email to {recipient_email}. "
        "Subject: 'Welcome to the trial'. "
        "Body: 'Thanks for signing up - your 14-day trial starts today. "
        "Reply to this email if you have questions.' "
        "Use a dedupeKey of 'welcome-{recipient_email}' to prevent duplicates."
    ),
    expected_output=(
        "Confirmation that the email was queued with a requestId, "
        "or the block reason if it was rejected by policy."
    ),
    agent=outreach_agent,
)

crew = Crew(
    agents=[manager_agent, outreach_agent],
    tasks=[send_task],
    process=Process.sequential,
    verbose=True,
)

result = crew.kickoff(inputs={"recipient_email": "alice@example.com"})
print(result)

5. Per-agent registration for multi-agent crews

If your crew has multiple agents that send email independently, give each one its own API key and register each agent with its key. Binding the key (bindKey: true) attributes every send that key makes to that agent in the decision trace, and applies the agent's own config (such as its humanizer setting) to its sends. Rate limits stay per mailbox and tenant, not per agent.

register_agents.py
import os
import requests

# One key per agent, created in the portal or with `molted auth keys create`
agents = [
    {"agentName": "outreach-agent", "agentRole": "outbound", "key": os.environ["OUTREACH_AGENT_KEY"]},
    {"agentName": "support-agent", "agentRole": "support", "key": os.environ["SUPPORT_AGENT_KEY"]},
    {"agentName": "churn-agent", "agentRole": "retention", "key": os.environ["CHURN_AGENT_KEY"]},
]

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"],
            "agentRole": agent["agentRole"],
            "bindKey": True,
        },
    )
    data = response.json()
    print(f"Registered {agent['agentName']}: agentId={data['id']}, key binding: {data['apiKeyBinding']}")

Then give each CrewAI agent a send tool that uses its own key. Per-agent config is set separately with PUT /v1/agent/agents/:agentId/config (or molted agents update-config); turning the humanizer on there is a human decision, see Agent Coordination.

6. Handle policy blocks in your crew

Common block reasons and how your agents should respond:

ReasonWhat it meansRecommended agent behavior
duplicateThis dedupeKey was already used by an earlier request. Dedupe is permanent, whatever became of that requestDo not retry with the same key. To send the same email again on purpose, use a new key
suppressedThe recipient is suppressed (unsubscribed, hard-bounced, or complained)Skip this contact, do not retry
cooldownThe recipient was emailed too recentlyTry later, or report it
hourly_limit_exceeded, daily_limit_exceeded, monthly_limit_exceededA send quota is used upPause and report; retry after the window with a new dedupeKey
no_consentThe tenant turned on requireConsentForMarketing and the recipient has no consent on fileDo not send; record consent first
lease_conflictAnother agent holds a lease on this contactWait for the lease to end (see Agent Coordination)
trial_not_activatedThe account has no active plan yetAsk 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 backstory:

outreach_agent = Agent(
    role="Outreach Specialist",
    backstory=(
        "...When a send is blocked:\n"
        "- 'duplicate': this dedupe key was already used. "
        "  Inform the crew manager. Do not retry.\n"
        "- 'suppressed': this contact has opted out. "
        "  Mark them as suppressed and skip.\n"
        "- 'hourly_limit_exceeded' or 'daily_limit_exceeded': pause and notify the manager. "
        "  Do not retry immediately.\n"
        "- Any other block: report the reason and requestId to the manager."
    ),
    ...
)

7. Async crews (LangGraph-style flows)

For async or flow-based CrewAI setups, the send tool works the same way since it uses blocking HTTP. For non-blocking sends in an async context:

import os
import httpx

async def send_email_async(to: str, subject: str, body: str, dedupe_key: str) -> dict:
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "https://mailbox.molted.email/v1/agent/request-send",
            headers={
                "Authorization": f"Bearer {os.environ['MOLTED_API_KEY']}",
                "Content-Type": "application/json",
            },
            json={
                "mailboxId": os.environ["MOLTED_MAILBOX_ID"],
                "recipientEmail": to,
                "templateId": "_default",
                "dedupeKey": dedupe_key,
                "payload": {"subject": subject, "html": body, "text": body},
            },
            timeout=10.0,
        )
        return response.json()

What gets enforced

When any agent in your crew calls send_email, the mailbox evaluates 20+ policy rules before anything leaves:

  1. Suppression - has this recipient opted out or hard-bounced?
  2. Deduplication - has any earlier request used the same dedupeKey? (Dedupe is permanent.)
  3. Cooldown - is there an active cooldown for this recipient?
  4. Rate limits - has the mailbox hit its per-minute, per-hour, or per-day budget?
  5. Negative-signal budget - have bounces and complaints in the last 24 hours used up the tenant's budget?
  6. 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. The agent receives the reason and can respond accordingly.

No agent in your crew - regardless of its instructions or the LLM powering it - can override these checks. They run at the infrastructure layer.