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 🙏

© 2025 – Pkg Stats / Ryan Hefner

mail-listener-flow

v1.0.12

Published

IMAP listener for Node.js using imapflow

Downloads

238

Readme

📖 Overview

mail-listener-flow is a library for Node.js, designed for monitoring IMAP servers and processing emails in real time. It uses modern libraries (imapflow and mailparser) to ensure stable connections, attachment support, and convenient email parsing.

Key Features

  • IMAP support via imapflow (a reliable implementation of the IMAP client).
  • Automatic email parsing using mail parser.
  • Attachment processing (saving to a file system or streaming).
  • Event-oriented architecture.
  • Automatic reconnection when the connection is disconnected.
  • TypeScript support.

📦 Core Dependencies

  • imapflow - Modern IMAP client
  • mailparser - Email parser
  • TypeScript - Static typing

🚀 Installation

npm install mail-listener-flow

🛠 Quick Start

Basic Usage

import { MailListener } from 'mail-listener-flow';
import path from 'path';

const listener = new MailListener({
  host: 'imap.gmail.com',
  port: 993,
  secure: true,
  username: '[email protected]',
  password: 'your-password', // or accessToken
  mailbox: 'INBOX',
  markSeen: true,
  attachments: true,
  attachmentOptions: {
    directory: path.join(__dirname, 'attachments')
  }
});

// Email events
listener.on('mail', (parsedMail, uid) => {
  console.log('New email:');
  console.log('Subject:', parsedMail.subject);
  console.log('Text snippet:', parsedMail.text?.substring(0, 100));
});

// Attachment handling
listener.on('attachment', (attachment, filePath) => {
  console.log(`Saved attachment to: ${filePath}`);
});

// Error handling
listener.on('error', (err) => {
  console.error('Error:', err.message);
});

// Start listening
listener.start().then(() => {
  console.log('Listener started');
});

📚 API Reference

MailListener Class

Constructor

new MailListener(options: MailListenerOptions)

Configuration Options (MailListenerOptions)

| Option | Type | Default | Description | |----------------------|----------------------------------------|---------------------|------------------------------------------------| | host | string | Required | IMAP server host (e.g., imap.gmail.com) | | port | number | 993 | IMAP port number | | secure | boolean | true | Use TLS/SSL connection | | username | string | Required | Account username/email | | password | string | - | Account password (omit if using accessToken) | | accessToken | string | - | OAuth2 access token | | mailbox | string | "INBOX" | Mailbox to monitor | | searchFilter | string \| string[] \| SearchCriteria | { seen: false } | Email search criteria | | fetchUnreadOnStart | boolean | true | Fetch unread emails on initialization | | mailParserOptions | ExtendedMailParserOptions | {} | Mailparser configuration options | | attachments | boolean | false | Enable attachment processing | | attachmentOptions | AttachmentOptions | { directory: "" } | Attachment handling configuration | | reconnectRetries | number | 3 | Max reconnection attempts | | reconnectTimeout | number | 30000 | Reconnection delay in milliseconds | | tls | object | {} | Custom TLS/SSL options | | logger | any | - | Custom logger implementation | | connectionTimeout | number | - | Connection timeout in ms | | socketTimeout | number | - | Socket timeout in ms | | markSeen | boolean | false | Mark emails as read when fetched |

Methods

  • start(): Promise<void> - Starts the listener
  • stop(): Promise<void> - Stops the connection

🧩 Usage Examples

1. Custom Search Filter

const listener = new MailListener({
  searchFilter: { 
    seen: false,
    subject: 'URGENT',
    since: new Date(2023, 0, 1) // Since Jan 1 2023
  }
});

2. OAuth2 Authentication

const listener = new MailListener({
  host: 'outlook.office365.com',
  username: '[email protected]',
  accessToken: 'oauth2-token-here'
});

3. Advanced Attachment Handling

const listener = new MailListener({
  attachments: true,
  attachmentOptions: {
    directory: './downloads',
    stream: true // Enable streaming
  }
});

listener.on('attachment', (attachment, filePath) => {
  if (attachment.contentType === 'application/pdf') {
    console.log('PDF attachment:', filePath);
  }
});

⚠️ Important Notes

1. Gmail Requirements:

  • Enable IMAP in Gmail settings
  • Use App Password if 2FA is enabled
  • Allow "Less secure apps" or configure OAuth2

2. Security:

// Use environment variables for credentials
password: process.env.IMAP_PASSWORD

3. Error Handling

listener.on('error', (err) => {
  if (err.code === 'ECONNRESET') {
    console.warn('Connection reset - will reconnect');
  }
});

📜 License

MIT License. See LICENSE file for details.