JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 13
  • Score
    100M100P100Q62852F
  • License MIT

IMAP listener for Node.js using imapflow

Package Exports

  • mail-listener-flow
  • mail-listener-flow/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (mail-listener-flow) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

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: 'your-email@gmail.com',
  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: 'user@domain.com',
  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.