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 listenerstop(): 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_PASSWORD3. Error Handling
listener.on('error', (err) => {
if (err.code === 'ECONNRESET') {
console.warn('Connection reset - will reconnect');
}
});📜 License
MIT License. See LICENSE file for details.
