Guide: Sending & Receiving Email
This guide walks you through the complete, practical workflow of an agent having a conversation. While the Core Concepts
pages detail the individual API calls, this guide shows you how to stitch them together to create a functional conversational loop.
The Foundation: Sending HTML & Text
As a quick reminder from our Messages
documentation, it’s a critical best practice to always provide both an html
and a text
version of your email. This ensures readability on all email clients and significantly improves deliverability.
The Conversational Loop
A common task for an agent is to check for replies in an Inbox
and then respond to them. While using Webhooks
is the most efficient method for this, you can also build a simple polling mechanism.
Here’s the step-by-step logic for a polling-based conversational agent.
1. Find a Thread that Needs a Reply
First, you need to identify which conversations have new messages that your agent hasn’t responded to. A great way to manage this is with Labels
. You can list Threads
in a specific Inbox
that have an unreplied
Label
.
2. Get the Last Message ID from the Thread
To reply to a conversation, you need to reply to the most recent message in the Thread
. You can get a specific Thread
by its ID, which will contain a list of all its Messages
. You’ll then grab the ID of the last Message
in that list.
3. Send the Reply and Update Labels
Now that you have the message_id
to reply to, you can send your agent’s response. It’s also a best practice to update the Labels
on the original Message
at the same time, removing the unreplied
Label
and adding a replied
Label
to prevent the agent from replying to the same message twice.
Real-Time Processing with Webhooks
For production applications, polling is inefficient. The best way to handle incoming replies is to use Webhooks
. This allows AgentMail to notify your agent instantly when a new Message
arrives, so you can reply in real-time.