AgentMail

AgentMail

Monitor invoice replies and auto-draft escalation reminders

Monitor invoice replies and auto-draft escalation reminders

Jun 9, 20264 min readBy AgentMail Examples

Manual review of invoice reply threads delays escalation, and drafting payment reminders requires consistent context and tone. AgentMail provides an Email Inbox API that lets your AI agents search, retrieve, and draft replies within invoice-tracking workflows. Monitor incoming replies to invoice messages, extract payment status context, and auto-draft escalation reminders without manual intervention. Use AgentMail's thread search and draft APIs to build a fully autonomous accounts receivable agent.

What this tutorial covers

  • Outcome: You will build an autonomous agent that monitors invoice reply threads, classifies payment status, and drafts escalation reminders for review.
  • Endpoints used: `GET /v0/inboxes/{inbox_id}/threads/search`, `GET /v0/inboxes/{inbox_id}/threads/{thread_id}`, `POST /v0/inboxes/{inbox_id}/drafts`, `PATCH /v0/inboxes/{inbox_id}/drafts/{draft_id}`, `PATCH /v0/inboxes/{inbox_id}/threads/{thread_id}`
  • SDK methods: `client.inboxes.threads.search()`, `client.inboxes.threads.get()`, `client.inboxes.drafts.create()`, `client.inboxes.drafts.update()`
  • Language: typescript
  • Auth: Bearer token (Authorization header)
  • Estimated implementation time: ~18 minutes

Step 1: Search invoice reply threads with AgentMail

Query your inbox for threads containing invoice-related keywords or sender domains. AgentMail's search endpoint filters by subject, body, and sender to isolate payment-related replies.

Search threads by invoice keyword

typescript
1const inbox_id = "your_inbox_id";
2const search_query = "invoice OR payment OR invoice_reply";
3const res = await fetch(`https://api.agentmail.to/v0/inboxes/${inbox_id}/threads/search?query=${encodeURIComponent(search_query)}`, {
4  method: "GET",
5  headers: {
6    "Authorization": `${process.env.API_TOKEN}`,
7    "Content-Type": "application/json"
8  }
9});
10const data = await res.json();
11console.log(`Found ${data.count} invoice-related threads`);
12for (const thread of data.threads) {
13  console.log(`Thread ${thread.thread_id} received at ${thread.received_timestamp}`);
14}

Response:

json
1{
2  "count": 0,
3  "limit": 0,
4  "next_page_token": "string",
5  "threads": [
6    {
7      "inbox_id": "string",
8      "thread_id": "string",
9      "labels": [],
10      "timestamp": "2026-01-01T00:00:00Z",
11      "received_timestamp": "2026-01-01T00:00:00Z"
12    }
13  ]
14}

Step 2: Fetch full thread context with AgentMail to extract payment details

Retrieve the complete thread conversation, including all replies and sender metadata. AgentMail returns the full message history so your agent can analyze payment status and dispute details before drafting a response.

Retrieve thread by ID

typescript
1// Using inbox_id from section 1, and picking the first thread from search results
2const thread_id = data.threads.length > 0 ? data.threads[0].thread_id : "your_thread_id";
3
4const res = await fetch(`https://api.agentmail.to/v0/inboxes/${inbox_id}/threads/${thread_id}`, {
5  method: "GET",
6  headers: {
7    "Authorization": `${process.env.API_TOKEN}`,
8    "Content-Type": "application/json"
9  }
10});
11const thread_data = await res.json();
12
13console.log("Full thread context retrieved:");
14console.log("Thread ID:", thread_data.thread_id);
15console.log("Labels:", thread_data.labels);
16console.log("Timestamp:", thread_data.timestamp);
17console.log("Message history ready for payment and dispute analysis");

Response:

