Learn how to build an intelligent email classification agent that uses AI to automatically analyze and label incoming emails. This intermediate example showcases AgentMail’s powerful labeling feature combined with OpenAI’s GPT-4o-mini to create a sophisticated inbox automation system.
By the end of this guide, you’ll have a working smart labeling agent that:
Here’s what happens when an email arrives:
Before you begin, make sure you have:
Required:
Create a new directory for your agent:
Create a file named agent.py and paste the following code:
Create a file named requirements.txt:
Install the required Python packages:
Create a .env file with your credentials:
Let’s understand how the agent works by breaking down the key components.
The setup_agentmail() function creates your inbox and webhook:
Idempotency with client_id:
Using client_id ensures you can safely restart the agent without creating duplicate inboxes or webhooks. If a resource already exists, AgentMail returns the existing one.
The analyze_email() function is the core of the agent:
Key features:
Example OpenAI prompt:
AI Response:
The apply_labels() function applies labels with a two-tier strategy:
Why two tiers?
The receive_webhook() function orchestrates everything:
Why always return 200?
Even if classification or labeling fails, we return 200 to tell AgentMail: “I received this webhook.” If we returned an error (400/500), AgentMail would retry sending the webhook, which doesn’t help with application errors.
Start the agent:
You should see output like this:
Success! Your agent is now running and ready to classify emails.
Leave this terminal window open - closing it will stop the agent.
Let’s test the agent with different types of emails to see how it classifies them.
Send this email:
Console Output:
Why this classification?
Send this email:
Console Output:
Why this classification?
Go to your AgentMail inbox and filter by labels to organize your emails:
Filter by sentiment:
negative to see all unhappy customerspositive to find praise and testimonialsneutral to review informational emailsFilter by priority, by department…
Combine filters for powerful queries:
urgent + negative → Critical customer issuessales + high → Hot leads requiring fast responsetechnical + bug-report → Engineering backlogPro tip: You can use AgentMail’s API to programmatically fetch emails by labels and build custom workflows, dashboards, and analytics.
Once your emails are automatically labeled, you can build powerful automation on top:
Scenario: Alert your team instantly when urgent issues arrive.
When an email is labeled urgent + negative, automatically send a Slack notification to your support channel. Include the sender’s email and subject line so your team can respond immediately. This ensures critical customer issues never slip through the cracks.
Scenario: Escalate negative sentiment to management.
Track all emails labeled negative and automatically notify customer success managers when sentiment trends downward. If a single customer sends 3+ negative emails in a week, trigger a personal outreach from leadership to address their concerns proactively.
Scenario: Auto-forward emails to the right team.
Create rules that automatically forward emails based on department labels:
sales → Forward to sales@yourcompany.combilling → Create a ticket in your billing systemtechnical → Post to #engineering Slack channelsupport → Add to support queue with appropriate SLAScenario: Send contextual automated responses.
Instead of generic auto-replies, craft responses based on classification:
question → “Thanks for your question! We’ll respond within 24 hours.”bug-report → “Thanks for reporting this. Our engineering team has been notified.”complaint → “We’re sorry to hear that. A senior support agent will contact you within 4 hours.”feature-request → “Great idea! We’ve added this to our product roadmap.”Scenario: Track email metrics and trends.
Build a dashboard that queries emails by labels to analyze:
Use this data to identify bottlenecks, improve processes, and make data-driven decisions about staffing and product priorities.
Congratulations! You’ve built an AI-powered email classification system. This agent showcases how AgentMail’s labeling feature can power sophisticated inbox automation and analytics.