Skip to content
send.io
All posts

How to read and search inbox messages from Claude Code

Claude Code reads email via MCP tool calls to search, filter, and fetch inbox messages with full payloads for agent context assembly. Filter aggressively before fetching full payloads, strip quoted text to cut token costs, and pipe production edge cases into your evaluation harness.

On this page
TL;DR: Claude Code doesn't read email natively. It acts as an MCP client that issues tool calls to an MCP server. send.io ships an MCP server exposing 160 tools spanning email sending and listing, agent inboxes, automations, and events. This guide walks through received-email retrieval using illustrative calls named search_inbox and fetch_message, which stand in for documented tools such as get-received-email, which returns a received email with its headers, HTML, and text, list-received-email-attachments, which lists attachment download URLs, and get-received-email-attachment, which returns one attachment with its download URL. Connect via mcp add to search, filter, and fetch messages programmatically, but budget context-window tokens carefully because full payloads consume more tokens than metadata. Turn production inbox messages into a golden dataset by filtering for edge cases and piping them to your evaluation harness.

Your agent needs a real inbox, not a workaround through a shared account, so it can receive verification codes, read replies, and respond without a human in the loop. Agent failures in production often trace back to context assembly rather than model quality, and the inbox is where that context lives. When you're debugging why your agent pulled the wrong message or failed to extract a verification code, you're dealing with tool outputs and payload structures, not model hallucinations.

Claude Code acts as an MCP client that consumes tools exposed by an MCP server. send.io ships that server, exposing tools for email retrieval, including documented tools such as get-received-email, which returns a received email with its headers, HTML, and text. This article shows illustrative tool calls, the filtering parameters, and the context-window budgeting patterns that turn inbox access from a demo into a reliable production workflow.

Why agents need programmatic inbox access

Before an agent can act on a task, someone has to gather the context it needs, and that context rarely lives in one place. Schemas sit in wikis, decisions sit in Slack threads, and credentials, replies, and notifications sit in email. Pulling those pieces together by hand takes up a large share of the time spent on each task. For AI agents, email is a key context source because it carries verification codes, user replies, system notifications, and edge cases that never appear in clean test fixtures.

Solving the context assembly bottleneck

Programmatic inbox access removes the manual search through scattered systems before you write a prompt or design a tool call. When an agent can query an inbox directly via MCP tools, it retrieves the exact message thread containing the API credentials, the error notification, or the user reply without human intervention.

send.io's agent inbox architecture provides dedicated inboxes with scoped API keys, so agents authenticate with credentials scoped to a specific inbox or pod rather than broad account access. This isolation matters for security and for debugging: when an agent misreads a message, you know exactly which inbox and which credential were involved.

Turning real inbox events into test data

Production inbox messages contain the edge cases that synthetic test data misses. Real users send malformed replies, include unexpected attachments, trigger spam filters, and write subject lines that break your parsing logic. A golden dataset is a structured list of test cases, each pairing an input prompt with a description of the expected outcome, and you should start with 20 to 50 cases drawn from real user logs or known failure modes rather than synthetic examples.

Pulling these messages into an evaluation harness lets you measure precision, recall, and F1 per extracted field, catching regressions before they hit production. The inbox becomes a source of ground truth for how your agent behaves under real conditions.

Connecting Claude Code to email via MCP

MCP (Model Context Protocol) uses JSON-RPC 2.0 as its underlying RPC protocol. When a connection succeeds, the client calls tools/list to discover what a server offers, then tools/call to execute. The server describes each tool with a name, description, and JSON Schema for its inputs.

To connect Claude Code, add the server with claude mcp add and sign in when prompted. To use an API key instead, set SENDIO_API_KEY where your client reads it from the environment.

# Add the hosted server, then run /mcp in Claude Code and sign in when prompted
claude mcp add --transport http sendio https://api.send.io/mcp

# To use an API key instead, set SENDIO_API_KEY where your client reads it from the environment
export SENDIO_API_KEY="your_api_key"

For free-inbox testing without an account, use the local stdio mode:

sendio mcp serve --tools free-inbox

This exposes a 5-tool set (free_inbox_create, free_inbox_list, free_inbox_wait_for_email, free_inbox_read, and free_inbox_connect) without requiring sign-in. The hosted server exposes 160 tools spanning email sending and listing, domains, API keys, webhooks, suppressions, templates, logs, agent inboxes, automations, and events.

Programmatic inbox filtering with Claude Code

