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

@gera2ld/imap

v0.0.1

Published

A lightweight IMAP client for Node.js that supports real-time email monitoring using IDLE mode.

Downloads

58

Readme

IMAP Client

A lightweight IMAP client for Node.js that supports real-time email monitoring using IDLE mode.

Usage

Basic Example

import { ImapClient } from '@gera2ld/imap';

const client = new ImapClient({
  host: 'imap.example.com',
  port: 993,
  secure: true,
  user: '[email protected]',
  password: 'your-password',
});

// Connect and authenticate
await client.connect();

// Select a mailbox
await client.selectMailbox('INBOX');

// Perform operations like fetching messages
const messages = await client.fetchMessages('1:*', ['UID', 'ENVELOPE']);
console.log(messages);

// Disconnect
await client.disconnect();

Watching for New Mails and Deletions Using IDLE Mode

import { ImapClient } from '@gera2ld/imap';

async function watchEmails() {
  const client = new ImapClient({
    host: 'imap.example.com',
    port: 993,
    secure: true,
    user: '[email protected]',
    password: 'your-password',
  });

  try {
    // Connect and authenticate
    await client.connect();
    
    // Select the mailbox to watch (e.g., INBOX)
    await client.selectMailbox('INBOX');
    
    // Listen for new emails
    client.on('newmail', (info) => {
      console.log(`New mail received! Total messages in mailbox: ${info.count}`);
      // Handle new email notification
    });
    
    // Listen for message deletions
    client.on('expunge', (info) => {
      console.log(`Message deleted! Sequence number: ${info.seq}`);
      // Handle message deletion
    });
    
    // Listen for other changes
    client.on('fetch', (message) => {
      console.log(`Message ${message.seq} updated with attributes:`, message.attributes);
    });
    
    // Start listening for real-time updates using IDLE mode
    await client.startIdle();
    console.log('Now listening for new emails and deletions...');
    
    // Keep the program running to continue listening
    // Set up graceful shutdown
    const handleShutdown = async () => {
      console.log('Shutting down gracefully...');
      try {
        // Stop listening for updates
        await client.stopIdle();
        // Disconnect from the server
        await client.disconnect();
        console.log('Disconnected from IMAP server');
        process.exit(0);
      } catch (err) {
        console.error('Error during shutdown:', err);
        process.exit(1);
      }
    };

    // Listen for termination signals
    process.on('SIGINT', handleShutdown);
    process.on('SIGTERM', handleShutdown);

  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the example
watchEmails();

Authentication

The client supports multiple authentication methods:

Password Authentication

const client = new ImapClient({
  host: 'imap.example.com',
  port: 993,
  secure: true,
  user: '[email protected]',
  password: 'your-password',
});

XOAUTH2 Authentication

const client = new ImapClient({
  host: 'imap.example.com',
  port: 993,
  secure: true,
  user: '[email protected]',
  accessToken: 'your-oauth-token',
});

// Or with a function that returns a token
const client = new ImapClient({
  host: 'imap.example.com',
  port: 993,
  secure: true,
  user: '[email protected]',
  accessToken: async () => {
    // Return a fresh access token
    return await getFreshAccessToken();
  },
});

Available Events

  • newmail: Emitted when new messages arrive in the mailbox
  • expunge: Emitted when messages are deleted from the mailbox
  • fetch: Emitted when message attributes are updated
  • recent: Emitted when the number of recent messages changes
  • flags: Emitted when message flags change
  • list: Emitted when mailbox list information is received
  • response: Emitted for raw IMAP responses
  • error: Emitted when an error occurs
  • close: Emitted when the connection is closed

API

ImapClient(options)

Creates a new IMAP client instance.

Options

  • host (string): The IMAP server hostname
  • port (number): The IMAP server port (typically 143 for non-secure, 993 for secure)
  • secure (boolean): Whether to use TLS/SSL connection
  • user (string): The username/email address
  • password (string, optional): The password for authentication
  • accessToken (string | function, optional): Access token for XOAUTH2 authentication

connect()

Connects to the IMAP server and performs authentication.

disconnect()

Disconnects from the IMAP server and cleans up resources.

selectMailbox(mailbox)

Selects a mailbox for subsequent operations.

listMailboxes()

Lists all mailboxes on the server.

fetchMessages(sequence, [items], [options])

Fetches messages from the currently selected mailbox.

  • items (optional): The message data items to fetch (e.g., ['UID', 'ENVELOPE', 'BODY.PEEK[]']). Defaults to ['UID', 'ENVELOPE', 'FLAGS']
  • options (optional): Additional options for the fetch operation
    • uid (boolean, default: true): Whether to use UID-based fetch

searchMessages(criteria, [options])

Searches messages in the currently selected mailbox based on the given criteria.

  • options (optional): Additional options for the search operation
    • uid (boolean, default: true): Whether to use UID-based search

setFlags(sequence, operation, flags, [options])

Sets flags on messages in the currently selected mailbox.

  • operation: The flag operation ('+' to add flags, '-' to remove flags, '=' to replace all flags)
  • flags: Array of flags to operate on (e.g., ['\Seen', '\Flagged'])
  • options (optional): Additional options for the operation
    • uid (boolean, default: true): Whether to use UID-based operation

markAsSeen(sequence, [options])

Marks messages as seen in the currently selected mailbox.

  • options (optional): Additional options for the operation
    • uid (boolean, default: true): Whether to use UID-based operation

markAsUnseen(sequence, [options])

Marks messages as unseen in the currently selected mailbox.

  • options (optional): Additional options for the operation
    • uid (boolean, default: true): Whether to use UID-based operation

deleteMessages(sequence, [options])

Deletes messages in the currently selected mailbox.

  • options (optional): Additional options for the operation
    • uid (boolean, default: true): Whether to use UID-based operation

moveMessages(sequence, destinationMailbox, [options])

Moves messages to a different mailbox.

  • options (optional): Additional options for the operation
    • uid (boolean, default: true): Whether to use UID-based operation

startIdle()

Manually starts IDLE mode for real-time updates.

stopIdle()

Manually stops IDLE mode.

Utilities

The package also exports utility functions for working with IMAP:

formatDateForImap(date)

Formats a Date object to the IMAP date format used in SEARCH commands (e.g., SINCE, ON). The format is "DD-MMM-YYYY" (e.g., "01-Jan-2023").

import { formatDateForImap } from '@gera2ld/imap';

const date = new Date('2023-01-15');
const imapDate = formatDateForImap(date); // "15-Jan-2023"

// Use in search commands
await client.searchMessages(`SINCE ${imapDate}`);

formatDateTimeForImap(date)

Formats a Date object to the IMAP datetime format used in SEARCH commands. The format is "DD-MMM-YYYY HH:MM:SS +ZZZZ" (e.g., "01-Jan-2023 12:00:00 +0000").

import { formatDateTimeForImap } from '@gera2ld/imap';

const date = new Date('2023-01-15T14:30:00Z');
const imapDateTime = formatDateTimeForImap(date); // "15-Jan-2023 14:30:00 +0000"

License

MIT