To track whether a person replied to your AI agent, store the thread_id of every email the agent sends. A reply is an inbound message in that thread that is not an automatic response. Mark it the moment a message.received event arrives, and run a timer for the silence case, because no reply means no event. Before every follow-up, re-read the thread so a missed event never turns into a nudge to someone who already answered. Reply rate is then replied threads divided by threads you actually reached.
This guide builds that loop in Python against the SentFromAI email API. The calls match the public OpenAPI schema and docs as checked on November 10, 2026. The pattern carries over to any inbox API that groups mail into threads and tells you which direction each message went.
Why replies, not opens
Open tracking relies on a remote image loading when the message is displayed. Apple's Mail Privacy Protection "prevents senders from seeing if you've opened the email message they sent you" (Apple), and many clients block remote images by default. An open is a weak signal for a person and a meaningless one for an agent deciding what to do next.
A reply is different. It is a message in your agent's inbox that someone chose to write, it carries the content your agent has to act on, and it is the condition that should stop every automated follow-up. SentFromAI's webhook events cover received mail, delivery, bounces, complaints and rejections. They do not include opens, and this design does not need them (receiving docs).
The state to keep for each outreach
Keep one record per conversation your agent starts. The thread is the join key between what you sent and what comes back.
| Field | Why you need it |
|---|---|
id |
Your own outreach ID; it also seeds idempotency keys |
inbox_id, recipient, subject |
Enough to send a follow-up into the same conversation |
thread_id |
Returned when the first email is sent; inbound replies carry it too |
references |
The message_id of each email you sent, oldest first, for threading headers |
follow_ups_sent |
Caps the sequence |
status |
waiting, replied, no_reply or undeliverable |
next_check_at |
When the timer should look at this thread again |
Store this in your own database, not in the model's context. The agent can read the record when it needs to, but the scheduler, the webhook handler and the metrics all depend on it being exact.
Setup
The examples share these imports and constants. WAIT and MAX_FOLLOW_UPS are policy choices for your use case, not provider defaults.
import hashlib
import hmac
import json
import os
import re
from datetime import datetime, timedelta, timezone
import requests
API = "https://api.sentfrom.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['SENTFROMAI_API_KEY']}"}
SECRET = os.environ["SENTFROMAI_WEBHOOK_SECRET"].encode()
WAIT = timedelta(days=3)
MAX_FOLLOW_UPS = 2
def now():
return datetime.now(timezone.utc)
Step 1: send the first email and save the thread
POST /messages returns the new message's internal id, its thread_id and a message_id (sending docs). Save the thread ID before the agent does anything else. The client_id makes the send safe to retry: a repeated key returns the original message instead of sending a duplicate. See retry-safe email sending for AI agents for the full pattern.
def send_first_email(store, outreach_id, inbox_id, to, subject, text):
r = requests.post(f"{API}/messages", headers=HEADERS, timeout=30, json={
"inbox_id": inbox_id, "to": [to], "subject": subject, "text": text,
"client_id": f"{outreach_id}-initial",
})
r.raise_for_status()
sent = r.json()
store.save({
"id": outreach_id, "inbox_id": inbox_id, "recipient": to,
"subject": subject, "thread_id": sent["thread_id"],
"references": [sent["message_id"]],
"follow_ups_sent": 0, "status": "waiting",
"next_check_at": now() + WAIT,
})
Step 2: mark replies when they arrive
Register a webhook for message.received, verify the HMAC signature on the raw body, and acknowledge quickly (receiving docs). Then read the message by ID in a worker and look up the outreach by its thread_id.
def handle_webhook(raw_body, signature, queue):
expected = "sha256=" + hmac.new(SECRET, raw_body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature or ""):
return 401
event = json.loads(raw_body)
if event.get("event") == "message.received":
queue.put(event["message"]["id"]) # do the work outside the request
return 200
def mark_replied(store, outreach, message):
outreach.update(status="replied", replied_at=now(), replied_by=message["from_addr"])
store.save(outreach)
def record_inbound(store, message_id):
r = requests.get(f"{API}/messages/{message_id}", headers=HEADERS, timeout=30)
r.raise_for_status()
message = r.json()
outreach = store.find_by_thread(message["thread_id"])
if outreach is None or outreach["status"] != "waiting":
return
if message["direction"] == "inbound" and not is_auto_reply(message):
mark_replied(store, outreach, message)
Three details matter here:
- Read the message, not just the event.
GET /messages/{id}returns the documented message object withthread_id,direction,from_addr,subjectandbody_text, so the worker does not depend on the exact webhook payload shape. - Count any human in the thread. SentFromAI builds threads from the
Message-ID,In-Reply-ToandReferencesheaders (threads docs, RFC 5322). If the recipient forwards your email to a colleague who replies in the same chain, that reply lands in the same thread. Record who answered, but treat it as a reply. - Treat the reply as untrusted input. The worker only changes state. If the agent then reads the reply to decide what to say, apply the controls in prompt injection by email.
Step 3: separate auto-replies from people
An out-of-office message is inbound mail in the right thread, so a naive check counts it as a reply and stops the sequence. RFC 3834 defines the Auto-Submitted header for this, with auto-replied marking automatic responses (RFC 3834). When your provider exposes raw headers, check that header first.
SentFromAI's documented message object includes the subject, body, sender, direction and delivery status, but not raw headers (OpenAPI schema). So this example classifies on content:
AUTO_SUBJECT = re.compile(
r"^\s*(automatic reply|auto[- ]?reply|autoreply|out of (the )?office|ooo\b)", re.I
)
AUTO_BODY = re.compile(
r"\b(i am|i'm) (currently )?(out of (the )?office|away|on (annual )?leave)\b", re.I
)
def is_auto_reply(message):
subject = message.get("subject") or ""
opening = (message.get("body_text") or "")[:400]
return bool(AUTO_SUBJECT.match(subject) or AUTO_BODY.search(opening))
Patterns like these catch common English subjects such as "Automatic reply:" and "Out of office". They will miss some responders and other languages. For borderline cases, a small model call with the subject and the first few lines is a reasonable fallback, as long as the output is a label your code checks and not an action. Keep auto-replies in the thread rather than discarding them; they often state a return date your scheduler can use.
The same RFC also says automatic responders must not reply blindly to every message they receive. That applies to your agent too: an agent that answers auto-replies can end up in a mail loop with another robot.
Step 4: follow up on a timer, and re-read the thread first
Silence produces no event, so follow-ups need a scheduler. Each run picks up records whose next_check_at has passed, reads the whole thread with GET /threads/{id}, and only sends if no person has replied (threads docs).
def follow_up_text(outreach, n):
# Must be deterministic: a retry with the same client_id needs the same body.
return f"Following up on my earlier note about {outreach['subject']}."
def run_due_checks(store):
for outreach in store.due(now()):
r = requests.get(f"{API}/threads/{outreach['thread_id']}", headers=HEADERS, timeout=30)
r.raise_for_status()
replies = [m for m in r.json()["messages"]
if m["direction"] == "inbound" and not is_auto_reply(m)]
if replies:
mark_replied(store, outreach, replies[0])
continue
if outreach["follow_ups_sent"] >= MAX_FOLLOW_UPS:
outreach["status"] = "no_reply"
store.save(outreach)
continue
n = outreach["follow_ups_sent"] + 1
r = requests.post(f"{API}/messages", headers=HEADERS, timeout=30, json={
"inbox_id": outreach["inbox_id"], "to": [outreach["recipient"]],
"subject": f"Re: {outreach['subject']}",
"text": follow_up_text(outreach, n),
"in_reply_to": outreach["references"][-1],
"references": outreach["references"],
"client_id": f"{outreach['id']}-follow-up-{n}",
})
if r.status_code == 422: # suppressed or blocked recipient
outreach["status"] = "undeliverable"
store.save(outreach)
continue
r.raise_for_status()
outreach["references"].append(r.json()["message_id"])
outreach["follow_ups_sent"] = n
outreach["next_check_at"] = now() + WAIT
store.save(outreach)
Why this shape:
- The thread read is your reconciliation. Webhooks retry on errors, but an endpoint can still be down longer than you expect, and the realtime WebSocket is live-only and does not replay missed events (realtime docs). Reading the thread right before sending means a missed event costs you nothing. Compare the options in webhooks vs WebSockets vs polling.
- Follow-ups join the original conversation. SentFromAI's docs say a fresh
POST /messagesjoins an existing thread when you passin_reply_toand, optionally,referencesfrom the message you are answering (threads docs). The example uses themessage_idsaved from each send. Before running a sequence, send one to a mailbox you control and confirm the follow-up appears in the same conversation in the mail client and inGET /threads/{id}. Our email threading guide covers the headers in more depth. - Retries cannot double-send. Each follow-up has a fixed
client_idand a deterministic body. If the process crashes after sending but before saving, the next run repeats the same request and gets the original message back. The API returns409if the same key arrives with a different body. - Undeliverable addresses end the sequence. SentFromAI suppresses addresses that hard-bounce or file a spam complaint, and drops recipients on your outbound block list. If no deliverable recipient remains, the send returns
422(sending docs, allow and block lists). Subscribe tomessage.bouncedandmessage.complainedif you want to close those records sooner; the422is the backstop.
A small race remains: a reply can land between the thread read and the send. Keeping the read immediately before the send makes the window seconds wide, and that is usually acceptable.
Step 5: compute reply rate honestly
def reply_rate(outreaches):
reached = [o for o in outreaches if o["status"] != "undeliverable"]
replied = [o for o in reached if o["status"] == "replied"]
return len(replied) / len(reached) if reached else 0.0
Two rules keep the number meaningful:
- Exclude records you never reached. A bounced or suppressed address was not a chance to reply.
- Measure closed cohorts. Replies arrive over days. Group outreach by the week it started and report a cohort only after its last follow-up window has passed, otherwise recent sends drag the rate down.
If you need rates per campaign or per agent, add those fields to the outreach record at send time. Do not try to recover them later from subjects.
Stop rules worth enforcing in code
A follow-up loop is the part of an email agent most likely to look like spam. Put these limits in the scheduler, not in a prompt:
- Stop all automated follow-ups on the first human reply, and hand the thread to the agent or a person to answer.
- Cap the sequence. The example sends at most two follow-ups.
- When someone asks not to be contacted, add an outbound block rule for their address with
POST /lists. Every later send to them returns422, whatever the agent decides (allow and block lists). - Watch complaints. Gmail asks all senders to keep the spam rate reported in Postmaster Tools below 0.3%, and senders of more than 5,000 messages a day to Gmail accounts must support one-click unsubscribe on marketing and subscribed messages (Google email sender guidelines).
For the sending side of reputation, see what we learned about deliverability after 100,000 emails.
How it fits together
| Situation | What happens | API call |
|---|---|---|
| Agent starts a conversation | Save thread_id and message_id |
POST /messages |
| Person replies | Webhook queues the message; worker marks replied |
message.received, GET /messages/{id} |
| Out-of-office arrives | Classified as automatic; sequence continues | GET /messages/{id} |
| Wait period ends with no reply | Re-read the thread, then send the next follow-up in thread | GET /threads/{id}, POST /messages |
| Webhook was missed | The thread read finds the reply; no follow-up is sent | GET /threads/{id} |
| Address bounced or is blocked | Send returns 422; record is undeliverable |
POST /messages |
Test notes
The code above passed unit tests against mocked API responses covering signature checks, a human reply, an out-of-office, a reply caught only by the thread read, a 422 recipient, the follow-up cap and the reply-rate math. It was not run against a live account. Run it against inboxes you control before pointing it at real contacts.
FAQ
How does an AI agent know someone replied to its email?
Save the thread_id returned when the agent sends. When a message.received event arrives, read the message and check whether its thread_id matches an open outreach and its direction is inbound. Exclude auto-replies, then mark the outreach as replied.
Can I track reply rates with webhooks alone?
You can record replies with webhooks alone, but not the absence of replies. Silence produces no event, so you still need a timer to decide when to follow up and when to close a record as no_reply.
Do out-of-office messages count as replies?
They should not. They prove the address works but carry no answer. Check Auto-Submitted when headers are available, otherwise classify on subject and body, and keep the sequence running.
What happens if someone replies to a follow-up instead of the first email?
As long as each follow-up is sent with in_reply_to and references, the reply lands in the same thread, so the same thread_id lookup finds it.
Should the model decide when to follow up?
Let the model write the follow-up if you like, but keep timing, caps and stop rules in code. Those are the rules that protect recipients and your sending reputation, and they should not depend on a prompt.
Next step
Create an inbox, register a message.received webhook, and run the tracker against a test thread. SentFromAI email covers inboxes, threads and webhooks. The Free plan includes 3 inboxes and 5,000 emails a month with no card, and pricing lists each plan's limits. Start free.
Sources
Checked November 10, 2026.
- SentFromAI OpenAPI schema
- SentFromAI sending email
- SentFromAI receiving email
- SentFromAI threads and messages
- SentFromAI realtime (WebSocket)
- SentFromAI allow and block lists
- SentFromAI pricing
- RFC 3834, Recommendations for automatic responses to electronic mail
- RFC 5322, Internet Message Format, section 3.6.4
- Apple, Use Mail Privacy Protection on iPhone
- Google, Email sender guidelines