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

supermail

v1.0.5

Published

Unified email interface for Gmail, Microsoft Graph, and IMAP/SMTP

Downloads

6

Readme

SuperMail 📧

A unified, provider-agnostic email library for Node.js that works seamlessly with Gmail and Microsoft Graph APIs.

SuperMail provides a single, consistent interface for email operations across multiple providers. Write your email logic once, and switch providers with just a configuration change.

✨ Features

  • 🔄 Unified Interface - Same API for Gmail and Microsoft Graph
  • 📧 Complete Email Operations - Send, receive, reply, delete, and more
  • 📁 Folder Management - Create, list, and organize folders/mailboxes
  • 🏷️ Label/Category Support - Tag and categorize emails
  • Batch Operations - Efficiently process multiple emails at once
  • 📎 Attachment Support - Send and receive file attachments
  • 🛡️ Error Handling - Normalized error handling across providers
  • 🔐 OAuth2 Ready - Simple token-based authentication
  • 📦 TypeScript First - Full type safety and IntelliSense support

📦 Installation

npm install supermail

🚀 Quick Start

Gmail

import { SuperMail } from 'supermail';

const client = new SuperMail({
  type: 'gmail',
  credentials: {
    client_id: 'your-client-id',
    client_secret: 'your-client-secret',
    redirect_uri: 'your-redirect-uri'
  },
  token: {
    access_token: 'your-access-token',
    refresh_token: 'your-refresh-token'
  }
});

// List emails
const emails = await client.listEmails({ maxResults: 10 });

// Send email
await client.sendEmail({
  subject: 'Hello World',
  to: [{ email: '[email protected]' }],
  body: 'This is a test email'
});

Microsoft Graph

import { SuperMail } from 'supermail';

const client = new SuperMail({
  type: 'microsoft',
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  tenantId: 'your-tenant-id',
  accessToken: 'your-access-token'
});

// Same API as Gmail!
const emails = await client.listEmails({ maxResults: 10 });

📖 API Reference

Email Operations

Send Email

await client.sendEmail({
  subject: 'Project Update',
  to: [
    { email: '[email protected]', name: 'Alice' },
    { email: '[email protected]', name: 'Bob' }
  ],
  cc: [{ email: '[email protected]' }],
  body: 'Plain text body',
  htmlBody: '<h1>HTML body</h1>',
  attachments: [{
    filename: 'report.pdf',
    content: fileBuffer,
    contentType: 'application/pdf'
  }]
});

List Emails

const result = await client.listEmails({
  maxResults: 50,
  unreadOnly: true,
  query: 'subject:important',
  pageToken: 'next-page-token' // for pagination
});

console.log(result.messages);
console.log(result.nextPageToken);
console.log(result.totalCount);

Get Email

const email = await client.getEmail('email-id');

console.log(email.subject);
console.log(email.from);
console.log(email.body);
console.log(email.attachments);

Reply to Email

await client.replyToEmail('email-id', {
  subject: 'Re: Original Subject',
  to: [{ email: '[email protected]' }],
  body: 'Thank you for your email...'
});

Delete Email

await client.deleteEmail('email-id');

Mark as Read/Unread

await client.markAsRead('email-id');
await client.markAsUnread('email-id');

Folder Management

List Folders

const folders = await client.listFolders();

folders.forEach(folder => {
  console.log(folder.name);
  console.log(`Unread: ${folder.unreadCount}`);
  console.log(`Total: ${folder.totalCount}`);
});

Create Folder

const folder = await client.createFolder('Projects');

// Create nested folder
const subFolder = await client.createFolder('2024', folder.id);

Move Email to Folder

await client.moveToFolder({
  emailId: 'email-id',
  folderId: 'folder-id'
});

Get Folder Details

const folder = await client.getFolder('folder-id');
console.log(folder.name, folder.unreadCount);

Label/Category Management

List Labels

const labels = await client.listLabels();

labels.forEach(label => {
  console.log(label.name);
  console.log(label.type); // 'system' or 'user'
  console.log(label.color);
});

Create Label

const label = await client.createLabel('Important', '#ff0000');

Add Labels to Email

await client.addLabels({
  emailId: 'email-id',
  labelIds: ['label-1', 'label-2']
});

Remove Labels from Email

await client.removeLabels({
  emailId: 'email-id',
  labelIds: ['label-1']
});

Batch Operations

Batch Process Emails

await client.batchOperation({
  emailIds: ['id-1', 'id-2', 'id-3'],
  operation: 'markRead' // 'delete', 'markRead', 'markUnread', 'archive'
});

Advanced Operations

Archive Email

await client.archiveEmail('email-id');

Move to Trash

await client.trashEmail('email-id');

🛡️ Error Handling

SuperMail provides normalized error handling across all providers:

