Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

imapflow

postalsys655.5kMIT1.0.199TypeScript support: included

IMAP Client for Node

imap, email, mail

readme

ImapFlow

ImapFlow is a modern and easy-to-use IMAP client library for Node.js.

[!NOTE] Managing an IMAP connection is cool, but if you are only looking for an easy way to integrate email accounts, then ImapFlow was built for EmailEngine Email API. It's a self-hosted software that converts all IMAP accounts to easy-to-use REST interfaces.

The focus for ImapFlow is to provide easy to use API over IMAP. Using ImapFlow does not expect knowledge about specific IMAP details. A general understanding is good enough.

IMAP extensions are handled in the background, so, for example, you can always request labels value from a {@link FetchQueryObject|fetch()} call, but if the IMAP server does not support X-GM-EXT-1 extension, then labels value is not included in the response.

Source

Source code is available from Github.

Usage

First install the module from npm:

npm install imapflow

next import the ImapFlow class into your script:

const { ImapFlow } = require('imapflow');

Promises

All ImapFlow methods use Promises, so you need to wait using await or wait for the then() method to fire until you get the response.

const { ImapFlow } = require('imapflow');
const client = new ImapFlow({
    host: 'ethereal.email',
    port: 993,
    secure: true,
    auth: {
        user: 'garland.mcclure71@ethereal.email',
        pass: 'mW6e4wWWnEd3H4hT5B'
    }
});

const main = async () => {
    // Wait until client connects and authorizes
    await client.connect();

    // Select and lock a mailbox. Throws if mailbox does not exist
    let lock = await client.getMailboxLock('INBOX');
    try {
        // fetch latest message source
        // client.mailbox includes information about currently selected mailbox
        // "exists" value is also the largest sequence number available in the mailbox
        let message = await client.fetchOne(client.mailbox.exists, { source: true });
        console.log(message.source.toString());

        // list subjects for all messages
        // uid value is always included in FETCH response, envelope strings are in unicode.
        for await (let message of client.fetch('1:*', { envelope: true })) {
            console.log(`${message.uid}: ${message.envelope.subject}`);
        }
    } finally {
        // Make sure lock is released, otherwise next `getMailboxLock()` never returns
        lock.release();
    }

    // log out and close connection
    await client.logout();
};

main().catch(err => console.error(err));

Admin Impersonation / Delegation (SASL PLAIN with authzid)

ImapFlow supports admin impersonation for mail systems like Zimbra that allow administrators to access user mailboxes. This is done using the SASL PLAIN mechanism with an authorization identity (authzid).

const { ImapFlow } = require('imapflow');
const client = new ImapFlow({
    host: 'mail.example.com',
    port: 993,
    secure: true,
    auth: {
        user: 'admin@example.com', // Admin credentials (authentication identity)
        pass: 'adminpassword',
        authzid: 'user@example.com', // User to impersonate (authorization identity)
        loginMethod: 'AUTH=PLAIN' // Must use PLAIN mechanism for authzid
    }
});

// Connection will authenticate as admin but authorize as the specified user
await client.connect();
// Now operating on user@example.com's mailbox as admin

Note: The authzid parameter only works with the AUTH=PLAIN mechanism. The server must support admin delegation/impersonation for this to work.

Documentation

API reference.

License

© 2020-2024 Postal Systems OÜ

Licensed under MIT-license

changelog

Changelog

1.0.199 (2025-10-09)

Bug Fixes

1.0.198 (2025-09-29)

Bug Fixes

1.0.197 (2025-09-24)

Bug Fixes

  • imap ID: Re-request ID information if only a single key was returned (87bc016)

1.0.196 (2025-09-14)

Bug Fixes

  • Added authzid option for AUTH=PLAIN authentication (541c43a)

1.0.195 (2025-08-26)

Bug Fixes

  • Add async yielding to compression readNext() to prevent CPU blocking (18e806d)
  • Add async yielding to lock processing loop (fbf1d9a)
  • Add async yielding to processInput() to prevent CPU blocking (6b619ce)
  • Add async yielding to reader() method to prevent CPU blocking (40574e3)
  • Add exponential backoff to FETCH retry logic (fb99e2d)
  • Add rate limiting for compression operations (f54c1d0)
  • Correct log source indicator for client commands (bb3ea09)