Filtering inbox data before it reaches the context window prevents token overflow and keeps the agent focused on relevant messages. The search_inbox tool in the examples below is illustrative: it doesn't appear in send.io's documented MCP tool list, so run tools/list against your server to confirm the exact tool names and parameter schemas. The pattern assumes a search tool that accepts filters for folder, contact, date range, and read status, and returns a paginated list of message metadata.

Reading inbox data via Claude Code

The primary tool for inbox retrieval is search_inbox, which accepts these parameters:

  • folder: Filter by folder name (e.g., INBOX, Sent, Archive)
  • contact: Filter by sender or recipient email address
  • thread_id: Illustrative filter to return only messages in a single thread. send.io's documented MCP tool list doesn't describe this parameter, so confirm the parameter name in your server's tools/list schema. The threading example later in this article uses it.
  • since: ISO 8601 timestamp for messages after this date
  • until: Timestamp for messages before this date. This example assumes the same ISO 8601 format as since, so confirm the accepted format in your server's tools/list schema.
  • unread: Illustrative flag to return only unread messages. send.io's documented MCP tool list doesn't describe an unread parameter, so confirm the parameter name and type in your server's tools/list schema.
  • limit: Maximum number of messages to return per page
  • cursor: Pagination cursor for retrieving the next page

Example tool call:

{
"tool": "search_inbox",
"arguments": {
"folder": "INBOX",
"unread": true,
"limit": 20,
"since": "2026-11-20T00:00:00Z"
}
}

A metadata-only search response typically lists fields like message_id, subject, from, to, and date and omits the full body. The exact fields depend on your server's schema, so check the tools/list output, and don't assume a field such as has_attachments exists unless the schema declares it. Fetch full payloads only for messages that match your criteria.

Filter by folder or label

Folders in IMAP-style inboxes map to labels in some email systems. Standard folders typically include INBOX, Sent, Drafts, Archive, and Spam, and some providers also let you create custom labels through their API.

To retrieve only messages from the Sent folder:

{
"tool": "search_inbox",
"arguments": {
"folder": "Sent",
"limit": 10
}
}

Filtering by folder reduces the result set before pagination, which matters when you're working with inboxes that accumulate thousands of messages over time.

Filter by contact or sender

In this illustrative example, the contact parameter is meant to match against both the from and to fields, which is useful when you need all messages in a thread regardless of direction. send.io's documented MCP tool list doesn't describe this matching behavior, so confirm how your server handles it in the tools/list schema before relying on it. To find all messages from a specific user:

{
"tool": "search_inbox",
"arguments": {
"contact": "user@example.com",
"since": "2026-11-01T00:00:00Z"
}
}

This returns both messages from user@example.com and messages sent to that address, giving you the full conversation context without multiple queries.

Managing large inbox message volumes

The search_inbox tool paginates results using a cursor-based system. Each response includes a next_cursor field if more results exist. When next_cursor is null, you've reached the end of the result set.

Rate limits apply per team. send.io's documented limit is 10 requests per second, and exceeding it returns a 429 status with the error name rate_limit_exceeded. Respect the Retry-After header when present and fall back to exponential backoff when it isn't.

For inboxes with high message volume, use date range filters (since and until) to partition queries into smaller chunks rather than paginating through thousands of results in a single session.

Accessing inbox payloads with Claude Code

In this illustrative example, the fetch_message tool stands in for a full-payload retrieval call. It doesn't appear in send.io's documented MCP tool list. The closest documented tools are get-received-email, which returns a received email with its headers, HTML, and text. Next is list-received-email-attachments, which lists attachments with download URLs. The third is get-received-email-attachment, which gets one attachment of a received email with its download URL. Run tools/list to confirm the exact names and return fields. Full payloads carry the body, headers, and attachment metadata, so token use grows with message length. Fetch them only after filtering to the specific messages you need.

Retrieve specific messages by ID

Once search_inbox returns message IDs, fetch the full payload:

{
"tool": "fetch_message",
"arguments": {
"message_id": "msg_01HXYZ123ABC"
}
}

A typical full-payload response includes fields such as:

  • id: Unique message identifier
  • thread_id: Thread identifier for grouping related messages
  • from: Sender address
  • to: Array of recipient addresses
  • cc: Array of CC addresses
  • subject: Message subject line
  • date: ISO 8601 timestamp
  • headers: Email headers as key-value pairs
  • body_text: Plain text body
  • attachments: Array of attachment metadata (filename, content_type, size, content_id)

Processing structured email fields