import {
  SuperMail,
  AuthenticationError,
  RateLimitError,
  NotFoundError
} from 'supermail';

try {
  await client.sendEmail(options);
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Token expired or invalid');
    // Refresh token
  } else if (error instanceof RateLimitError) {
    console.error('Rate limit exceeded');
    console.log(`Retry after: ${error.retryAfter} seconds`);
  } else if (error instanceof NotFoundError) {
    console.error('Email not found');
  }
}

Available Error Classes

  • SuperMailError - Base error class
  • AuthenticationError - Authentication failures
  • RateLimitError - Rate limit exceeded
  • NotFoundError - Resource not found
  • ValidationError - Invalid input

🔐 Authentication

Gmail OAuth2

  1. Create credentials in Google Cloud Console
  2. Enable Gmail API
  3. Get OAuth2 credentials
  4. Implement OAuth flow to get access/refresh tokens
  5. Pass tokens to SuperMail
const client = new SuperMail({
  type: 'gmail',
  credentials: {
    client_id: process.env.GMAIL_CLIENT_ID,
    client_secret: process.env.GMAIL_CLIENT_SECRET,
    redirect_uri: process.env.GMAIL_REDIRECT_URI
  },
  token: {
    access_token: process.env.GMAIL_ACCESS_TOKEN,
    refresh_token: process.env.GMAIL_REFRESH_TOKEN
  }
});

Microsoft Graph OAuth2

  1. Register app in Azure Portal
  2. Add Mail.ReadWrite and Mail.Send permissions
  3. Get client credentials
  4. Implement OAuth flow to get access token
  5. Pass token to SuperMail
const client = new SuperMail({
  type: 'microsoft',
  clientId: process.env.MICROSOFT_CLIENT_ID,
  clientSecret: process.env.MICROSOFT_CLIENT_SECRET,
  tenantId: process.env.MICROSOFT_TENANT_ID,
  accessToken: process.env.MICROSOFT_ACCESS_TOKEN
});

📊 TypeScript Support

SuperMail is written in TypeScript and provides full type definitions:

import {
  SuperMail,
  EmailMessage,
  SendEmailOptions,
  EmailFolder,
  EmailLabel
} from 'supermail';

const options: SendEmailOptions = {
  subject: 'Typed Email',
  to: [{ email: '[email protected]' }],
  body: 'Fully typed!'
};

const message: EmailMessage = await client.sendEmail(options);

🎯 Use Cases

Multi-Tenant Email Platform

function getEmailClient(tenant: Tenant) {
  if (tenant.provider === 'gmail') {
    return new SuperMail({
      type: 'gmail',
      credentials: tenant.gmailCredentials,
      token: tenant.gmailToken
    });
  } else {
    return new SuperMail({
      type: 'microsoft',
      clientId: tenant.microsoftClientId,
      clientSecret: tenant.microsoftClientSecret,
      tenantId: tenant.microsoftTenantId,
      accessToken: tenant.microsoftToken
    });
  }
}

// Same code works for all tenants
const client = getEmailClient(tenant);
await client.sendEmail(emailOptions);

Email Automation

// Archive old emails
const emails = await client.listEmails({ maxResults: 100 });
const oldEmails = emails.messages
  .filter(e => isOlderThanDays(e.date, 30))
  .map(e => e.id!);

await client.batchOperation({
  emailIds: oldEmails,
  operation: 'archive'
});

Email Organization

// Auto-label emails from specific sender
const emails = await client.listEmails({
  query: 'from:[email protected]'
});

const importantLabel = await client.createLabel('From Boss', '#ff0000');

for (const email of emails.messages) {
  await client.addLabels({
    emailId: email.id!,
    labelIds: [importantLabel.id]
  });
}

🧪 Examples

Check out the examples directory for complete working examples:

  • Basic Examples

    • gmail-example.ts - Gmail-specific example
    • microsoft-example.ts - Microsoft-specific example
  • Complete Example

    • complete-example.ts - Demonstrates ALL features

Run examples:

cd examples
npm install
cp .env.example .env
# Add your credentials to .env

npm run gmail              # Run Gmail example
npm run microsoft          # Run Microsoft example
npm run complete:gmail     # Run complete example with Gmail
npm run complete:microsoft # Run complete example with Microsoft

📝 Provider Differences

SuperMail abstracts provider differences, but it's helpful to understand how features map:

| Feature | Gmail | Microsoft Graph | |---------|-------|-----------------| | Folders | Labels (system) | Native folders | | Labels/Tags | Labels (user) | Categories | | Archive | Remove INBOX label | Move to Archive folder | | Trash | Move to TRASH | Move to Deleted Items |

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

MIT

🔗 Links

🙏 Acknowledgments

Built with:


Made with ❤️ for developers who want to build email applications without vendor lock-in.