json
1const res = await fetch("https://api.agentmail.to/v0/inboxes/{inbox_id}/threads/{thread_id}", {
2  method: "GET",
3  headers: {
4    "Authorization": `${process.env.API_TOKEN}`,
5    "Content-Type": "application/json"
6  }
7});
8const thread_data = await res.json();
9const full_thread_context = {
10  inbox_id: thread_data.inbox_id,
11  thread_id: thread_data.thread_id,
12  labels: thread_data.labels,
13  timestamp: thread_data.timestamp,
14  received_timestamp: thread_data.received_timestamp
15};

Step 3: Auto-draft escalation reminders using AgentMail drafts API

Based on thread context and payment status, your agent generates a tailored escalation reminder. AgentMail's drafts API creates the message for human review before sending, following AWS best practices that recommend agents review all AI-generated content.

Create draft escalation reminder

typescript
1// Fetch thread to check context and payment status
2const thread_res = await fetch(`https://api.agentmail.to/v0/inboxes/${inbox_id}/threads/${thread_id}`, {
3  method: "GET",
4  headers: {
5    "Authorization": `${process.env.API_TOKEN}`,
6    "Content-Type": "application/json"
7  }
8});
9const thread_data = await thread_res.json();
10
11// Create escalation reminder draft for human review
12const draft_res = await fetch(`https://api.agentmail.to/v0/inboxes/${inbox_id}/drafts`, {
13  method: "POST",
14  headers: {
15    "Authorization": `${process.env.API_TOKEN}`,
16    "Content-Type": "application/json"
17  },
18  body: JSON.stringify({
19    "reply_to": [thread_data.thread_id],
20    "to": [customer_email],
21    "subject": "Payment Escalation Reminder",
22    "labels": ["escalation", "pending_review"]
23  })
24});
25const draft_data = await draft_res.json();
26console.log(`Draft created for human review: ${draft_data.draft_id}`);
27

Step 4: Update draft with refined language and mark thread as escalated

After human review, your agent refines the draft tone or adds account-specific terms and conditions. AgentMail's update endpoint allows edits before sending. Tag the thread as escalated to prevent duplicate reminders.

Update draft and mark thread

Both the draft message and thread metadata are updated. The thread now has labels and status that prevent the agent from re-escalating the same customer, implementing the feedback-loop discipline that Ramp recommends.

Step 5: Build an autonomous invoice-monitoring loop with AgentMail

Wire the search, fetch, and draft functions into a continuous agent loop. Your agent monitors for new replies, extracts payment context, drafts escalations, and flags exceptions for human review.

Autonomous invoice agent workflow

The agent autonomously monitors invoice threads, identifies pending payments, generates escalation drafts, and marks them for review. This workflow combines search, context retrieval, and draft generation into a continuous feedback loop.

Common pitfalls when using AgentMail

  • Always review AI-generated drafts before sending. Your agent may misclassify payment status or use tone that damages customer relationships. Follow AWS Connect's recommendation to have humans review all AI-generated content, especially for sensitive financial communications.
  • Avoid duplicate escalations with thread labels. Without labeling escalated threads, your agent risks sending multiple reminders to the same customer. Use the thread update endpoint to tag processed threads with labels like 'escalated' to prevent resending.
  • Monitor API usage for cost control. Each search and fetch call consumes quota. Like AWS Connect's recommendation to check contact attributes first, prefilter threads by date or sender before calling search to reduce unnecessary API calls and cost.
  • Improve escalation quality by storing feedback. When humans reject or edit a draft, log that correction. Ramp recommends regularly reviewing flagged invoices and correcting mistakes because each correction trains the system for better future escalations.

Ready to automate your accounts receivable email workflow? Get started with AgentMail and integrate email capabilities into your autonomous agents today.

Documentation references

The code examples in this tutorial are grounded in the following docs pages:

Ready to give your agents real email access?

Join leading developers using AgentMail to enable AI agents to send, receive, and search email natively via API.

Read More Blog Posts

AgentMailAgentMail

Actionable email strategies for agent developers

© 2026 AgentMail, Inc. All rights reserved.