1.0.194 (2025-08-13)

Bug Fixes

  • Fixed race condition when opening multiple mailboxes simultaneusly (1248f84)
  • Merge branch 'master' into mustang-im-trycatch (b024a0a)

1.0.193 (2025-07-31)

Bug Fixes

  • Improved exception handling (0eb77ac)

1.0.192 (2025-07-31)

Bug Fixes

  • destroy _inflate and _deflate streams if set (eab274b)
  • do not allow too large IMAP literals (680a44d)
  • Improved socket handler listener setup/cleanup (0b72714)
  • remove unneeded timer (1867606)

1.0.191 (2025-07-10)

Bug Fixes

  • search: Use the next day when searching BEFORE/SENTBEFORE to include current day in the range as well (9e6d749)

1.0.190 (2025-07-10)

Bug Fixes

  • search: Prefer WITHIN YOUNGER/OLDER instead of BEFORE/SINCE for searches if possible (7492ac9)

1.0.189 (2025-06-30)

Bug Fixes

  • improved error handling (0b955e4)
  • Remove diacritics in ID values (c79df56)

1.0.188 (2025-06-13)

Bug Fixes

  • atom: Allow < and [ in an atom value (53b96bb)

1.0.187 (2025-05-20)

Bug Fixes

1.0.186 (2025-04-20)

Bug Fixes

  • parsing: Limit the depth of nested input (c6cd7ce)

1.0.185 (2025-04-14)

Bug Fixes

  • search: add a not option for search options (#281) (000686b)

1.0.184 (2025-03-11)

Bug Fixes

  • Allow to call the connect method only once (ca7ec96)
  • Authentication: Report errors; Fix LOGINDISABLED (#275) (a3a3fb9)

1.0.183 (2025-03-09)

Bug Fixes

  • Date time format in IMAP requires space before a single digit (#272) (bdb6b09)

1.0.182 (2025-03-04)

Bug Fixes

  • messageFlagsSet with empty flag array (#268) (7de471c)

1.0.181 (2025-02-06)

Bug Fixes

  • parser: Fixed DIGIT handling' (75389f1)

1.0.180 (2025-02-06)

Bug Fixes

  • tls: If socket fails then clear upgrade timeout as well (12c60d2)

1.0.179 (2025-01-28)

Bug Fixes

  • connection-failure: Reject all pending commands, not just LOGOUT (1b42a61)

1.0.178 (2025-01-23)

Bug Fixes

  • bodystructure: Handle unicode filenames for servers that do not know how to use parameter continuations (2b4b240)

1.0.177 (2025-01-17)

Bug Fixes

  • login: When using slashes in username (indicates an Exchange account or drive account), use LOGIN as the authentication mechanism (7ac0036)

1.0.176 (2025-01-15)

Bug Fixes

  • idle: Treat preCheck as async function (346bb43)

1.0.175 (2025-01-15)

Bug Fixes

  • socket: Throw an error if trying to write to a closed socket (1d8e941)

1.0.174 (2025-01-08)

Bug Fixes

  • auth: Fixed AUTHENTICATE LOGIN if server uses 'VXNlciBOYW1lAA==' for username (86c08a7)

1.0.173 (2025-01-08)

Bug Fixes

  • bodystructure: Handle invalid BODYSTRUCTURE from Bluemind mail server (b63f861)

1.0.172 (2025-01-03)

Bug Fixes

  • password-auth: Added option auth.loginMethod to set specific authentication method ('LOGIN', 'AUTH=PLAIN', 'AUTH=LOGIN') (ce3c339)

1.0.171 (2024-12-05)

Bug Fixes

  • Trying to re-publish as previous release attempt failed, no actual changes (d882816)

1.0.170 (2024-12-05)

Bug Fixes

  • uidvalidity: Do not expect UIDVALIDITY to always exist (7761653)

1.0.169 (2024-11-08)

Bug Fixes

  • fetc: Treat 'Some of the requested messages no longer exist' as a success, not a failure (565f988)

1.0.168 (2024-11-07)

Bug Fixes

  • imap: Fixed issue with a single + response (51be3a9)

1.0.167 (2024-11-07)

Bug Fixes

  • auth: Prefer AUTH=LOGIN and AUTH=PLAIN to LOGIN (3efd98a)

1.0.166 (2024-11-05)

Bug Fixes

  • login: Always treat username and password as strings, not atom (01b3471)

1.0.165 (2024-11-01)

Bug Fixes

  • imap: Support invalid servers that return a full partial instead of starting byte for a FETCH property (7281ce9)

1.0.164 (2024-07-09)

Bug Fixes

1.0.163 (2024-07-06)

Bug Fixes

  • parser: parse subfolders with square brackets (0d0e8a6)
  • socket: Use destroy() instead of destroySoon() (830c2d1)

1.0.162 (2024-05-07)

Bug Fixes

  • idle: Do not clear preCheck from other command (cdf7643)

1.0.161 (2024-05-06)

Bug Fixes

  • listTree: pass listing options as an optional argument (917ba80)

1.0.160 (2024-04-22)

Bug Fixes

  • copy: Updated cipyright year to 2024 (e3f5040)

1.0.159 (2024-04-12)

Bug Fixes

1.0.158 (2024-03-19)

Bug Fixes

  • locking: log extra information about locks (9790ec5)

1.0.157 (2024-03-19)

Bug Fixes

  • logs: Log mailbox lock description (ce87cf5)

1.0.156 (2024-03-07)

Bug Fixes

  • micro-optimizations for parser (3451ad2)

1.0.155 (2024-03-06)

Bug Fixes

  • exchange: handle special error response from exchange (3ed4198)

1.0.154 (2024-03-05)

Bug Fixes

  • FETCH: throw on failing FETCH (12f9a45)

1.0.153 (2024-02-29)

Bug Fixes

1.0.152 (2024-02-12)

Bug Fixes

  • address: do not use '@' instead of empyt address if a field does not contain a value (aeabbde)

1.0.151 (2024-02-12)

Bug Fixes

  • filename: Fixed filename decoding for the download method (68a8159)

1.0.150 (2024-02-01)

Bug Fixes

  • deps: Bumped Nodemailer version (ee02764)

1.0.149 (2024-01-31)

Bug Fixes

  • flag-colors: added a method to set Flag Color. The color is also included in the Fetch response structure (d840951)

1.0.148 (2024-01-16)

Bug Fixes

  • logout: Fixed race condition for logout and TCP close. Fixes #161 (39a7333)

1.0.147 (2023-10-26)

Bug Fixes

  • idle: removed unneeded variable (da59d9a)

1.0.146 (2023-10-26)

Bug Fixes

  • throttling: automatically retry throttled FETCH commands a few times (07a9aea)

1.0.145 (2023-10-26)

Bug Fixes

  • docs: Fixed mailbox property name in AppendResponseObject (ca6d789)
  • special-use: support custom special use flags for the Archive folder (17aa6a8)

1.0.144 (2023-09-13)

Bug Fixes

  • MS365: Wait until responding with a throttling response (#142) (09bfb3e)

1.0.143 (2023-09-04)

Bug Fixes

  • release: updated provenance setting (e178629)

1.0.142 (2023-09-04)

Bug Fixes

  • release: updated provenance setting (4fd5fa8)

1.0.141 (2023-09-04)

Bug Fixes

  • readme: testing note format (3038c4d)

1.0.140 (2023-09-04)

Bug Fixes

  • license: bumped license timeframe in README (9a04730)

1.0.139 (2023-09-04)

Bug Fixes

  • license: Bumped license timeframe (ce308b6)

1.0.138 (2023-09-04)

Bug Fixes

  • release: Added package-lock (e35bda8)
  • release: updated package-lock (b59220f)

1.0.137 (2023-09-04)

Bug Fixes

  • deps: Bumped dependencies (e8f5e8c)

CHANGELOG

  • 1.0.136 - 2023-08-15

    • Added missing destroySoon method for the PassThrough writable socket
  • 1.0.135 - 2023-07-29

    • Improved handling of unexpected close
  • 1.0.134 - 2023-07-20

    • Fixed unicode search if UTF8=ACCEPT extension was enabled
  • 1.0.131 - 2023-06-29

    • Fixed issue with labels that start with tilde
  • 1.0.129 - 2023-06-12

    • Bumped deps for maintenance
  • 1.0.127 - 2023-04-10

    • Use default Node.js TLS settings
  • 1.0.123 - 2023-03-22

    • Do not throw if server responds with tag BYE
  • 1.0.118 - 2022-12-22

    • Refactored detecting special use folders
  • 1.0.117 - 2022-12-05

    • Updated command compiling. The command compiler returns a Buffer, not a "binary" string.
  • 1.0.116 - 2022-11-30

    • Added SPECIAL-USE flag by default when given parameters to Imap#list
  • 1.0.113 - 2022-10-21

    • Added stats() method to get the count of bytes sent and received
  • 1.0.112 - 2022-10-16

    • Improved ID compatibility with servers that allow ID only after login
  • 1.0.111 - 2022-10-13

    • Added new connection options
      • connectionTimeout=90000: how many milliseconds to wait for the connection to establish (default is 90 seconds)
      • greetingTimeout=16000: how many milliseconds to wait for the greeting after connection is established (default is 16 seconds)
      • socketTimeout=300000: how many milliseconds of inactivity to allow (default is 5 minutes)
  • 1.0.110 - 2022-10-10

    • Allow unicode atoms by default
  • 1.0.109 - 2022-09-29

    • New method downloadMany
  • 1.0.102 - 2022-08-18

  • 1.0.100 - 2022-06-17

    • Emit new message notification if appending to currently opened folder
  • 1.0.99 - 2022-06-05

    • Check if folder exists on failed status command
  • 1.0.98 - 2022-05-30

    • Fixed an issue with envelope parsing where literal values were returned as Buffers
  • 1.0.97 - 2022-05-29

    • Allow single quotes in atoms
  • 1.0.96 - 2022-05-18

    • Allow non-standard characters in ATOM if it's the string after NO/OK/BAD response
  • 1.0.95 - 2022-05-03

    • Do not use FETCH BINARY, unless binary option is true
  • 1.0.94 - 2022-05-03

    • Fixed source download
  • 1.0.93 - 2022-05-03

    • Fixed missing unicode encoding for APPEND, COPY, MOVE
  • 1.0.92 - 2022-05-03

    • Added support for IMAP BINARY extension (rfc3516)
    • Logging improvements
  • 1.0.91 - 2022-05-02

    • Do not throw if literal includes a null byte
    • Use UTF8 path names by default
    • Overrides '*' range query with the EXISTS value
  • 1.0.90 - 2022-04-04

    • Added new configuration option maxIdleTime
  • 1.0.89 - 2022-04-04

    • Added new event type response that emits all command responses
  • 1.0.88 - 2022-03-24

    • Fixed folder name match where not all non-ascii characters triggered UTF encoding
  • 1.0.87 - 2022-03-21

    • If LIST failed then do not suppress exception
  • 1.0.86 - 2022-03-14

    • Do not try to decode mailbox path from utf7 as methods expect utf-8 not utf-7
  • 1.0.85 - 2022-02-23

    • Trim null bytes in the beginning of IMAP responses to deal with a buggy server that pads responses with null bytes
  • 1.0.84 - 2022-02-17

    • QRESYNC tweaks
  • 1.0.83 - 2022-02-16

    • QRESYNC tweaks
  • 1.0.82 - 2022-02-15

    • Added extra option expungeHandler
  • 1.0.81 - 2022-02-15

    • Added support for the QRESYNC extension and untagged VANISHED responses
  • 1.0.80 - 2022-02-07

    • Added support for the missing NOMODSEQ mailbox modifier
  • 1.0.79 - 2021-12-29

    • Added property greeting that contains that first response from the server
  • 1.0.78 - 2021-11-28

    • Proxy support. Use configuration options proxy: "url" to use proxies
  • 1.0.77 - 2021-11-25

    • Testing out proxy connections
    • Add X-GM-RAW support for search (jhi721 #68)
  • 1.0.75 - 2021-10-15

    • Fixed an exception with failing IDLE (ramiroaisen #60)
    • Do not use 1 and 1.MIME for single node messages, fallback to TEXT and HEADERS
  • 1.0.71 - 2021-09-28

    • IDLE precheck changes
  • 1.0.70 - 2021-09-27

    • IDLE logging changes
  • 1.0.69 - 2021-09-27

    • Added option logRaw to log data read from and written to the socket
  • 1.0.68 - 2021-09-16

    • Decrease message count on untagged EXPUNGE even if EXISTS does not follow
  • 1.0.67 - 2021-08-02

    • Added new option chunkSize for download() options
  • 1.0.66 - 2021-07-30

    • Meta update to change README
    • Replaced andris9/imapflow with postalsys/imapflow
  • 1.0.65 - 2021-07-25

    • Changed project license from AGPL to MIT
  • 1.0.59 - 2021-06-16

    • Fixed issue with complex OR search
  • 1.0.57 - 2021-04-30

    • Do not wait indefinitely after logout if connection was not established
  • 1.0.56 - 2021-03-18

    • Fixed issue with exploding LOGOUT
  • 1.0.55 - 2021-03-17

    • Fixed raw source downloads
  • 1.0.53 - 2021-02-17

  • 1.0.52 - 2021-02-17

    • Fixed HTML content loading for some messages from Outlook/Hotmail
  • 1.0.51 - 2020-09-24

    • Close connection after LOGOUT even if command fails
  • 1.0.49 - 2020-09-02

    • When connection is closed mid-command then reject the promise instead of going blank
    • Fix issue with search({uid:'1:*'})
  • 1.0.47 - 2020-05-29

    • Fix search query with {header:{key: true}}
  • 1.0.46 - 2020-05-15

    • Do not use IP address as SNI servername
  • 1.0.45 - 2020-05-02

    • Better support for XOAUTH2
  • 1.0.44 - 2020-04-20

    • Better detcting of special use mailboxes
  • 1.0.43 - 2020-04-20

    • Better handling of NIL as delimiter
  • 1.0.42 - 2020-04-13

    • Try to handle edge case when authenticating against Exchange IMAP
  • 1.0.41 - 2020-04-12

    • Bumped deps
    • Log 'close' event
  • 1.0.40 - 2020-04-06

    • Added option useLabels for message flag update methods to modify Gmail labels instead of message flags
  • 1.0.36 - 2020-03-26

    • Do not try to write to socket if connection already closed
  • 1.0.35 - 2020-03-25

    • Set time argument for setKeepAlive
  • 1.0.34 - 2020-03-25

    • Replaced nodemailer/imapflow with andris9/imapflow
    • Removed TS typings
  • 1.0.33 - 2020-03-20

    • Fixed issue with using date queries in search a0000778
  • 1.0.30 - 2020-03-06

    • Added new option and property emitLogs and 'log' event to fire on every log entry
  • 1.0.29 - 2020-03-05

    • Updated JSDoc for some optional params
    • Better PREAUTH support
  • 1.0.28 - 2020-03-04

    • Changed license of the project from UNLICENSED to AGPL-3.0-or-later
  • 1.0.27 - 2020-03-02

    • Added support for XOAUTH2 and OAUTHBEARERTOKEN authentication mechanisms
  • 1.0.16 - 2020-02-15

    • Logging level changes (FETCH responses downgraded from DEBUG to TRACE)
  • 1.0.14 - 2020-02-13

    • Added new property idling
  • v1.0.13 - 2020-02-12

    • Do not filter out changes with same MODSEQ value
  • v1.0.12 - 2020-02-12

    • Logging level changes
  • v1.0.11 - 2020-02-06

    • Bump current uidNext if message UID seems to be higher
  • v1.0.10 - 2020-02-02

    • Use debug logging level for IMAP traffic
  • v1.0.9 - 2020-02-02

    • Yet another documentation change to get TypeScript typings more correct
  • v1.0.8 - 2020-02-02

    • Documented missing option changedSince for fetch
    • Emit changes also on STATUS
  • v1.0.7 - 2020-01-31

    • Added new method getMailboxLock() to lock a mailbox for usage
    • Added new connection events "mailboxOpen" and "mailboxClose"
  • v1.0.6 - 2020-01-30

    • Updated TypeScript typings
    • Updated ID request formatting
  • v1.0.5 - 2020-01-29

    • Updated TypeScript typings
  • v1.0.3 - 2020-01-28

    • Fixed eternal loop when breaking IDLE after connection is closed
  • v1.0.2 - 2020-01-24

    • Allow using emailId and threadId as search parameters
  • v1.0.1 - 2020-01-14

    • Initial version. Had to use v1.0.1 as v1.0.0 was already taken by template repository.