Headers contain routing information, authentication results (SPF, DKIM, DMARC), and threading metadata (In-Reply-To, References). For agent workflows, the most useful headers are:

  • Message-ID: Unique identifier for deduplication
  • In-Reply-To: Message-ID this message replies to
  • References: Chain of Message-ID values in the thread
  • X-Spam-Score: Spam filter score (if present)

Extract these programmatically rather than asking the LLM to parse raw headers:

message = fetch_message(message_id="msg_01HXYZ123ABC")
thread_id = message["thread_id"]
in_reply_to = message["headers"].get("In-Reply-To")

Retrieving text and HTML message payloads

Email bodies come in two formats: plain text and HTML. In this illustrative example, body_text holds the plain text version and body_html holds the HTML version. send.io's documented MCP tool list describes get-received-email as returning a received email with its headers, HTML, and text, but it doesn't confirm these exact field names, so check the tools/list schema for the real ones. Not all messages have both formats.

For LLM processing, prefer body_text because it consumes fewer tokens and avoids HTML parsing complexity. If body_text is empty but body_html exists, strip HTML tags before adding to context:

from html.parser import HTMLParser

class HTMLStripper(HTMLParser):
def __init__(self):
super().__init__()
self.text = []

def handle_data(self, data):
self.text.append(data)

def get_text(self):
return ''.join(self.text)

stripper = HTMLStripper()
stripper.feed(message["body_html"])
plain_text = stripper.get_text()

This pre-processing step reduces token consumption and removes markup noise that doesn't contribute to understanding.

Parsing attachments and nested message threads

Attachments and threading add complexity to inbox retrieval. Attachments arrive as Base64-encoded data or as references to separate fetch operations, and threading requires following In-Reply-To chains to reconstruct conversation context.

Extracting files with Claude Code MCP

The fetch_message response includes an attachments array with metadata for each file:

{
"attachments": [
{
"filename": "invoice.pdf",
"content_type": "application/pdf",
"size": 45230,
"content_id": "att_01HXYZ456DEF"
}
]
}

In this illustrative example, fetch_attachment stands in for a call that retrieves attachment content by content_id. It doesn't appear in send.io's documented MCP tool list, which instead lists list-received-email-attachments for listing a received email's attachments with download URLs and get-received-email-attachment for getting one attachment with its download URL, the closer match for a single-attachment fetch. Run tools/list to confirm the exact tool name and required arguments before relying on this call:

{
"tool": "fetch_attachment",
"arguments": {
"message_id": "msg_01HXYZ123ABC",
"content_id": "att_01HXYZ456DEF"
}
}

In this illustration, the response returns Base64-encoded file data, which you decode before processing. The documented path works differently: list-received-email-attachments and get-received-email-attachment return download URLs rather than Base64 data, so the Base64 shape here is the illustration, not documented behavior.

import base64

attachment = fetch_attachment(message_id="msg_01HXYZ123ABC", content_id="att_01HXYZ456DEF")
file_data = base64.b64decode(attachment["data"])

with open("invoice.pdf", "wb") as f:
f.write(file_data)

For text-based attachments (CSV, JSON, plain text), decode and add the content directly to context. For binary files (PDFs, images), save to disk and process with appropriate tools rather than adding raw bytes to the prompt.

Tracking Claude Code email reply chains

Threading relies on the thread_id field and the In-Reply-To / References headers. All messages in a thread share the same thread_id, so you can fetch the full conversation. The thread_id filter in this example is illustrative and isn't in send.io's documented MCP tool list, so confirm it in your server's tools/list schema:

{
"tool": "search_inbox",
"arguments": {
"thread_id": "thread_01HXYZ789GHI"
}
}

This returns all messages in the thread, ordered by date. The References header contains a space-separated list of Message-IDs representing the reply chain, which you can use to reconstruct the conversation tree if you need parent-child relationships.

For agent workflows that need to reply to a message, include the original Message-ID in the In-Reply-To header and append it to References when sending the reply.

Configuring Claude Code request limits

Claude Code's MCP client respects rate limits returned by the MCP server. When the server returns a 429 error, check whether the response includes a Retry-After header. If it does, wait for that duration before retrying, and otherwise fall back to exponential backoff.

Implement exponential backoff for failed requests:

import time

def fetch_with_retry(message_id, max_retries=3):
for attempt in range(max_retries):
try:
return fetch_message(message_id=message_id)
except RateLimitError as e:
if attempt == max_retries - 1:
raise
wait_time = int(e.retry_after) if hasattr(e, 'retry_after') else 2 ** attempt
time.sleep(wait_time)

