agentsmail-sdk
v1.0.1
Published
TypeScript SDK for AgentsMail - Email service for AI agents with secure authentication and per-agent access control
Maintainers
Readme
AgentsMail SDK - Email Service for Autonomous AI Agents
AgentsMail SDK is a production-ready TypeScript SDK that enables autonomous AI agents to autonomously manage email accounts, send messages, receive emails, and respond to real-time events through webhooks—all with enterprise-grade security.
Built specifically for AI agents, AgentsMail provides:
- 🤖 Agent Autonomy - Your AI agent can register itself, create email accounts, and manage emails independently
- 🔐 Enterprise Security - JWT authentication, per-agent isolation, rate limiting, and encrypted storage
- 📧 Full Email Lifecycle - Send, receive, forward, search, and manage drafts
- 🪝 Real-Time Webhooks - Get instant notifications for email events
- ⚡ Rate Limiting - Built-in quota management (1 email account per day per agent)
- 📊 Type-Safe - Complete TypeScript type definitions with full IDE support
- 🌐 Multi-Agent - Manage multiple agents with complete isolation
- 💼 Enterprise Ready - Production-grade API with 99.5% SLA
🎯 What is AgentsMail?
AgentsMail is a complete email infrastructure built specifically for autonomous AI agents. Unlike traditional email services designed for humans, AgentsMail is engineered for agents that need to:
- Register themselves without human intervention
- Create email accounts autonomously (with built-in quotas)
- Send messages to humans (alerts, reports, notifications)
- Receive and process emails (instructions, feedback, data)
- Forward important messages to human operators
- Operate independently across multiple domains and use cases
Key Differences from Traditional Email
| Feature | Traditional Email | AgentsMail | |---------|-------------------|------------| | Authentication | Username/password | Agent ID + secret + JWT | | Multi-agent support | Multiple accounts | Built-in agent isolation | | Quotas | Unlimited | 1 account per day per agent | | Webhooks | Not standard | First-class citizen | | Type safety | None | Full TypeScript | | Rate limiting | Per IP | Per agent | | Access control | Shared passwords | Isolated secrets |
✨ Core Features
✅ Autonomous Agent Registration - Agents register themselves without admin approval
✅ Secure Authentication - JWT tokens + agent secrets + bcryptjs hashing
✅ Complete Isolation - Each agent can ONLY access their own emails (database-enforced)
✅ Daily Rate Limits - 1 email account creation per agent per day
✅ Full Email Lifecycle - Send, receive, forward, delete, search, drafts
✅ Real-Time Webhooks - Instant notifications for: sent, received, forwarded, deleted
✅ Type-Safe SDK - 30+ methods with complete TypeScript definitions
✅ Draft Management - Save and organize emails before sending
✅ Search Capabilities - Full-text search by sender, subject, content
✅ Attachment Support - Send and receive files
✅ Multi-Agent Support - Unlimited agents with complete data isolation
✅ Enterprise Ready - Production-grade security, monitoring, backups
Installation
npm install @agentsmail/sdkQuick Start
1. Register Your Agent
import { AgentsMail } from '@agentsmail/sdk';
const mail = new AgentsMail({
apiUrl: 'https://api.agentsmail.online' // Production URL
});
// Register your agent
const registration = await mail.registerAgent('My Trading Bot');
console.log('✅ Registered:', registration.agentId);
console.log('🔐 Secret:', registration.secret); // Save this securely!
console.log('🎫 Token:', registration.token);2. Create Email Accounts
// Create your first email account (1 per day limit)
const emailAccount = await mail.createEmailAccount(
'trading-bot', // username
'SecurePass123!', // password
500 // quota in MB
);
console.log('📧 Email:', emailAccount.email);
// Output: [email protected]3. Send Emails
// Send an email from your account
const result = await mail.sendEmail(emailAccount.id, {
to: '[email protected]',
subject: 'Trading Alert',
body: 'BTC has reached your target price',
html: '<p>BTC has reached your target price</p>'
});
console.log('✅ Sent:', result.messageId);4. Manage Your Emails
// List all email accounts
const accounts = await mail.listEmailAccounts();
console.log('📬 Accounts:', accounts);
// Get messages from an account
const messages = await mail.getMessages(emailAccount.id, {
direction: 'in',
limit: 50,
offset: 0
});
// Search messages
const results = await mail.searchMessages(emailAccount.id, {
q: 'bitcoin',
from: '[email protected]'
});
// Forward an email to your human
await mail.forwardEmail(
emailAccount.id,
messages[0].id,
'[email protected]'
);5. Use Webhooks for Real-Time Events
// Register webhook to receive email events
const webhook = await mail.registerWebhook({
url: 'https://your-domain.com/webhook',
events: ['email.sent', 'email.received', 'email.forwarded']
});
console.log('🔔 Webhook registered:', webhook.id);Complete Agent Workflow Example
import { AgentsMail } from '@agentsmail/sdk';
async function runTradingAgent() {
const mail = new AgentsMail({
apiUrl: 'https://api.agentsmail.online'
});
// Step 1: Register agent
console.log('📝 Registering agent...');
const registration = await mail.registerAgent('Trading Bot v1');
// Save these securely!
const agentId = registration.agentId;
const secret = registration.secret;
console.log(`✅ Agent registered: ${agentId}`);
// Step 2: Create email account (1 per day)
console.log('📧 Creating email account...');
const emailAccount = await mail.createEmailAccount(
'tradingbot',
'SecurePassword123!',
500
);
console.log(`✅ Email created: ${emailAccount.email}`);
// Step 3: Set up webhook for alerts
console.log('🔔 Setting up webhooks...');
await mail.registerWebhook({
url: 'https://your-domain.com/webhooks/email',
events: ['email.received', 'email.sent']
});
console.log('✅ Webhooks registered');
// Step 4: Send alert email
console.log('📤 Sending alert...');
const result = await mail.sendEmail(emailAccount.id, {
to: '[email protected]',
subject: 'ETH Price Alert',
body: 'ETH has crossed $2000. Execute trading plan?',
html: '<strong>ETH has crossed $2000</strong>. Execute trading plan?'
});
console.log(`✅ Alert sent: ${result.messageId}`);
// Step 5: Check incoming messages
console.log('📥 Checking messages...');
const messages = await mail.getMessages(emailAccount.id, {
direction: 'in',
limit: 10
});
console.log(`✅ You have ${messages.length} incoming messages`);
// Step 6: Search for important emails
const importantEmails = await mail.searchMessages(emailAccount.id, {
q: 'urgent'
});
console.log(`⚠️ Found ${importantEmails.length} urgent emails`);
}
// Run the agent
runTradingAgent().catch(console.error);API Reference
Authentication
registerAgent(name: string)
Register a new agent autonomously. Returns agent ID and secret.
const response = await mail.registerAgent('My Bot');
// {
// agentId: 'agent_abc123...',
// secret: 'xyz789...',
// token: 'eyJhbGciOiJIUzI1NiIs...',
// message: 'Agent created successfully...'
// }login(agentId: string, secret: string)
Login with existing credentials.
const response = await mail.login('agent_abc123', 'xyz789');
// Sets token automatically for authenticated requestssetToken(token: string, agentId: string)
Manually set authentication token (useful if you stored it).
mail.setToken(
'eyJhbGciOiJIUzI1NiIs...',
'agent_abc123'
);Email Accounts
createEmailAccount(username: string, password: string, quota?: number)
Create a new email account. Limited to 1 per day per agent.
const account = await mail.createEmailAccount(
'mybot',
'SecurePass123!',
500 // Optional: MB quota (default 500)
);Throws QUOTA_EXCEEDED (429) if 1 account already created today.
listEmailAccounts()
List all email accounts for this agent.
const accounts = await mail.listEmailAccounts();
// [
// { id: 'uuid', email: '[email protected]', created_at: '...' },
// { id: 'uuid', email: '[email protected]', created_at: '...' }
// ]getEmailAccount(accountId: string)
Get details of a specific account.
const account = await mail.getEmailAccount('account-uuid');deleteEmailAccount(accountId: string)
Delete an email account.
await mail.deleteEmailAccount('account-uuid');Email Operations
sendEmail(accountId: string, request: SendEmailRequest)
Send an email from an account.
const result = await mail.sendEmail(accountId, {
to: '[email protected]',
subject: 'Hello',
body: 'Email body',
html: '<p>Email body</p>',
attachments: [
{ filename: 'file.txt', content: 'file contents' }
]
});getMessages(accountId: string, options?)
Get messages from an account.
const messages = await mail.getMessages(accountId, {
direction: 'in', // 'in' or 'out'
limit: 50, // default: 50
offset: 0 // for pagination
});getMessage(accountId: string, messageId: string)
Get a single message.
const message = await mail.getMessage(accountId, messageId);deleteMessage(accountId: string, messageId: string)
Delete a message.
await mail.deleteMessage(accountId, messageId);forwardEmail(accountId: string, messageId: string, to: string)
Forward an email to another address.
await mail.forwardEmail(
accountId,
messageId,
'[email protected]'
);searchMessages(accountId: string, params: SearchMessagesParams)
Search messages by criteria.
const results = await mail.searchMessages(accountId, {
q: 'search term', // Full-text search
from: '[email protected]',
to: '[email protected]',
subject: 'keyword'
});Draft Management
saveDraft(accountId: string, draft: SaveDraftRequest)
Save an email draft.
const draft = await mail.saveDraft(accountId, {
recipient: '[email protected]',
subject: 'Draft subject',
body: 'Draft body',
html: '<p>Draft body</p>'
});getDrafts(accountId: string)
Get all drafts for an account.
const drafts = await mail.getDrafts(accountId);deleteDraft(accountId: string, draftId: string)
Delete a draft.
await mail.deleteDraft(accountId, draftId);Webhooks
registerWebhook(request: RegisterWebhookRequest)
Register a webhook for email events.
const webhook = await mail.registerWebhook({
url: 'https://your-domain.com/webhook',
events: ['email.sent', 'email.received', 'email.forwarded', 'email.deleted']
});listWebhooks()
List all registered webhooks.
const webhooks = await mail.listWebhooks();updateWebhook(webhookId: string, request: UpdateWebhookRequest)
Update a webhook.
await mail.updateWebhook(webhookId, {
url: 'https://new-domain.com/webhook',
events: ['email.sent'],
active: true
});deleteWebhook(webhookId: string)
Delete a webhook.
await mail.deleteWebhook(webhookId);Webhook Payload Format
When a webhook is triggered, you'll receive:
{
"event": "email.sent",
"timestamp": "2026-02-11T16:00:00Z",
"data": {
"messageId": "uuid",
"from": "[email protected]",
"to": "[email protected]",
"subject": "Alert"
}
}Supported Events
email.sent- Email was sent successfullyemail.received- New email receivedemail.forwarded- Email was forwardedemail.deleted- Email was deleted
Rate Limiting
- Email Accounts: 1 per day per agent (429 response)
- API Requests: 100 per 15 minutes per agent
- Webhook Retries: Exponential backoff (up to 5 retries)
Error Handling
try {
const account = await mail.createEmailAccount('bot', 'pass');
} catch (error) {
if (error.message.includes('Quota exceeded')) {
console.log('Already created 1 email today. Try tomorrow.');
} else if (error.message.includes('Email already exists')) {
console.log('This email is taken.');
} else {
console.error('Error:', error.message);
}
}Security Best Practices
Never hardcode secrets
// ❌ WRONG const secret = 'xyz789...'; // ✅ RIGHT const secret = process.env.AGENT_SECRET;Store credentials securely
- Use environment variables
- Use a secrets manager (AWS Secrets, HashiCorp Vault)
- Never commit to git
Use HTTPS only
- All API calls use HTTPS
- Ensure webhook URLs are HTTPS
Rotate credentials
- Regularly update agent secrets
- Rotate webhook URLs periodically
Validate webhook signatures (when receiving webhooks)
// Verify webhook authenticity const isValid = verifyWebhookSignature( req.headers['x-agentsmail-signature'], req.rawBody );
FAQ
Q: How many email accounts can my agent create? A: 1 per day. This rate limit resets daily at midnight UTC.
Q: Can agents access each other's emails? A: No! Each agent can only access their own email accounts and messages. Isolation is enforced at the database and API level.
Q: What happens if I lose my agent secret? A: You'll need to register a new agent. Store your secret securely!
Q: Can I send emails without creating an account? A: No. You must create an email account (with agentsmail.online domain) to send emails.
Q: Are webhooks reliable? A: Webhooks are retried up to 5 times with exponential backoff. For critical operations, always verify message status independently.
Q: Can I use my own email domain? A: Currently, only @agentsmail.online is supported. Custom domains coming soon.
Support
- Documentation: https://docs.agentsmail.online
- GitHub Issues: https://github.com/agentsmail/sdk/issues
- Email: [email protected]
License
MIT
