@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 mailboxexpunge: Emitted when messages are deleted from the mailboxfetch: Emitted when message attributes are updatedrecent: Emitted when the number of recent messages changesflags: Emitted when message flags changelist: Emitted when mailbox list information is receivedresponse: Emitted for raw IMAP responseserror: Emitted when an error occursclose: Emitted when the connection is closed
API
ImapClient(options)
Creates a new IMAP client instance.
Options
host(string): The IMAP server hostnameport(number): The IMAP server port (typically 143 for non-secure, 993 for secure)secure(boolean): Whether to use TLS/SSL connectionuser(string): The username/email addresspassword(string, optional): The password for authenticationaccessToken(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 operationuid(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 operationuid(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 operationuid(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 operationuid(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 operationuid(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 operationuid(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 operationuid(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
