EmailJS IMAP Client
emailjs-imap-client is a low-level JavaScript IMAP client designed to interact with IMAP servers for email management. It provides a programmatic interface for tasks like connecting, authenticating, listing mailboxes, fetching messages, and other standard IMAP operations. The current stable version is 3.1.0, released approximately six years ago. The library is currently in a maintenance state, as the original author is no longer actively maintaining it, and there's an open call for community contributions. This means new feature development and proactive bug fixes are sporadic or non-existent without community involvement. Its primary differentiator is being one of the few dedicated IMAP client implementations available for JavaScript environments, making it a critical component for applications requiring direct IMAP protocol interaction. It handles both plain and TLS-secured connections, with configurable STARTTLS behavior.
Common errors
-
Error: Self-signed certificate in certificate chain
cause The IMAP server uses a self-signed TLS certificate or one issued by an untrusted Certificate Authority (CA), which the client's TLS stack does not recognize.fixFor development or testing, you can set `tls: { rejectUnauthorized: false }` in the options object of `ImapClient` (use with extreme caution in production as it bypasses certificate validation). For production, ensure the IMAP server uses a certificate from a trusted CA, or configure your system/environment to trust the custom CA if applicable. -
Error: AUTHENTICATION FAILED
cause The provided username, password, or OAuth2 access token in the `auth` options is incorrect or the IMAP server rejected the authentication attempt for another reason (e.g., account locked, app-specific password required).fixDouble-check the `auth.user` and `auth.pass` (or `auth.xoauth2`) values for typos. Verify credentials directly with the IMAP server using another client if possible. Check server-side logs for more specific authentication failure reasons, and ensure the account doesn't require specific app passwords or two-factor authentication bypasses. -
Error: Client connection terminated unexpectedly
cause The IMAP server closed the TCP connection prematurely, possibly due to a timeout, an invalid command from the client, too many failed attempts, or underlying network instability. This can also happen if the server enforces idle timeouts.fixCheck network connectivity to the IMAP server. Review server logs for specific error messages. Ensure your client's commands adhere strictly to the IMAP protocol. Remember that `ImapClient` instances are not reusable; if the connection drops, a new instance must be created to reconnect. Consider implementing a robust retry mechanism with new client instances.
Warnings
- gotcha ImapClient instances cannot be reused. After a connection is terminated (either intentionally via `logout()` or `close()`, or due to an error), a new `ImapClient` instance must be created for subsequent operations. Reattempting to use a disconnected or errored instance will lead to unexpected behavior and potential errors.
- gotcha The library is not actively maintained by its original author. While functional, future feature development, proactive bug fixes, and updates to the IMAP protocol or underlying dependencies are reliant on community contributions. This poses a long-term risk for new projects or those requiring active support.
- gotcha Default STARTTLS support is opportunistic. If the server advertises STARTTLS, the client attempts to use it. If not, credentials might be sent in plain text over an unencrypted connection, which is a significant security risk. For explicit security, always configure `useSecureTransport`, `requireTLS`, or `ignoreTLS` carefully.
- breaking Future versions are planned to remove the 'emailjs-tcp-socket' shim in favor of Node.js's native 'net' and 'tls' modules. This change will primarily affect the internal implementation, but could potentially break environments or custom setups that rely on the shim's specific behavior or browser compatibility strategies.
Install
-
npm install emailjs-imap-client -
yarn add emailjs-imap-client -
pnpm add emailjs-imap-client
Imports
- ImapClient
import { ImapClient } from 'emailjs-imap-client'import ImapClient from 'emailjs-imap-client'
- ImapClient (CommonJS)
const ImapClient = require('emailjs-imap-client')const ImapClient = require('emailjs-imap-client').default - ImapClient (Type)
import type ImapClient from 'emailjs-imap-client'
Quickstart
import ImapClient from 'emailjs-imap-client';
const host = 'localhost'; // Replace with your IMAP server host, e.g., 'imap.mail.com'
const port = 143; // Standard IMAP port (993 for IMAPS)
const username = 'testuser'; // Replace with your IMAP username
const password = process.env.IMAP_PASS ?? 'testpass'; // Use environment variable for real passwords in production
async function runImapClient() {
// Create a new client instance for each connection session due to reusability limitations.
const client = new ImapClient(host, port, {
auth: {
user: username,
pass: password
},
// Recommended for secure connections: useSecureTransport for IMAPS, requireTLS for STARTTLS.
// useSecureTransport: true, // For IMAPS (SSL/TLS on connection, typically port 993)
// requireTLS: true, // Force STARTTLS if server supports it, fail if not.
// ignoreTLS: true, // Use with extreme caution: allows plain text password over unencrypted connection.
// For self-signed certificates in dev/test, add:
// tls: { rejectUnauthorized: false }
});
client.logLevel = 'info'; // Set verbosity to 'error', 'warn', 'info', 'debug'
client.on('error', (err) => {
console.error('IMAP Client Error:', err);
});
try {
await client.connect();
console.log('Successfully connected to IMAP server.');
// Example: List all mailboxes
const mailboxes = await client.listMailboxes();
console.log('Available Mailboxes:');
mailboxes.forEach(mb => console.log(` - ${mb.name} (Delimiter: '${mb.delimiter}', Flags: ${mb.flags.join(', ')})`));
// Example: Select 'INBOX' and list messages (first 10)
console.log('\nSelecting INBOX...');
const mailboxStatus = await client.selectMailbox('INBOX');
console.log(`INBOX has ${mailboxStatus.exists} messages, ${mailboxStatus.unseen} unseen.`);
const messages = await client.listMessages('INBOX', '1:10', ['uid', 'flags', 'envelope']);
console.log('First 10 messages in INBOX:');
messages.forEach(msg => {
console.log(` UID: ${msg.uid}, Subject: ${msg.envelope.subject ?? '[No Subject]'}, From: ${msg.envelope.from?.[0]?.address ?? 'N/A'}`);
});
// Disconnect from the server
await client.logout();
console.log('Disconnected from IMAP server.');
} catch (error) {
console.error('Failed to connect or perform IMAP operation:', error);
// It's crucial to create a new client instance after an error if you want to retry.
}
}
runImapClient();