This prevents tight retry loops that compound rate limit issues.

Controlling token consumption in MCP sessions

Claude Code's context window holds conversation, files, skills, and path rules, and auto-compacts when full by silently dropping content in a fixed priority order. Window size ranges from 200K to 1M tokens depending on model and provider, so check Anthropic's documentation for the limit that applies to your setup. The system prompt and CLAUDE.md files also consume context before any message is read. By default, Claude Code loads only MCP tool names and defers each server's full schemas through tool search. Fully loading a large server's schemas can add tens of thousands of tokens, and one source reports roughly 42,000 tokens for a single server, which is a single-source estimate. Budget for that overhead up front, enable only the tools a task needs, and use /context to see where tokens go.

Filtering inbox data to save tokens

Metadata-only responses from search_inbox consume far fewer tokens than full payloads from fetch_message. A metadata response carries just the fields you filter on (message ID, subject, from, date), while a full payload adds the body and headers, so token use grows with message length.

Filter aggressively before fetching full payloads:

  1. Use search_inbox with folder, contact, and date filters to narrow the result set
  2. Review subjects and senders in the metadata response
  3. Fetch full payloads only for messages that match your criteria
  4. Extract only the fields you need (body_text, specific headers) rather than adding the entire response to context

Pre-processing email for token efficiency

Strip quoted reply text, email signatures, and legal disclaimers before adding message bodies to context. These elements repeat across messages in a thread and consume tokens without adding information.

def clean_email_body(body_text):
# Remove quoted text (lines starting with >)
lines = body_text.split('\n')
cleaned = [line for line in lines if not line.startswith('>')]

# Remove signature (everything after "-- " on its own line)
text = '\n'.join(cleaned)
if '\n-- \n' in text:
text = text.split('\n-- \n')[0]

return text.strip()

Quoted replies, signatures, and legal footers add tokens without adding new information, so stripping them reduces context use in active reply threads.

Optimizing Claude Code inbox retrieval

One guide recommends typing /compact manually when context reaches around 40-50% to summarize the conversation and reset the context window while preserving the essential state. Compacting before auto-compaction fires prevents it from dropping tool call results you still need.

For long-running inbox processing sessions:

  1. Set a turn budget (maximum number of tool calls) before triggering human review
  2. Extract and save important data to files rather than keeping it in context
  3. Use /compact between processing batches of messages
  4. Monitor token usage with /cost to avoid hitting the limit mid-task

Automating test data extraction from Claude Code

Production inbox messages contain edge cases that synthetic test data misses. Real users send malformed replies, include unexpected attachments, and write subject lines that break your parsing logic. Extracting these messages into a golden dataset lets you measure agent performance against real conditions.

Identifying real-world production edge cases

Edge cases in email workflows include:

  • Messages with missing or malformed headers
  • Attachments with unexpected content types or sizes
  • Reply chains with broken threading (missing In-Reply-To headers)
  • Messages with only HTML body and no plain text version
  • Subject lines with special characters or encodings
  • Messages from addresses that don't match expected patterns

Filter for these patterns. The has_attachments filter in this example is an illustrative field, so confirm it in your server's tools/list schema:

{
"tool": "search_inbox",
"arguments": {
"has_attachments": true,
"since": "2026-11-01T00:00:00Z"
}
}

Review the results for messages that caused agent failures in production logs.

Tagging conversations for evaluation

A golden dataset is a hand-labeled set of test data used to evaluate a non-deterministic LLM output by computing precision, recall, and F1 per field, plus an overall LLM-as-judge agreement check against human labels.

Structure each test case with:

{
"test_id": "email_extraction_001",
"input": {
"message_id": "msg_01HXYZ123ABC",
"task": "extract_verification_code"
},
"expected_output": {
"code": "123456",
"confidence": "high"
},
"metadata": {
"source": "production",
"date": "2026-11-15",
"edge_case": "html_only_body"
}
}

Tag each case with the edge case it represents so you can measure performance per category.

Piping Claude Code inputs to evaluators

Export retrieved messages to a JSONL file for batch evaluation:

import json

test_cases = []

for message_id in production_failures:
message = fetch_message(message_id=message_id)
test_case = {
"test_id": f"email_{message_id}",
"input": {
"body_text": message["body_text"],
"subject": message["subject"],
"from": message["from"]
},
"expected_output": {
# Fill in based on manual review
},
"metadata": {
"message_id": message_id,
"thread_id": message["thread_id"],
"date": message["date"]
}
}
test_cases.append(test_case)

