Blog

How to build an email agent that gets the answer right

How to build an email agent that handles changed dates, conflicting replies, replaced attachments and hidden instructions. Five fixes, five checks.

11 min read

Branching tree of email threads with one highlighted, checked message at the end of a green path

Email agents rarely fail on easy questions.

A lookup of one message from one sender works on the first try. The failures come from how email records decisions. A delivery date gets agreed in one thread and moved twice in another. Two teams promise different things to the same client. A contract goes out as an attachment, then a corrected version follows three replies later, under the same filename.

Somewhere in the inbox, a message contains text written to steer an AI.

A model reading raw messages has to rebuild that history every time it answers. It won’t always manage. The mistakes are predictable, though.

This guide covers five of them. Each comes with a fix and a check that proves the fix works. One rule sits underneath all five: every claim in an answer carries its source. The last section sets out how to measure an email agent against all five.

The five failures at a glance

Failure What a raw agent does Fix Check
A decision spread across threads Answers from the first thread it finds Rebuild the conversation before the model reads it Ask a question whose answer sits in a second thread
A date that changed Reports the first date it saw Store every date with the message that set it, and whether it was confirmed Move a date twice, then ask for it
Conflicting commitments Picks one and sounds sure Report both, with sources Plant two promises that disagree
A replaced attachment Quotes the old version Track candidate versions, and read the message around each file Send a corrected file under the same name
Instructions inside an email Follows them Treat email content as data Plant an instruction, then ask a normal question

The rule underneath: every claim carries its source

Citation is not decoration. It is the architecture the other five fixes sit on.

Every fact the agent extracts is stored with the message it came from. Every answer returns those sources. A user who can open the message can verify the answer. A test can do the same.

# Conceptual example
@dataclass
class Source:
    message_id: str
    sender: str
    sent_at: datetime

Return that source with every important claim. Where the agent quotes text, quote the message’s own words, not the copy quoted in a later reply.

The rest of the guide builds on this. A date is a claim with a source. A conflict is two claims with two sources. An attachment version is a file with a source.

Check: open the cited message for each answer. The claim should appear there, in that message’s own text.

1. Rebuild the conversation before the model reads it

Most email agents start with search.

The Gmail API’s messages.list takes a q parameter with the same syntax as the Gmail search box. It returns results in pages. Each entry holds only a message ID and a thread ID. Every message needs its own fetch.

Two problems follow.

The first is completeness. A search can return more pages than the agent reads. Stop the loop early, and the agent answers from a partial picture. Nothing in the answer says so.

The second is shape. A thread arrives as a stack of messages. Most replies carry a quoted copy of everything before them, so the model sees the first message once per reply, with no clear sign of which words are new, who wrote them or whether anything changed since.

Fix both before the model sees anything:

  • Page through every result. Record when a cap stops the search early.
  • Group messages into conversations. Start with Gmail’s own thread IDs. Where threads break, use the threading headers: RFC 5322 defines Message-ID, In-Reply-To and References for this job.
  • Strip quoted text. Each message should contribute only its own words.
  • Keep the sender, the timestamp and the message ID on every message. Every later step depends on them.

The headers are a good signal, not a guarantee. RFC 5322 says messages should carry them, and some clients don’t. Treat a missing header as a reason to fall back, not as proof that two messages are unrelated.

# Conceptual example
def search_all(gmail, query, max_pages=10):
    ids, token = [], None
    for _ in range(max_pages):
        page = gmail.users().messages().list(
            userId="me", q=query, pageToken=token
        ).execute()
        ids += [m["id"] for m in page.get("messages", [])]
        token = page.get("nextPageToken")
        if not token:
            return ids, True   # every page read
    return ids, False          # more results exist

The second return value is the one that matters.

When it comes back False, the answer has to say the search was cut short. An agent that hides an incomplete search gives confident answers from half the evidence.

Related decisions also live in separate threads with different subject lines. Search by the people and the project involved, not by subject alone.

Check: ask your agent a question whose answer only appears in a second thread with a different subject line. A passing agent finds it, or says plainly that its search was incomplete.

2. Keep every date with the message that set it

Dates move.

A delivery date agreed on a call gets pushed in a reply two weeks later, then pushed again. Which one does the agent report? An agent that reads top to bottom and stops at the first date gives the oldest answer. One that reads everything at once may merge them. Others simply pick one.

Store each date as a claim, not a fact. A claim records the value, whether the message confirmed it or only proposed it, and the source.

