Sales Agent with WebSocket
Overview
Learn how to build a real-time sales agent that processes emails instantly using WebSocket connections. Unlike webhook-based agents that require ngrok and public URLs, this WebSocket approach connects directly to AgentMail for true real-time processing with minimal setup.
This agent demonstrates a practical sales workflow: a manager delegates customer outreach to the agent, which then handles the entire conversation autonomously while keeping the manager informed of key signals.
What You’ll Build
By the end of this guide, you’ll have a working sales agent that:
- Connects via WebSocket for instant, real-time email processing
- Handles manager emails by extracting customer info and sending personalized outreach
- Processes customer replies with AI-powered, context-aware responses
- Notifies the manager when customers show strong buying signals
Here’s the workflow:
WebSocket vs Webhook: Why WebSocket?
For more details, see the WebSocket API Reference and the Python SDK WebSocket documentation.
Prerequisites
Before you begin, make sure you have:
Required:
- Python 3.11 or higher installed
- An AgentMail account and API key
- An OpenAI account and API key
Project Setup
Step 1: Create Project Directory
Create a new directory for your agent:
Step 2: Create the Agent Code
Create a file named main.py and paste the following code:
Click to view full main.py code
Step 3: Create Requirements File
Create a file named requirements.txt:
Step 4: Install Dependencies
Install the required Python packages:
Step 5: Configure Environment Variables
Create a .env file with your credentials:
Note: Unlike webhook-based agents, you don’t need ngrok or a public URL. The WebSocket connection is outbound only, so it works behind firewalls without any port forwarding.
Code Walkthrough
Let’s understand how the agent works by breaking down the key components.
Architecture Overview
1. WebSocket Connection Setup
The core of this agent is the WebSocket connection:
Key points:
AsyncAgentMailis the async version of the clientagentmail.websockets.connect()creates the WebSocket connectionSubscribespecifies which inboxes to monitor
2. Event Handling Loop
The agent uses an async iterator pattern to process events:
Event types:
Subscribed- Confirmation that subscription was successfulMessageReceivedEvent- A new email arrived in the inbox
3. Email Processing Flow
The agent routes emails based on content:
Email extraction helper:
4. Manager Email Handler
When the manager sends an email with customer info:
5. Customer Email Handler with Intent Detection
The agent tracks conversations and detects customer intent:
6. AI Response Generation
The agent uses OpenAI for generating responses:
Key points:
- Includes full conversation history for context
- Graceful error handling with fallback message
Running the Agent
Start the agent:
You should see output like this:
Success! Your agent is now running and listening for emails in real-time.
Leave this terminal window open - closing it will stop the agent.
Testing Your Agent
Let’s verify everything works with some test scenarios.
Test Scenario: Manager Outreach Request
Send this email from your personal email:
Expected console output:
You’ll receive: A confirmation email with the sales pitch that was sent.
It works! The agent processed emails in real-time, generated AI responses, and notified you about the interested customer.
Customization
Modifying Intent Detection
Update the intent_keywords dictionary in handle_customer_email():
Adding More Inbox Subscriptions
Subscribe to multiple inboxes:
Troubleshooting
Common Issues
WebSocket connection refused or timeout
Problem: Cannot connect to AgentMail WebSocket.
Solutions:
- Verify your API key is correct:
- Check your internet connection and firewall settings
- Ensure you’re using
agentmail>=0.0.19which includes WebSocket support:
Emails not being received
Problem: Agent is running but not receiving emails.
Checklist:
- Verify the inbox exists:
- Check subscription confirmation in console output
- Send test email to the correct inbox address
- Verify the email isn’t being filtered as spam
Agent crashes with asyncio errors
Problem: Async-related exceptions.
Solutions:
- Ensure Python 3.11+ is installed:
- Don’t mix sync and async code improperly
- Use
asyncio.run(main())as the entry point
If you build something cool with AgentMail, we’d love to hear about it. Share in our Discord community!
