Email threading for AI agents
Email threads rest on three headers. Every message has a Message-ID. A reply names its parent in In-Reply-To and lists the chain in References. An agent that replies must set both, keep the subject, and read only the new part of each message so quoted history does not flood the model.
Updated
Which headers make an email thread?
| Header | Holds | In a reply |
|---|---|---|
Message-ID | A unique ID for this one message | A new one |
In-Reply-To | The parent's ID | The parent's Message-ID |
References | The chain of earlier IDs | The parent's References, then the parent's Message-ID |
Subject | A line for the reader | The parent's, with one Re: |
RFC 5322 section 3.6.4 gives the rule. If the parent has no References but has a single ID in In-Reply-To, start the chain from that ID.
How do you build a correct reply in Python?
Pass the raw bytes of the message you are answering. The standard library does the rest.
from email import message_from_bytes, policy
from email.message import EmailMessage
from email.utils import make_msgid
# 998 is the longest line the standard allows. It keeps long IDs from being rewritten.
SEND = policy.SMTP.clone(max_line_length=998)
def build_reply(raw_parent: bytes, from_addr: str, text: str) -> EmailMessage:
parent = message_from_bytes(raw_parent, policy=policy.default)
reply = EmailMessage(policy=SEND)
reply["From"] = from_addr
reply["To"] = str(parent["Reply-To"] or parent["From"])
subject = str(parent["Subject"] or "")
reply["Subject"] = subject if subject.lower().startswith("re:") else f"Re: {subject}"
reply["Message-ID"] = make_msgid(domain=from_addr.split("@")[1])
parent_id = str(parent["Message-ID"] or "").strip()
chain = str(parent["References"] or "").split()
if not chain and len(str(parent["In-Reply-To"] or "").split()) == 1:
chain = str(parent["In-Reply-To"]).split()
if parent_id:
reply["In-Reply-To"] = parent_id
chain.append(parent_id)
if chain:
reply["References"] = " ".join(chain)
reply.set_content(text)
return replyHand the result to smtplib.SMTP.send_message. It replies to Reply-To when there is one, as mail programs do, so check that address before an agent sends anything private.
Why do replies lose their thread on Python 3.12?
Many message IDs are longer than a default header line. In our test, Python 3.9.6, 3.11.15 and 3.12.13 with the default policy rewrote a long ID in In-Reply-To and References into encoded words:
In-Reply-To: =?utf-8?q?=3CCAF+xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx?=That header no longer holds a readable ID, so the other side may not match it. Python 3.13.13 and 3.14.8 left the same ID intact. The SEND policy above fixes it on all five: it allows lines of 998 characters, the most RFC 5322 permits.
How do you group messages into threads?
import re
MSG_ID = re.compile(r"<[^<>\s]+>")
def group_threads(messages):
"""Group parsed messages that share any ID, in whatever order they arrived."""
root = {}
def find(x):
root.setdefault(x, x)
while root[x] != x:
root[x] = root[root[x]]
x = root[x]
return x
keyed = []
for n, msg in enumerate(messages):
headers = (msg["Message-ID"], msg["In-Reply-To"], msg["References"])
ids = MSG_ID.findall(" ".join(str(h or "") for h in headers)) or [f"<none-{n}>"]
for other in ids[1:]:
root[find(other)] = find(ids[0])
keyed.append((ids[0], msg))
threads = {}
for key, msg in keyed:
threads.setdefault(find(key), []).append(msg)
return list(threads.values())It joins messages that share any ID, so arrival order does not matter and a missing message does not split a chain. It leaves two messages apart when they share a subject and nothing else. That is deliberate: anyone can copy a subject.
What does the Gmail API need to keep a thread?
Google lists three conditions for adding a message to a thread: the threadId is in your request, References and In-Reply-To follow the standard, and the Subject headers match.
How should an agent read a thread?
- New part only. Quoted history repeats everything and grows with each turn.
- Who said what. Label each message with its direction and sender, or the model may take a stranger's line as its own earlier promise.
- Trust the worst message. One hostile message taints the context it sits in.
- Check who is writing. A reply inside a real thread can come from a changed address or a taken over account. See thread hijacking.
- Reply to the message. A fresh send with
Re:typed in the subject drops the headers.
Which message should an agent answer?
Answer the latest message, and only when it is inbound, readable and written by something that is not an autoresponder. Then cap the number of replies per thread, because two machines can answer each other without end. With a thread from the Trotta Mail SDK:
def message_to_answer(thread, max_replies=5):
"""The message an agent should answer now, or None."""
messages = thread["messages"]
sent = [m for m in messages if m["direction"] == "outbound" and m["status"] in ("queued", "sent")]
if not messages or len(sent) >= max_replies: # a loop with another machine stops here
return None
last = messages[-1]
if last["direction"] != "inbound" or last["withheld"] or last["extracted"]["is_automated"]:
return None
return lastOn our test threads it returned the new inbound message, and nothing when the last entry was the agent's own reply or draft. is_automated is a hint, not proof, which is why the cap is there too. When it returns None for a thread you expected to answer, tell your human instead of guessing.
Which mistakes break a thread?
| Mistake | What you see | Fix |
|---|---|---|
| Sending a new message instead of a reply | A second conversation | Set In-Reply-To and References, or use a reply call |
Reusing the parent's Message-ID | Two messages with one identity | Make a new ID for every message |
Keeping only the last ID in References | Gaps when a message is missing | Append to the chain, never replace it |
| Changing the subject mid thread | Gmail's API will not file it there | Keep the subject, add Re: once |
| Sending long IDs from Python 3.12 or older | Encoded words in the header | Serialize with a 998 line limit |
How does Trotta Mail handle threads?
Each inbox keeps its own conversations, and every message carries a thread_id. The reply call sets the recipient, subject and threading headers. The context call returns the conversation as one block for a model: earlier messages as their new part, the latest in full, inside boundaries a sender cannot fake, with a trust level.
import os
from trottamail import TrottaMail
mail = TrottaMail() # reads TROTTA_MAIL_API_KEY
msg = mail.messages.get(os.environ["MESSAGE_ID"])
# The whole conversation, oldest first. Held messages have no content.
thread = mail.threads.get(msg["thread_id"])
for m in thread["messages"]:
new_part = m["extracted_text"] or m["text"] or "(withheld)"
print(m["direction"], m["from"]["address"], "|", new_part[:60])
# One block for a model, with boundaries around each message.
context = mail.threads.context(msg["thread_id"])
# A reply sets recipient, subject and threading headers for you.
reply = mail.messages.reply(msg["id"], text="Thanks, the 20th works.")
print(reply["subject"], reply["thread_id"] == msg["thread_id"], reply["in_reply_to"] == msg["message_id"])
print(reply["references"])
print(context["trust"], context["messages"])A held message appears in its thread with no content. extracted_text is null in lists, so fetch the message or the thread to get it. Over plain HTTP the calls are GET /v1/threads/{id}, GET /v1/threads/{id}/context and POST /v1/messages/{id}/reply: see the API reference.
Questions
What is the difference between In-Reply-To and References?
In-Reply-To names the message being answered. References carries the chain of earlier IDs, which lets a program rebuild the thread when some messages are missing.
Does a matching subject put emails in one thread?
Some mail programs also group by subject. Do not rely on it, and never let a copied subject grant trust.
How do I keep a long thread out of the model's context limit?
Pass each earlier message as its new part, drop signatures and cap the number of messages. Fetch an older one again when the task needs it.
Can a sender fake a thread?
Yes. These headers are written by the sender. They organize mail and prove nothing about who wrote it.