Healthcare teams manually sort incoming referral emails, risking delayed specialist confirmations and patient care gaps. AgentMail enables AI agents to search, classify, and reply to referral emails via REST API, automating triage workflows. By combining AgentMail's search and draft capabilities, agents encode clinical triage logic and generate HIPAA-safe specialist confirmations without human overhead. Real referral management systems show that centralizing intake and automating triage reduces leakage and ensures every referral is tracked from request to appointment.
What this tutorial covers
- •Outcome: You will build an AI agent that searches incoming referral emails, extracts urgency and specialty, drafts confirmation replies, and routes them for review.
- •Endpoints used: `GET /v0/inboxes/{inbox_id}/messages/search`, `GET /v0/inboxes/{inbox_id}/messages/{message_id}`, `POST /v0/inboxes/{inbox_id}/drafts`, `PATCH /v0/inboxes/{inbox_id}/drafts/{draft_id}`, `POST /v0/inboxes/{inbox_id}/messages/{message_id}/reply`
- •SDK methods: `client.inboxes.messages.search()`, `client.inboxes.messages.get()`, `client.inboxes.drafts.create()`, `client.inboxes.drafts.update()`, `client.inboxes.messages.reply()`
- •Language: typescript
- •Auth: Bearer token (Authorization header)
- •Estimated implementation time: ~18 minutes
Step 1: Search for unprocessed referral emails in AgentMail inbox
Begin by querying AgentMail's inbox for new referral messages. The search endpoint filters by subject keywords and sender domain to isolate incoming specialist requests.
Query referral messages by keyword
Response:
1const res = await fetch("https://api.agentmail.to/v0/inboxes/{inbox_id}/messages/search", {
2 method: "GET",
3 headers: {
4 "Authorization": `${process.env.API_TOKEN}`,
5 "Content-Type": "application/json"
6 }
7});
8const data = await res.json();Step 2: Fetch full message and extract clinical triage signals
Retrieve the complete message body to parse urgency keywords, patient demographics, and clinical reason. AgentMail's get endpoint surfaces headers and full MIME content for entity extraction. Pass extracted signals to your LLM-based triage classifier to assign specialty routing and priority level.
Load and parse referral details
Your agent now holds extracted clinical signals and urgency level, ready to draft an appropriate specialist confirmation response.
Step 3: Draft AI-generated specialist confirmation for review
Use AgentMail's drafts endpoint to compose a HIPAA-safe confirmation response. The draft is stored in the inbox for human review before sending. The agent encodes your clinic's SOP for confirmations: acknowledge receipt, restate patient details, confirm appointment window, and request missing documents.
Create draft confirmation message
Response:
1const res = await fetch("https://api.agentmail.to/v0/inboxes/{inbox_id}/drafts", {
2 method: "POST",
3 headers: {
4 "Authorization": `${process.env.API_TOKEN}`,
5 "Content-Type": "application/json"
6 }
7});
8const draft = await res.json();
9const updatedRes = await fetch("https://api.agentmail.to/v0/inboxes/{inbox_id}/drafts/{draft_id}", {
10 method: "PATCH",
11 headers: {
12 "Authorization": `${process.env.API_TOKEN}`,
13 "Content-Type": "application/json"
14 }
15});
16const confirmation = await updatedRes.json();Step 4: Update draft and finalize specialist reply in AgentMail
If the LLM-generated draft requires adjustments (e.g., missing SOP details or scheduling constraints), use AgentMail's update endpoint to refine the draft before approval. Once the draft is validated by your clinical compliance rules, convert it to a real reply using the reply endpoint to send the confirmation directly.
Refine and send confirmation reply
1// Update draft with refined content before approval
2const updateDraftRes = await fetch(`https://api.agentmail.to/v0/inboxes/{inbox_id}/drafts/{draft_id}`, {
3 method: "PATCH",
4 headers: {
5 "Authorization": `${process.env.API_TOKEN}`,
6 "Content-Type": "application/json"
7 }
8});
9const updatedDraft = await updateDraftRes.json();
10
11// Validate draft against clinical compliance rules
12if (updatedDraft) {
13 // Send reply using the validated draft
14 const replyRes = await fetch(`https://api.agentmail.to/v0/inboxes/{inbox_id}/messages/{message_id}/reply`, {
15 method: "POST",
16 headers: {
17 "Authorization": `${process.env.API_TOKEN}`,
18 "Content-Type": "application/json"
19 }
20 });
21 const reply = await replyRes.json();
22}Response:
1const res = await fetch("https://api.agentmail.to/v0/inboxes/{inbox_id}/drafts/{draft_id}", {
2 method: "PATCH",
3 headers: {
4 "Authorization": `${process.env.API_TOKEN}`,
5 "Content-Type": "application/json"
6 }
7});
8const data = await res.json();Step 5: Audit triage decisions and log referral workflow state
Log each triage decision (specialty, urgency, action) alongside AgentMail message IDs and timestamps to create an audit trail for compliance and referral tracking. This log enables analytics on referral-to-appointment time, specialty distribution, and AI decision accuracy for continuous improvement.
Record triage audit trail
Your referral triage workflow is now fully auditable, with each AI decision tied to AgentMail message records for HIPAA compliance and referral analytics.
Common pitfalls when using AgentMail
- •PHI in draft body not encrypted in transit. AgentMail handles encryption in transit and at rest, but ensure your clinic's BAA covers automated triage agents and that you do not log unencrypted PHI locally. Verify API responses are handled securely in memory.
- •Drafts sent without clinical validation. Always route AI-generated confirmation drafts through human clinical review before sending. Use draft state to hold for review, not as a fire-and-forget confirmation. Misrouted urgency levels or specialty assignments can delay critical care.
- •Missing referral documents or incomplete metadata. AgentMail returns the raw email body and headers; if senders omit required fields (patient age, imaging), your triage classifier will hallucinate. Always fall back to a 'HUMAN_REVIEW' urgency state when extraction confidence is low.
- •No EHR or scheduling system sync. The confirmation reply does not automatically update your EHR or scheduling system. Implement a downstream workflow that calls your scheduling API after the reply is sent to create the actual appointment slot.
Ready to automate your referral intake with AI and AgentMail? Start building a triage agent today and reduce referral leakage across your specialty clinics.
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
Automate candidate screening and interview confirmations with AI agents
Recruiting teams spend hours manually drafting candidate screening emails and scheduling confirmations, slowing hiring timelines and reducing recruiter producti
eesel AI Alternatives That Actually Handle Agentic Workflows
Eesel AI earns its reputation as a sharp enterprise knowledge tool. But when your AI agents need to act — sending emails, triaging inboxes, routing messages acr