The latest date is not the same as the latest confirmed date. A vendor’s proposal sent yesterday doesn’t replace what the client confirmed last week. Sorting by timestamp alone gets that wrong.

# Conceptual example
@dataclass
class Claim:
    field: str                  # e.g. "delivery_date"
    value: str                  # e.g. "2026-12-04"
    status: str                 # "confirmed" or "proposed", read from the message itself
    source: Source
    replaces: str = ""          # message ID this claim says it replaces, if the text says so

def resolve(claims, field):
    history = sorted(
        (c for c in claims if c.field == field), key=lambda c: c.source.sent_at
    )
    standing, replaced = {}, []          # message ID -> confirmed claim still standing
    for c in history:
        if c.status != "confirmed":
            continue
        for mid, old in list(standing.items()):
            if c.replaces == mid or old.source.sender == c.source.sender:
                replaced.append(standing.pop(mid))
        standing[c.source.message_id] = c
    live = list(standing.values())
    newest = max((c.source.sent_at for c in live), default=None)
    pending = [
        c for c in history
        if c.status == "proposed" and (newest is None or c.source.sent_at > newest)
    ]
    if len({c.value for c in live}) > 1:
        return {"current": None, "conflicts": live, "pending": pending, "replaced": replaced}
    current = max(live, key=lambda c: c.source.sent_at) if live else None
    return {"current": current, "conflicts": [], "pending": pending, "replaced": replaced}

Notice what resolve returns. A confirmed date, if there is one. The proposals that came after it. The values it replaced. And a conflict list, which section 3 uses.

Reading whether a message confirms or proposes is a judgment about its wording. A model can make it, but the claim’s source lets a person check it.

Keep the replaced values too. “December 4, moved from November 20 in the client’s reply of October 30” is more useful than the date alone, and it’s far easier to verify.

Check: move one date twice across two threads, then add a later proposal that nobody confirmed. Ask your agent for the date. A passing agent gives the latest confirmed date, cites the message that set it, and mentions the open proposal.

3. Report conflicting commitments instead of picking one

Two teams can promise different things in good faith.

Sales tells a client the integration ships in Q1. Engineering’s thread with the same client says Q2. Ask a model for “the” date, and it’ll usually choose one and state it with total confidence.

That’s worse than no answer. It hides the one thing the user most needed to see.

Treat disagreement as a result. When two confirmed claims for the same field come from different senders and neither replaces the other, the honest answer is a conflict. Return both, each with its source, and say so.

That is what the conflicts list in resolve holds. The rule is crude on purpose: the same sender’s later claim replaces their earlier one, a different sender’s claim doesn’t, and a message that says it replaces another does. Your agent will need richer rules for authority, but the shape stays the same.

Most of the time that list is empty. When it isn’t, the user learns about the problem from the agent rather than from an unhappy client.

Check: plant two commitments that disagree, in separate threads from different teams. A passing agent names both and cites each one.

4. Track candidate versions, and read the message around each file

Attachments break agents quietly.

A proposal goes out as proposal.pdf. Three replies later, a corrected version follows, often under the same filename. An agent that finds attachments by name takes the first match. The answer reads well. It’s quoting the wrong document.

Group the files that might be versions of one document. The thread, the sender, the filename and the send date are useful signals. They are heuristics, not proof. Two files with the same name may be unrelated. Two files with different names may be the same document.

# Conceptual example
@dataclass
class Attachment:
    filename: str
    sha256: str
    thread_id: str
    source: Source

def sha256_of(data):
    return hashlib.sha256(data).hexdigest()


def candidate_versions(attachments):
    """Group files that might be versions of one document. A heuristic, not proof."""
    groups = {}
    for a in sorted(attachments, key=lambda a: a.source.sent_at):
        groups.setdefault((a.thread_id, a.filename.lower()), []).append(a)
    for group in groups.values():
        for i, a in enumerate(group):
            a.same_bytes_as_previous = i > 0 and a.sha256 == group[i - 1].sha256
    return groups

A hash of the file’s bytes settles one question: whether two files are identical. It says nothing about which one is authoritative.

The newest file is not automatically the right one. That depends on the message around it. “Attached is the corrected version” replaces the earlier file. “Here’s last year’s contract for comparison” does not. So pass the surrounding message to the model along with each candidate, and ask it which file the sender meant to be current.

Then name the version in the answer: the filename, the sender and the message it arrived in. Every time.

