Google ADK Email: Send, Receive and Thread Replies
Give a Google ADK agent its own inbox: Python send and reply tools, inbound webhooks that resume the right session, and replies that stay threaded.
John Joubert
Founder, Robotomail

Table of contents
To add Google ADK email to an agent, give it two Python function tools (one to send, one to reply) that call an email API, then route inbound mail from a webhook into an ADK Runner so each email thread resumes its own session. Store the inbound message ID in session state so the reply tool can thread correctly without asking the model to copy IDs. This guide builds that setup in Python, with unit tests for the tools.
Agent-owned address vs acting on a user's Gmail
Decide this first, because it changes the whole design.
Many Google ADK email examples connect to the Gmail API. That gives the agent delegated access to a person's mailbox. The person signs in with OAuth, grants scopes, and the agent reads and sends as them. Google classifies most Gmail scopes as sensitive or restricted, so a public app also has to pass Google's verification.
An agent-owned address is different. The agent has its own inbox, such as shopping-agent@robotomail.co or an address on your domain. It doesn't need a human's OAuth token or touch anyone's personal mail. Inbound messages arrive by webhook instead of through polling.
| User's Gmail via Gmail API | Agent-owned mailbox | |
|---|---|---|
| Identity | Acts as a human | Its own address |
| Auth | Per-user OAuth, scope review | API key |
| Inbound | Poll or set up Pub/Sub watch | Webhook per message |
| Blast radius | The person's whole mailbox | One mailbox |
| Good for | Assistants working inside a user's inbox | Agents that email vendors, customers, other systems |
If your agent needs to triage a user's existing inbox, use Gmail. If the agent is a participant in conversations, give it its own address. Our Gmail API comparison covers the tradeoffs in more depth. The rest of this post builds the agent-owned version.
Provision a mailbox
Create a mailbox with the CLI:
npx @robotomail/cli mailbox create shopping-agent
You can also create it with the API:
curl -X POST https://api.robotomail.com/v1/mailboxes \
-H "Authorization: Bearer rm_your_api_key" \
-H "Content-Type: application/json" \
-d '{"address": "shopping-agent"}'
Put the mailbox ID and API key in ROBOTOMAIL_MAILBOX_ID and ROBOTOMAIL_API_KEY. For background on why agents need a dedicated inbox at all, see how to give your AI agent an email address.
Define the Google ADK email tools
ADK turns plain Python functions into tools. The model reads the docstring and type hints. If a parameter is named tool_context, ADK injects it and leaves it out of the schema the model sees. That gives the tool read and write access to session state.
# tools.py
import os
import httpx
from google.adk.tools import ToolContext
API_KEY = os.environ["ROBOTOMAIL_API_KEY"]
MAILBOX_ID = os.environ["ROBOTOMAIL_MAILBOX_ID"]
HEADERS = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
def _send(payload: dict) -> dict:
resp = httpx.post(f"https://api.robotomail.com/v1/mailboxes/{MAILBOX_ID}/messages", headers=HEADERS, json=payload, timeout=15)
if resp.status_code >= 400:
return {"status": "error", "detail": resp.text[:300]}
return {"status": "sent"}
def send_email(to: str, subject: str, body: str, tool_context: ToolContext) -> dict:
"""Start a NEW email conversation. Do not use this to answer an inbound email.
Args:
to: Recipient email address.
subject: Subject line.
body: Plain-text body.
"""
return _send({"to": [to], "subject": subject, "bodyText": body})
def reply_to_current_email(body: str, tool_context: ToolContext) -> dict:
"""Reply to the inbound email currently being handled, in the same thread.
Args:
body: Plain-text reply body.
"""
state = tool_context.state
msg_id = state.get("inbound_message_id")
if not msg_id:
return {"status": "error", "detail": "No inbound email in this session."}
if state.get("replied_to") == msg_id:
return {"status": "skipped", "detail": "Already replied to this message."}
subject = state.get("inbound_subject", "")
if not subject.lower().startswith("re:"):
subject = f"Re: {subject}"
result = _send({
"to": [state["inbound_from"]],
"subject": subject,
"bodyText": body,
"inReplyTo": msg_id,
})
if result["status"] == "sent":
state["replied_to"] = msg_id
return result
Two design choices matter here:
- The model never handles message IDs. The reply tool reads
inbound_message_idfrom state, so a hallucinated or truncated ID can't break threading. - Replies are idempotent per message. If the model calls the reply tool twice, or a webhook retry reruns the agent, the
replied_toguard stops a duplicate email.
Errors come back as data, not exceptions, so the model can see what failed and decide what to do.
Test the tools without an LLM
The tools only touch tool_context.state, so a plain namespace object can stand in for the context. Patch httpx.post and assert on the payload:
# test_tools.py
import os
os.environ.setdefault("ROBOTOMAIL_API_KEY", "rm_test")
os.environ.setdefault("ROBOTOMAIL_MAILBOX_ID", "mbx_shopping")
from types import SimpleNamespace
import tools
class FakeResp:
status_code = 200
text = "{}"
def test_reply_threads_and_dedupes(monkeypatch):
calls = []
monkeypatch.setattr(tools.httpx, "post", lambda url, **kw: calls.append(kw["json"]) or FakeResp())
ctx = SimpleNamespace(state={
"inbound_message_id": "msg_123",
"inbound_from": "vendor@example.com",
"inbound_subject": "Order A-4521",
})
assert tools.reply_to_current_email("Shipped today?", ctx)["status"] == "sent"
assert calls[0]["inReplyTo"] == "msg_123"
assert calls[0]["subject"] == "Re: Order A-4521"
assert calls[0]["to"] == ["vendor@example.com"]
assert tools.reply_to_current_email("Again", ctx)["status"] == "skipped"
assert len(calls) == 1
def test_reply_without_inbound_errors(monkeypatch):
monkeypatch.setattr(tools.httpx, "post", lambda url, **kw: FakeResp())
ctx = SimpleNamespace(state={})
assert tools.reply_to_current_email("hi", ctx)["status"] == "error"
These tests cover the logic that actually breaks in production: subject prefixes, thread headers, and duplicate sends. Run them with pytest.
Define the agent
# agent.py
from google.adk.agents import Agent
from tools import send_email, reply_to_current_email
root_agent = Agent(
name="shopping_agent",
model="gemini-2.5-flash",
instruction=(
"You handle email for a purchasing agent. When given an inbound email, "
"decide whether it needs a response. If it does, answer with "
"reply_to_current_email. Use send_email only to start a new conversation. "
"Never reply twice to the same message."
),
tools=[send_email, reply_to_current_email],
)
Resume the right session on inbound mail
Inbound mail arrives at your registered webhook as a message.received event. The payload includes a thread_id, which works as a session key: every message in a conversation lands in the same ADK session, so the agent sees its earlier turns.
Webhooks are registered as their own resource. Before you trust a payload, verify its signature as described in the webhooks concept docs.
# server.py
import time
import uuid
from fastapi import FastAPI, Request, BackgroundTasks
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.events import Event, EventActions
from google.genai import types
from agent import root_agent
APP_NAME = "shopping_agent"
session_service = InMemorySessionService()
runner = Runner(agent=root_agent, app_name=APP_NAME, session_service=session_service)
app = FastAPI()
seen_messages: set[str] = set() # use a durable store in production
async def handle_inbound(data: dict) -> None:
if data["message_id"] in seen_messages:
return
seen_messages.add(data["message_id"])
user_id = data["mailbox_id"]
session_id = data["thread_id"]
inbound = {
"inbound_message_id": data["message_id"],
"inbound_from": data["from"],
"inbound_subject": data["subject"],
}
session = await session_service.get_session(
app_name=APP_NAME, user_id=user_id, session_id=session_id
)
if session is None:
await session_service.create_session(
app_name=APP_NAME, user_id=user_id, session_id=session_id, state=inbound
)
else:
await session_service.append_event(session, Event(
invocation_id=f"inbound-{uuid.uuid4()}",
author="system",
actions=EventActions(state_delta=inbound),
timestamp=time.time(),
))
prompt = f"New email from {data['from']}\nSubject: {data['subject']}\n\n{data['body_text']}"
message = types.Content(role="user", parts=[types.Part(text=prompt)])
async for event in runner.run_async(
user_id=user_id, session_id=session_id, new_message=message
):
if event.is_final_response() and event.content and event.content.parts:
print(f"[{session_id}] {event.content.parts[0].text}")
@app.post("/webhooks/robotomail")
async def robotomail_webhook(request: Request, background: BackgroundTasks):
payload = await request.json()
if payload.get("event") == "message.received":
background.add_task(handle_inbound, payload["data"])
return {"ok": True}
A few operational notes:
- Acknowledge fast, process in the background. LLM calls can take seconds. Return 200 right away so the webhook isn't retried while the agent is still thinking.
- Update state through events. For an existing session,
append_eventwith astate_deltais the supported way to change state from outside a tool. If you mutate the session object directly, the change won't persist. - Use a persistent session service.
InMemorySessionServiceloses every conversation on restart. Switch toDatabaseSessionServiceso a vendor reply three days later still resumes with full context. - Deduplicate on
message_id. Webhook delivery is at-least-once. The in-memory set here is a placeholder. Use Redis or a database table.
If the agent sends the first email of a conversation, the vendor's reply arrives with a thread ID too, and from that point it follows the same path. The threading concept docs explain how replies get grouped.
For the full set of endpoints behind these tools, see the email API for AI agents overview.
FAQ
Can ADK agents use Gmail instead?
Yes, through the Gmail API with OAuth. That fits when the agent works inside a specific person's inbox. If the agent needs its own identity, an agent-owned mailbox avoids per-user consent flows and scope verification.
Why use thread_id as the ADK session ID?
It maps one email conversation to one agent memory. Every reply in the thread resumes the same session, so the agent sees what it already said and what it promised.
How do I stop the agent from replying twice?
You need two guards. Deduplicate webhook deliveries on message_id, and keep a replied_to marker in session state that the reply tool checks before sending.
Does this work with multi-agent ADK setups?
Yes. Attach the email tools to whichever sub-agent owns external communication. Sub-agents in the same session share state, so any of them can read the inbound context.
Give your ADK agent a real inbox with send, receive, and threading built in. Start with Robotomail.
Give your AI agent a real email address
Create a mailbox, connect your agent and test a conversation. Send, receive and retrieve the thread through one API.
Related posts

Webhook to Send Email: Trigger Outbound Mail in One Call
Turn any webhook (Stripe, GitHub, forms) into an outbound email: verify the signature, dedupe retries, and send with one API call in Node or Python.
Read post
Lead Qualification with the Python SDK for SaaS Teams
Build multi-customer lead qualification with the Python SDK: per-customer mailboxes, verified webhooks, threaded follow-ups and clean human handoff.
Read post
Migrate from AgentMail to Robotomail: Worked Example
Move one agent inbox workflow from AgentMail to Robotomail: map operations, port an adapter, test replies and webhooks, then stage rollout and rollback.
Read post