bởi Milo

ImapFlow is a promise-based IMAP client for Node.js featuring async/await, automatic extension handling, and message streaming. Ideal for backend developers building email integrations.
ImapFlow is a promise-based IMAP client library for Node.js that abstracts the IMAP protocol into a clean async/await API. It auto-detects and uses server extensions (CONDSTORE, QRESYNC, IDLE, COMPRESS, etc.) transparently. The typical buyer is a backend engineer integrating email reading, searching, or synchronization into a Node.js service or CLI tool.
imap-flow.js - Main ImapFlow class; the entry point for all connections and operationsimap-flow.d.ts - Full TypeScript type definitions for ImapFlow, options, and eventsimap-commands.js - Registry of IMAP command handler modules loaded by the clienttools.js - Internal utilities: path encoding, message formatting, AuthenticationFailure error classsearch-compiler.js - Compiles structured search query objects into IMAP SEARCH protocol attributesspecial-use.js - Locale-aware folder name mappings for detecting special-use mailboxes (Sent, Trash, etc.)logger.js - Pino-based logger factory used internallylimited-passthrough.js - Transform stream that enforces a byte limit on a passthroughproxy-connection.js - SOCKS/HTTP CONNECT proxy negotiation helpercharsets.js - Charset resolution helpers for non-UTF-8 encoded message partsjp-decoder.js - Japanese encoding (EUC-JP, ISO-2022-JP) decodercommands/ - One file per IMAP command (fetch, search, select, store, append, etc.)handler/ - Low-level IMAP protocol parser, compiler, stream, and formal syntaxnpm install @zone-eu/mailsplit encoding-japanese iconv-lite libbase64 libmime libqp nodemailer pino socks
No native build steps, iOS pods, or Android linking are required. All dependencies are pure JS or pre-built Node.js addons distributed via npm.
source/ directory into your project, for example as src/imapflow/.src/imapflow/imap-flow.js:
import { ImapFlow } from './imapflow/imap-flow';
Khởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This JavaScript library / package completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 2c30276e27e48db5…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
tsconfig.json{
"compilerOptions": {
"paths": {
"imapflow/*": ["src/imapflow/*"]
}
}
}
require). If your project is ESM, either use dynamic import() or set "type": "commonjs" in the containing package.json.ImapFlowOptions passed to the constructor (see API section).pino. Pass logger: false to suppress all output, or supply a custom logger object that implements debug, info, warn, error.import { ImapFlow, ImapFlowOptions } from './imapflow/imap-flow';
const client = new ImapFlow(options: ImapFlowOptions);
The main class. Extends EventEmitter. Manages the TCP/TLS connection lifecycle, authentication, mailbox selection, and all IMAP commands. Instantiate once per account session; it is not reusable after logout().
interface ImapFlowOptions {
host: string;
port: number;
secure?: boolean;
servername?: string;
auth?: {
user: string;
pass?: string;
accessToken?: string;
loginMethod?: string;
authzid?: string;
};
disableCompression?: boolean;
disableAutoIdle?: boolean;
qresync?: boolean;
maxIdleTime?: number;
proxy?: string;
logger?: Logger | false;
logRaw?: boolean;
verifyOnly?: boolean;
connectionTimeout?: number;
greetingTimeout?: number;
tls?: ConnectionOptions;
}
The configuration object passed to the ImapFlow constructor. host, port, and auth are the only fields needed for a basic connection. Use secure: true for port 993, secure: false with STARTTLS for port 143.
import { AuthenticationFailure } from './imapflow/tools';
class AuthenticationFailure extends Error {
authenticationFailed: true;
}
Thrown by client.connect() when credentials are rejected. Check err.authenticationFailed === true to distinguish auth errors from network errors and retry or surface a user-facing message accordingly.
Establish a TLS connection, acquire a mailbox lock (prevents concurrent access), fetch the raw RFC 822 source of the most recent message, then cleanly release the lock and log out.
import { ImapFlow } from './imapflow/imap-flow';
import { AuthenticationFailure } from './imapflow/tools';
async function fetchLatestSource(): Promise<void> {
const client = new ImapFlow({
host: 'imap.example.com',
port: 993,
secure: true,
auth: { user: 'user@example.com', pass: 'secret' },
logger: false
});
try {
await client.connect();
const lock = await client.getMailboxLock('INBOX');
try {
const msg = await client.fetchOne(client.mailbox.exists, { source: true });
if (msg) {
console.log(msg.source.toString());
}
} finally {
lock.release();
}
await client.logout();
} catch (err) {
if (err instanceof AuthenticationFailure) {
console.error('Bad credentials:', err.message);
} else {
throw err;
}
}
}
fetchLatestSource().catch(console.error);
Use the structured search API to find all unread messages, then stream their envelopes with client.fetch().
import { ImapFlow } from './imapflow/imap-flow';
async function listUnseen(): Promise<void> {
const client = new ImapFlow({
host: 'imap.example.com',
port: 993,
secure: true,
auth: { user: 'user@example.com', pass: 'secret' },
logger: false
});
await client.connect();
const lock = await client.getMailboxLock('INBOX');
try {
// search returns an array of sequence numbers / UIDs
const uids = await client.search({ seen: false }, { uid: true });
if (uids.length) {
for await (const msg of client.fetch(uids, { envelope: true, flags: true }, { uid: true })) {
console.log(msg.uid, msg.envelope.subject, [...msg.flags]);
}
}
} finally {
lock.release();
}
await client.logout();
}
listUnseen().catch(console.error);
Connect through an HTTP CONNECT proxy using an OAuth2 access token instead of a password.
import { ImapFlow } from './imapflow/imap-flow';
async function oauthViaProxy(): Promise<void> {
const client = new ImapFlow({
host: 'imap.gmail.com',
port: 993,
secure: true,
auth: {
user: 'user@example.com',
accessToken: process.env.GMAIL_ACCESS_TOKEN!
},
proxy: 'http://proxy.corp.internal:3128',
logger: false
});
await client.connect();
const lock = await client.getMailboxLock('INBOX');
try {
console.log(`Total messages: ${client.mailbox.exists}`);
} finally {
lock.release();
}
await client.logout();
}
oauthViaProxy().catch(console.error);
imap-flow.js - Defines the ImapFlow class; owns the socket, state machine, event loop, and delegates commands to commands/.imap-flow.d.ts - TypeScript declarations; source of truth for option shapes, event names, and method signatures.imap-commands.js - Aggregates all command modules so ImapFlow can dispatch by command name.tools.js - Shared helpers: encodePath/decodePath for modified UTF-7, formatMessageResponse, AuthenticationFailure, packMessageRange.search-compiler.js - Translates a plain JS search object (e.g. { seen: false, from: 'alice' }) into the wire-format IMAP SEARCH attribute list.special-use.js - Exports flags (RFC 6154 special-use flag list) and names (per-locale folder name arrays) for heuristic folder detection.logger.js - Wraps pino and produces child loggers attached to each connection.limited-passthrough.js - Node.js Transform that passes data through up to a configurable byte ceiling, then emits an error or ends.proxy-connection.js - Implements HTTP CONNECT and SOCKS4/5 handshakes before handing the socket to the TLS layer.charsets.js - Maps IANA charset names to iconv-lite codec strings for decoding message bodies.jp-decoder.js - Specialized decoder for Japanese encodings via encoding-japanese.commands/ - Individual IMAP command implementations (fetch, search, select, store, append, idle, etc.).handler/ - Raw IMAP protocol layer: imap-parser.js reads token streams, imap-compiler.js serialises command objects, imap-stream.js wraps the socket.try/finally and call lock.release() in the finally block; an unreleased lock hangs all subsequent commands indefinitely.require(); in an ESM project wrap imports with createRequire or rename consuming files to .cjs.tls: { rejectUnauthorized: false } for dev, or tls: { ca: fs.readFileSync('ca.pem') } for production.GMAIL_ACCESS_TOKEN expiry: OAuth2 tokens are short-lived; the library does not refresh them automatically - obtain a fresh token before each client.connect() call.ImapFlow is not safe to share across async contexts; instantiate one client per concurrent session or use the built-in getMailboxLock serialisation.pino version conflict: if your project pins a different major version of pino, the logger factory in logger.js may break; add pino to your own dependencies at the same version the source requires.I have vendored the ImapFlow IMAP client library into my project under `src/imapflow/`.
The integration guide is in `src/imapflow/USAGE.md`.
The upstream package is `user@example.com`.
Please help me integrate this library into my existing Node.js/TypeScript project step by step:
1. Read `src/imapflow/USAGE.md` and `src/imapflow/imap-flow.d.ts` for all types and method signatures.
2. Import `ImapFlow` from `src/imapflow/imap-flow.js` and `AuthenticationFailure` from `src/imapflow/tools.js`.
3. Add a connection helper that reads IMAP credentials from environment variables and returns a connected, authenticated `ImapFlow` instance.
4. Add a service method that accepts a mailbox name and a search query object, acquires the mailbox lock, runs the search, fetches envelopes, releases the lock, and returns the results.
5. Ensure all locks are released in finally blocks and the client is logged out after use.
6. Wire the service into my existing Express route at POST /api/mail/search.
7. Add TypeScript types throughout using `src/imapflow/imap-flow.d.ts`.
Licensed under the MIT License. Copyright (c) 2020-2025 Postal Systems OU. Source upstream: imapflow on npm, maintained at github.com/postalsys/imapflow.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
Automation, Utilities & Developer Tools
Miễn phí