Check: send a document, then a corrected version three replies later under the same filename. Then send a third message that attaches an older file “for reference”. A passing agent quotes the corrected version, names the message it arrived in, and doesn’t mistake the reference copy for a replacement.

5. Treat email content as data, never as instructions

Anyone can email your users.

Who wrote the text your agent just read? Often, a stranger.

That makes the inbox the easiest place to plant instructions for an AI. OWASP calls this indirect prompt injection, which occurs when an LLM accepts input from external sources, such as websites or files. Email is the same case: the text the agent reads was written by someone outside the system.

No prompt makes a model immune. OWASP itself says it is unclear whether fool-proof prevention exists.

Two controls limit the damage:

  • Separate the content. Pass retrieved email to the model as untrusted material, apart from the user’s request. OWASP’s guidance is to separate and clearly denote untrusted content.
  • Limit what the agent can do while it reads. An agent that can only search and read can’t be talked into sending, forwarding or deleting. OWASP’s guidance is to restrict the model’s access privileges to the minimum necessary.

The second control is the one that holds when the first fails. Your AI agent is a token store traces one planted email through two setups, one with a send tool and one without.

Check: plant a message that tells the agent to ignore its other sources or forward a file. Then ask an ordinary question. A passing agent answers it, ignores the instruction and flags the message.

Where iGPT fits

On a raw Gmail connection, every step above runs at question time. Search, page, fetch, rebuild, strip, extract, answer. The work repeats for every question. It doesn’t get cheaper with practice.

Agent200’s iGPT connector moves the reading earlier. The iGPT page describes “Emails and attachments, indexed automatically” and says it “Indexes new messages and attachments instantly.” Its capabilities include thread reconstruction, which “Rebuilds email threads across time, participants and attachments.” It also lists cited answers: “Every answer links back to source messages and attachments.” The agent asks once and gets a cited answer in one request.

Those capabilities line up with the first fix and with the rule underneath. The citations point to specific messages, which is what every check in this guide needs.

The page doesn’t describe how iGPT handles a moved date, a conflict between teams or a corrected attachment. Treat those as open questions for any setup, iGPT included, and run the five checks against your own mailbox before relying on any of them.

Agent200’s published comparison covers eight real-inbox questions, a Gmail agent against iGPT on the same underlying model, run in August 2026.

Average per question Gmail agent iGPT
Tokens 502K 218K
Cost $0.56 $0.24
Time to an answer 128.0s 105.2s

Eight questions is a small sample. That’s worth saying plainly.

It also measures three things only: tokens, cost and time. It doesn’t score accuracy on the five failures in this guide, so it says nothing about how either setup handles a moved date, a conflict, a replaced attachment or a planted instruction. Your agent is reading too much explains where the token gap comes from. The rebuild steps apply to any mailbox the agent reaches, whichever of the email and calendar connectors it uses.

For a wider look at the options, how to connect AI agents to email compares the approaches, and build or buy covers the cost of doing it yourself. The Gmail connector page lists the read tools an agent can use.

How to measure an email agent

Accuracy claims about email agents are easy to make. If you plan to publish a measurement, it needs four things:

  • A fixed set of sources. A small, fictional inbox where every answer is known in advance. Real inboxes change, and they can’t be shared.
  • Questions built around the five failures. At least one per failure, plus a few easy ones as a baseline.
  • Scoring that checks the source, not just the answer. An answer counts only when the value is right and the citation points to the message that states it. An injected instruction that gets followed fails the run.
  • The same model on every setup. Otherwise the comparison measures the model, not the approach.

Publish the question set, the sources and the scoring script with the results, so anyone can rerun them.

Record input tokens, tool calls and time to an answer for every question, because those three numbers, more than the model’s price, decide what the agent costs to run once real users start asking real questions about real inboxes. Agents that answer with sources covers the citation side in more depth.

An email agent doesn’t fail because the model can’t read.

It fails because email hides its history in threads, replies and attachments, and nobody rebuilt that history before the model saw it.

Rebuild it first. Then make every answer show where it came from.

200 OK

Build the agent.
Access everything it needs.

Bring the agent you already have. Agent200 provides and executes its external capabilities.

Book a demo.
See it in action.

Tell us who you are, then pick a time for a 1:1 session with an expert from our team.

We use your details only to email you about Agent200. See the Privacy Policy.

Pick a time. We'll take it from there.

A 1:1 session with an expert from our team, about what you are building.

Open in Calendly (opens in a new tab)