with open("golden_dataset.jsonl", "w") as f:
for case in test_cases:
f.write(json.dumps(case) + "\n")

Run your agent against this dataset and compare outputs to expected values using your evaluation harness.

Checklist for building a golden dataset from inbox messages:

  • Identify production failures or edge cases from agent logs
  • Search inbox for messages matching failure patterns
  • Fetch full payloads for identified messages
  • Manually label expected outputs for each test case
  • Tag each case with edge case category
  • Export to JSONL format with input/expected_output/metadata structure
  • Run evaluation harness against dataset
  • Measure precision, recall, and F1 per extracted field
  • Add failing cases to regression test suite
  • Update dataset quarterly with new production edge cases

If your current setup splits inbound and outbound across two providers, send.io handles both under one API. Provision a free instant agent mailbox and connect it to Claude Code via the local MCP server to test inbox retrieval in a sandbox.

FAQs

How can Claude Code read and search an inbox?

Claude Code acts as an MCP client that issues tool calls to an MCP server like send.io. Connect with claude mcp add --transport http sendio https://api.send.io/mcp and sign in when prompted, or set SENDIO_API_KEY where your client reads it from the environment to use an API key instead. Then use a search tool (search_inbox in this article's examples) with filters for folder, contact, and date range to retrieve message metadata, and a fetch tool (fetch_message in these examples) to get full payloads. The tool names search_inbox and fetch_message in this article are illustrative and don't appear in send.io's documented MCP tool list, which includes get-received-email for retrieving a received email. Run tools/list to confirm the exact names.

What happens when pagination hits the rate limit?

The API typically returns a 429 status code, and the response may include a Retry-After header indicating how many seconds to wait. Implement exponential backoff in your retry logic, and respect the header value when it's present, to avoid compounding rate limit issues.

Can Claude Code access attachments directly?

Yes, but you need two tool calls. In this article's illustrative examples, fetch_message returns attachment metadata including a content_id, then fetch_attachment retrieves the file data, which you decode before processing or saving to disk. Neither name appears in send.io's documented MCP tool list, which lists get-received-email, list-received-email-attachments (attachments with download URLs), and get-received-email-attachment (one attachment with its download URL). Run tools/list to confirm the exact tool names and return format.

How can you prevent context window overflow?

Filter aggressively with a search call (search_inbox in this article's illustrative examples) before fetching full payloads, strip quoted text and signatures from message bodies, and consider running /compact when context reaches roughly 40-50% capacity, a threshold one guide recommends. Extract and save important data to files rather than keeping everything in the conversation context.

What tool calls does Claude issue to fetch email?

Claude Code issues tools/list to discover available tools when connecting to the MCP server, then tools/call with a search tool (search_inbox in this article's examples) for metadata retrieval and a fetch tool (fetch_message in these examples) for full payloads. This article's examples use the illustrative names search_inbox and fetch_message. send.io's documented MCP tool list includes get-received-email, list-received-email-attachments, and get-received-email-attachment, so confirm the real names with tools/list. All communication uses JSON-RPC 2.0 over HTTP or stdio transport.

Key terms glossary

MCP (Model Context Protocol): A protocol that uses JSON-RPC 2.0 to let AI assistants like Claude Code connect to external tools and data sources. The client calls tools/list to discover capabilities, then tools/call to execute them.

Tool calling: The mechanism by which an LLM issues structured requests to external functions. Claude Code sends tool calls to MCP servers, which execute the requested operation and return structured results.

Scoped API key: An authentication credential limited to specific resources or permissions. send.io's agent inboxes use scoped keys limited to a specific inbox or pod, preventing credential leaks from exposing broader account access.

Golden dataset: A hand-labeled set of test cases used to evaluate LLM outputs. Each case pairs an input with expected outputs, enabling measurement of precision, recall, and F1 scores per extracted field.

Evaluation harness: Code that runs an LLM against a golden dataset and measures performance metrics. It catches regressions by comparing current outputs to expected results and flagging cases where accuracy drops below thresholds.

Context window: The maximum number of tokens an LLM can process in a single conversation. Claude Code's context window includes the system prompt, conversation history, tool schemas, and retrieved data, and it auto-compacts when full by dropping older content. The size varies by model and provider, so check Anthropic's documentation for the limit that applies to your setup.