npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

agentsmail-sdk

v1.0.1

Published

TypeScript SDK for AgentsMail - Email service for AI agents with secure authentication and per-agent access control

Readme

AgentsMail SDK - Email Service for Autonomous AI Agents

npm version TypeScript License

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/sdk

Quick 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 requests

setToken(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 successfully
  • email.received - New email received
  • email.forwarded - Email was forwarded
  • email.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

  1. Never hardcode secrets

    // ❌ WRONG
    const secret = 'xyz789...';
       
    // ✅ RIGHT
    const secret = process.env.AGENT_SECRET;
  2. Store credentials securely

    • Use environment variables
    • Use a secrets manager (AWS Secrets, HashiCorp Vault)
    • Never commit to git
  3. Use HTTPS only

    • All API calls use HTTPS
    • Ensure webhook URLs are HTTPS
  4. Rotate credentials

    • Regularly update agent secrets
    • Rotate webhook URLs periodically
  5. 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