{"id":16806,"library":"emailjs-imap-client","title":"EmailJS IMAP Client","description":"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.","status":"maintenance","version":"3.1.0","language":"javascript","source_language":"en","source_url":"git://github.com/emailjs/emailjs-imap-client","tags":["javascript","IMAP"],"install":[{"cmd":"npm install emailjs-imap-client","lang":"bash","label":"npm"},{"cmd":"yarn add emailjs-imap-client","lang":"bash","label":"yarn"},{"cmd":"pnpm add emailjs-imap-client","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides the underlying TCP/TLS socket communication for the IMAP client. This dependency acts as a shim, especially relevant for browser environments or older Node.js versions. The project roadmap indicates a future intention to remove this shim in favor of Node.js's native `net` and `tls` modules, which would be a breaking change.","package":"emailjs-tcp-socket","optional":false}],"imports":[{"note":"The primary `ImapClient` class is exported as a default export for ECMAScript Modules (ESM).","wrong":"import { ImapClient } from 'emailjs-imap-client'","symbol":"ImapClient","correct":"import ImapClient from 'emailjs-imap-client'"},{"note":"When using CommonJS modules (e.g., in Node.js environments prior to ESM adoption), the default export must be accessed via the `.default` property.","wrong":"const ImapClient = require('emailjs-imap-client')","symbol":"ImapClient (CommonJS)","correct":"const ImapClient = require('emailjs-imap-client').default"},{"note":"For TypeScript users, it is recommended to use `import type` if only importing the type definition to prevent bundling unnecessary runtime code. This library provides implicit type inference, but explicit type declarations might be community-contributed.","symbol":"ImapClient (Type)","correct":"import type ImapClient from 'emailjs-imap-client'"}],"quickstart":{"code":"import ImapClient from 'emailjs-imap-client';\n\nconst host = 'localhost'; // Replace with your IMAP server host, e.g., 'imap.mail.com'\nconst port = 143; // Standard IMAP port (993 for IMAPS)\nconst username = 'testuser'; // Replace with your IMAP username\nconst password = process.env.IMAP_PASS ?? 'testpass'; // Use environment variable for real passwords in production\n\nasync function runImapClient() {\n  // Create a new client instance for each connection session due to reusability limitations.\n  const client = new ImapClient(host, port, {\n    auth: {\n      user: username,\n      pass: password\n    },\n    // Recommended for secure connections: useSecureTransport for IMAPS, requireTLS for STARTTLS.\n    // useSecureTransport: true, // For IMAPS (SSL/TLS on connection, typically port 993)\n    // requireTLS: true,       // Force STARTTLS if server supports it, fail if not.\n    // ignoreTLS: true,        // Use with extreme caution: allows plain text password over unencrypted connection.\n    // For self-signed certificates in dev/test, add:\n    // tls: { rejectUnauthorized: false }\n  });\n\n  client.logLevel = 'info'; // Set verbosity to 'error', 'warn', 'info', 'debug'\n\n  client.on('error', (err) => {\n    console.error('IMAP Client Error:', err);\n  });\n\n  try {\n    await client.connect();\n    console.log('Successfully connected to IMAP server.');\n\n    // Example: List all mailboxes\n    const mailboxes = await client.listMailboxes();\n    console.log('Available Mailboxes:');\n    mailboxes.forEach(mb => console.log(`  - ${mb.name} (Delimiter: '${mb.delimiter}', Flags: ${mb.flags.join(', ')})`));\n\n    // Example: Select 'INBOX' and list messages (first 10)\n    console.log('\\nSelecting INBOX...');\n    const mailboxStatus = await client.selectMailbox('INBOX');\n    console.log(`INBOX has ${mailboxStatus.exists} messages, ${mailboxStatus.unseen} unseen.`);\n\n    const messages = await client.listMessages('INBOX', '1:10', ['uid', 'flags', 'envelope']);\n    console.log('First 10 messages in INBOX:');\n    messages.forEach(msg => {\n      console.log(`  UID: ${msg.uid}, Subject: ${msg.envelope.subject ?? '[No Subject]'}, From: ${msg.envelope.from?.[0]?.address ?? 'N/A'}`);\n    });\n\n    // Disconnect from the server\n    await client.logout();\n    console.log('Disconnected from IMAP server.');\n  } catch (error) {\n    console.error('Failed to connect or perform IMAP operation:', error);\n    // It's crucial to create a new client instance after an error if you want to retry.\n  }\n}\n\nrunImapClient();","lang":"javascript","description":"Demonstrates how to initialize the ImapClient, connect to a server with authentication, list mailboxes, select a mailbox, list messages, and handle basic errors, emphasizing security for passwords and instance reusability."},"warnings":[{"fix":"Always create a new `new ImapClient(...)` instance after a connection is closed or fails, before attempting to reconnect or perform new operations. Do not try to reconnect with an old instance.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Evaluate the current state against project needs. Be prepared to contribute fixes or features, or consider forking if dedicated maintenance is required. Monitor the GitHub repository for new maintainers and community activity.","message":"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.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"For secure connections, explicitly set `options.useSecureTransport: true` for IMAPS (SSL/TLS on connection, typically port 993) or `options.requireTLS: true` to enforce STARTTLS. Use `options.ignoreTLS: true` only if you fully understand the security implications and accept plain-text communication.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Monitor future release notes closely. If you have custom socket implementations or browser environments currently using the `emailjs-tcp-socket` shim, be prepared for potential adjustments and ensure compatibility once this breaking change is introduced.","message":"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.","severity":"breaking","affected_versions":">=3.1.0 (future unreleased versions)"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"For 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.","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.","error":"Error: Self-signed certificate in certificate chain"},{"fix":"Double-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.","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).","error":"Error: AUTHENTICATION FAILED"},{"fix":"Check 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.","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.","error":"Error: Client connection terminated unexpectedly"}],"ecosystem":"npm","meta_description":null}