package
Scriptable, strictly RFC compliant in-memory IMAP server for testing IMAP clients
npm install imapkitGitHub-flavored package documentation.
Across all versions.
Download trend unavailable.
Runtime metadata.
Tagged topics.
Estimated unpacked size across 2 packages.
3.0 MB
Includes dependencies.
ImapKit is a scriptable, in-memory IMAP server for testing IMAP clients. It implements IMAP4rev1 (RFC 3501) and, as an optional plugin, IMAP4rev2 (RFC 9051), with more than 50 extensions that can be turned on and off per server instance. Nothing is ever written to disk: the mailbox tree comes from a JSON object, so every new server starts from the same known state.
ImapKit is strict on purpose: it answers client input that breaks the RFCs with BAD or NO, so client bugs show up in your test suite instead of in production (see Strict by design).
Homepage: imapkit.com. ImapKit requires Node.js 20 or newer.
ImapKit is maintained by the team behind EmailEngine, a self-hosted email API that turns Gmail, Microsoft 365, and IMAP accounts into REST endpoints, with managed OAuth2 and webhooks for incoming mail. If you need a production email integration rather than a mock IMAP server for tests, start there.
Formerly Hoodiecrow. ImapKit was published as
hoodiecrow-imapup to version 3.3.1. To migrate, installimapkitinstead and userequire('imapkit'). The command is nowimapkitand its environment variables start withIMAPKIT_instead ofHOODIECROW_. The API, plugins and storage format are unchanged.
Install ImapKit globally with npm and run it:
npm install -g imapkit
imapkit -p 1143Point your IMAP client to localhost:1143 and log in with user name testuser and password testpass. Without -p the server listens on port 143 (993 with --secure), which usually needs root privileges.
imapkit -p 1143 --tls-port=1993 also listens for implicit TLS (IMAPS) connections on port 1993, both ports serve the same mailboxes. imapkit --smtpPort=1025 also starts an SMTP server that appends every message it receives to INBOX. SMTP needs the optional smtp-server package, which is not installed with ImapKit: npm install -g smtp-server (or npm install smtp-server next to a local install).
Run imapkit --help to see all command line options, the environment variables (IMAPKIT_PORT, IMAPKIT_PLUGINS, ...) and sample configuration data. For example, imapkit -p 1143 --plugin=IDLE,MOVE,CONDSTORE --storage=storage.json loads three plugins and the mailboxes of storage.json.
Add imapkit dependency
npm install imapkitCreate and start an IMAP server
import imapkit from 'imapkit';
// or with CommonJS: const imapkit = require('imapkit');
const server = imapkit(options);
server.listen(1143);ImapKit is written in TypeScript and ships both ES modules and CommonJS, each with type declarations. The package exports the imapkit(options) factory as its default export, the IMAPServer and IMAPConnection classes, and types such as IMAPServerOptions, Plugin, CommandHandler, Mailbox and Message for writing plugins:
import imapkit, { type IMAPServerOptions, type Plugin } from 'imapkit';ImapKit needs Node.js 20 or newer. It also runs on the latest Bun and Deno releases (npm:imapkit in Deno), CI runs the whole test suite on both.
See complete.js for an example, control-api.js for a client test that changes the server state with the control API, and rest-api.py for the REST API from Python.
imapkit/browser is a single ES module bundle for browsers, for interactive examples and in-page demos. There are no sockets in a browser, so server.connect() opens a connection in memory and returns the client end: write commands to it and read the responses from its data events (Uint8Array chunks, or strings after setEncoding()). server.connect() works in Node.js too and needs no listen().
import imapkit from 'imapkit/browser';
const server = imapkit({ plugins: ['IDLE'] });
const client = server.connect(); // counts as a TLS connection, { secure: false } for plaintext
client.setEncoding('utf8');
client.on('data', text => console.log(text));
client.write('A1 LOGIN testuser testpass\r\n');The client end has write(data, [callback]), end(), destroy(), pause(), resume() and the data, end, close and error events. Each write reaches the server as one chunk on a later event loop turn. By default the connection counts as encrypted, as if it ran over TLS. With { secure: false } it starts as plaintext, and STARTTLS only marks it as encrypted (client.encrypted turns true), nothing is encrypted. A close: 'reset' script rule gives the client an ECONNRESET error. The bundle has every plugin but COMPRESS, which throws when it is loaded; listen(), the SMTP listener and the REST API need Node.js and throw too.
Try it live on imapkit.com runs this bundle in a web terminal, examples/browser.html is a minimal page: run npm run build, serve the repository root over HTTP (npx http-server -c-1 .) and open /examples/browser.html.
ImapKit is a single user, multiple connection IMAP server. Changes made over IMAP live only in the memory of that server instance, so start a new server for every test.
Several clients can connect to the server simultaneously but all the clients share the same user account, even if login credentials are different. The ACL plugin can limit what users other than the owner can do (see ACL).
ImapKit is extendable: any command can be overridden and plugins can be added (see Creating custom plugins, and src/commands and src/plugins for the built-in commands and plugins). To test a client against a broken or unusual server, script rules make the server misbehave at chosen points.
ImapKit is meant for developing standards compliant IMAP clients, so it follows the RFCs strictly instead of accepting whatever clients send. Most production servers are lenient, which hides client bugs until the client meets a stricter server. ImapKit answers these with BAD (or NO where the RFC requires it):
FETCH before SELECT or LOGIN and AUTHENTICATE (with any mechanism, known or not) after loginNOOP x, CLOSE x), missing or extra arguments, and values that break the RFC 3501 grammar+ continuation request (RFC 3501 section 4.3); {n+} is only accepted when LITERAL+ or LITERAL- is enabled, and with LITERAL- only up to 4096 octets, a larger one is answered with BAD [TOOBIG] (RFC 7888 section 5)foo//bar, /foo, foo//), answered with NO [CANNOT] (RFC 5530 section 3)0, abc), message sequence numbers greater than the number of messages in FETCH, STORE, COPY and MOVE, also * in an empty mailbox (RFC 3501 section 9, seq-number; UID sets and SEARCH keys can point past the end), flags that are not atoms, \Recent in STORE or APPEND, invalid datesCHARSET UTF-8, invalid UTF-8, unsupported charsets (NO [BADCHARSET])REVERSE that is not followed by a sort key (REVERSE REVERSE DATE), or a threading algorithm that is not an atomDONE while IDLELOGIN (RFC 9755 section 5: UTF-8 user names need AUTHENTICATE), and invalid UTF-8 in an AUTHENTICATE PLAIN message (RFC 4616 section 2). User names are unicode strings everywhere: the keys of users, SASL user names and ACL identifiers%x01 after an OAUTHBEARER error resultSTARTTLS and COMPRESS with commands pipelined after them (RFC 9051 section 6.2.1, RFC 4978 section 3), TLS or compression is then not started and the pipelined commands are refused with BAD without running, and COMPRESS while compression is active (BAD [COMPRESSIONACTIVE])CHECK followed by FETCH without waiting for the CHECK resultENABLE after SELECT or EXAMINE (RFC 5161 section 3.1), and ID lists that break the RFC 2971 limitsSELECT parameter or the VANISHED modifier without ENABLE QRESYNC, VANISHED with FETCH or without CHANGEDSINCE, and QRESYNC values that break the RFC 7162 grammar (UIDVALIDITY or mod-sequence 0, * in the UID sets, sequence match sets that are not ascending or not of the same size)SEARCH RETURN options or RETURN after CHARSET (RFC 4466 section 2.6.1), $ combined with numbers, and SEARCH MODSEQ values or entry names that break the RFC 7162 grammarRECURSIVEMATCH without a base option like SUBSCRIBED (also (SPECIAL-USE RECURSIVEMATCH), RFC 6154 section 6), an empty pattern list, options with values they do not take, a repeated STATUS return option with different items, and invalid STATUS items (RFC 5819)CREATE ... (USE (...)) (CREATE-SPECIAL-USE) with entries that are not an atom starting with a backslash, like NIL, quoted strings or Sent (RFC 6154 section 6: use-attr-ext = "\" atom); an attribute the server does not support gets NO [USEATTR] (section 3)//, a trailing /, *, %, 8-bit or control characters, a scope other than /private or /shared), values that are atoms or use bare CR or LF as line ends, empty entry or option lists, and GETMETADATA options after the mailbox name (errata 2785)APPEND without MULTIAPPEND, and with MULTIAPPEND a zero-length message literal cancels the whole APPEND with NO (RFC 3502)/INBOX/;UID=1), including relative-path references like ;UID=1 that RFC 5092 section 7.2 forbids, and URLs of message parts that do not exist (NO [BADURL ...])BAD [UIDREQUIRED]UIDAFTER and UIDBEFORE (MESSAGELIMIT, RFC 9738 section 3.2) with anything but a single UIDSEARCH CHARSET after ENABLE UTF8=ACCEPT, mailbox names with control characters (UTF-8, or encoded in modified UTF-7 like &AA0-), U+2028, U+2029, a leading BOM, unassigned code points or a name that is not in Unicode Normalization Form C, and NO for APPEND of a message with an 8-bit header before ENABLE UTF8=ACCEPT (section 4)~{n}) anywhere but in an APPEND or REPLACE message with BINARY, or a SETMETADATA value with METADATA, refused without a continuation request; NUL octets in a normal literal; a literal8 TEXT part in CATENATEBINARY[], BINARY of multipart or message/rfc822 parts (RFC 9051 section 6.4.5 allows leaf body parts only), HEADER, TEXT or MIME sections, and a partial range on BINARY.SIZEselected/selected-delayed (section 6.1), fetch attributes outside the selected filters, empty event or mailbox lists, NOTIFY SET without event groups; unknown events get NO [BADEVENT (...)] listing the supported ones (section 3.1)ENABLE IMAP4rev2 (RFC 9051): CHECK, LSUB, the RFC822, RFC822.HEADER and RFC822.TEXT FETCH items, the NEW, OLD and RECENT SEARCH keys and the RECENT STATUS item, none of which are in the RFC 9051 grammar (Appendix E), numbers above 63 bits in LARGER and SMALLER, and invalid UTF-8 or mailbox names that are not Net-Unicode (section 5.1); before it, 8-bit quoted strings (Appendix A) and partial ranges, LARGER and SMALLER values above 32 bits (RFC 3501 section 9 number)Responses follow the grammar strictly too: strings that can not be quoted are sent as literals. Failures carry the RFC 5530 response codes that RFC 9051 section 7.1 lists, in both protocol revisions: AUTHENTICATIONFAILED and AUTHORIZATIONFAILED for logins, ALREADYEXISTS, NONEXISTENT, CANNOT, HASCHILDREN and NOPERM for mailbox operations, TRYCREATE when the target of APPEND, COPY or MOVE does not exist or is a \Noselect name, CLIENTBUG for STATUS on the selected mailbox and for STORE, EXPUNGE, UID EXPUNGE, MOVE and REPLACE in a mailbox selected read-only, and EXPUNGEISSUED when FETCH, STORE, SEARCH, SORT or THREAD (or UID SEARCH, UID SORT or UID THREAD with message numbers in the criteria) completes while the EXPUNGE of another session can not be reported yet.
Some client side recommendations of RFC 2683 are checked too: STATUS on the selected mailbox gets CLIENTBUG (section 3.1.1), mailbox names must be valid modified UTF-7 (section 3.4.2), and EXPUNGE or STORE after EXAMINE, which answered [READ-ONLY], get NO (section 3.3.2). Command lines are not limited to the 1000 octets that section 3.2.1.5 suggests for clients, the server accepts up to 1 MiB (the section asks servers for at least 8000 octets) and answers a longer line with BAD.
ImapKit follows these of the strategies that RFC 2180 (IMAP4 Multi-Accessed Mailbox Practice) allows, so a client can be tested against one consistent behavior:
OK [EXPUNGEISSUED].SILENT it ends with OK (section 4.2.1), otherwise the other messages are stored and get their FETCH responses, and the tagged response is NO [EXPUNGEISSUED] (sections 4.2.2 and 4.2.3; with CONDSTORE NO [MODIFIED ...] when that applies, RFC 7162 section 3.1.3)NO [EXPUNGEISSUED] (section 4.4.1)OK [EXPUNGEISSUED]* n RECENT with the number of \Recent messages of the session (RFC 3501 section 7.3.2), also for its own APPEND, COPY and MOVE into the selected mailbox, but not after ENABLE IMAP4rev2* BYE (section 3.3)By default the only account is user name "testuser" with password "testpass" (and access token "testtoken" for XOAUTH2 and OAUTHBEARER). The users option replaces the default account list, for example { "testuser": { "password": "testpass" }, "otheruser": { "password": "secret" } }, and server.control.addUser() adds users at runtime (see Control API). All users share the same mailbox tree.
The oauth option (--oauth-port) starts a test identity provider, so a mail client can run its whole OAuth sign-in against ImapKit: the authorization code flow with PKCE, a consent page that needs no password, and tokens that log in to IMAP (XOAUTH2, OAUTHBEARER) and SMTP (AUTH XOAUTH2), expire on the server clock, refresh and can be revoked.
const server = imapkit({
plugins: ['SASL-IR', 'XOAUTH2', 'OAUTHBEARER'],
users: { 'alice@example.com': { password: 'pw', displayName: 'Alice' }, 'denied@example.com': { password: 'pw', oauth: { consent: 'deny' } } },
oauth: { port: 8085 }
});
await server.start(1143); // discovery: http://127.0.0.1:8085/.well-known/openid-configurationA consent policy decides every sign-in, from the first that has one: a queued decision (control.queueOAuthDecision()), the user that login_hint names, the client, the server default. prompt shows the consent page (pick an account, Allow or Deny), approve and deny redirect right away with a plain HTTP 302, so a test can follow the redirect without a browser, and an error object answers with that error. The clients imapkit, imapkit-approve and imapkit-deny are registered by default, with loopback redirect URIs on any port. The ID token's email claim is the user name, so use address-style user names for OAuth tests. The provider is strict like the IMAP side: PKCE S256 for public clients, single-use codes, exact redirect URIs, no unknown scopes. Token faults, forced expiry and revocation are in the control API and the REST API. See OAuth 2.0 and OpenID Connect.
All RFC 3501 commands are supported. Some choices that the RFCs leave to the server:
LIST (SUBSCRIBED) keep listing the name (as \NonExistent in extended LIST) until UNSUBSCRIBE, and a mailbox created again under that name is subscribed. RENAME leaves the subscription with the old name (RFC 9051 section 6.3.6). A mailbox from the storage object is subscribed unless it has "subscribed": false, a new mailbox is not. SUBSCRIBE refuses names that are not mailboxes, UNSUBSCRIBE accepts any namea/b also creates a as a normal mailbox if it does not exist (RFC 3501 section 6.3.3, Dovecot creates a \Noselect level instead). An existing \Noselect level stays \Noselect\Noselect level that keeps nothing but the children, CREATE of that name makes a new mailbox with a new UIDVALIDITY"allowPermanentFlags": false STORE accepts exactly the flags PERMANENTFLAGS lists (permanentFlags and the flags its messages have or had) and ignores the others, APPEND and COPY leave them out (RFC 3501 section 7.1)<@route.example:a@b.c>, RFC 5322 section 4.4) goes to the at-domain-list field of the ENVELOPE address ((NIL "@route.example" "a" "b.c")), the mailbox name is the local part only (RFC 9051 section 7.5.2), like Dovecot sends itPlugins can be enabled when starting the server but can not be unloaded or loaded when the server is already running.
All plugins are self contained and not tied to core. If you do not enable a plugin, no trace of it is left
to the system. For example, if you do not enable CONDSTORE, messages do not have a MODSEQ value set.
Plugin names are case insensitive and capability spellings like LITERAL+ or AUTH=PLAIN are accepted too.
An unknown plugin name throws an error, and a plugin listed more than once is loaded only once.
RIGHTS=texk (SETACL, DELETEACL, GETACL, LISTRIGHTS and MYRIGHTS), and LIST-MYRIGHTS [RFC8440] when LIST-EXTENDED is loaded. See ACL belowappendLimit (octets) sets the limit for every mailbox and is advertised as APPENDLIMIT=<n>. A mailbox in the storage can set its own appendLimit (a number, or null for no limit), then the capability is advertised without a value and clients read the limits with STATUS (APPENDLIMIT). Larger messages in APPEND and REPLACE fail with NO [TOOBIG], synchronizing literals are refused before the client sends themBINARY[<part>]<<partial>>, BINARY.PEEK and BINARY.SIZE FETCH items that remove base64 and quoted-printable encodings (NO [UNKNOWN-CTE] for other encodings), and APPEND, MULTIAPPEND and REPLACE with literal8 messages (~{n}, ~{n+} with LITERAL+ or LITERAL-). Decoded data is sent as a literal8 only when it contains NUL. Binary parts of an appended message, and parts with NUL octets, are stored base64 encoded, so BODY[] stays valid IMAP4rev1/INBOX;UIDVALIDITY=1/;UID=2/;SECTION=1.MIME/;PARTIAL=0.100, other URLs and URLs that do not resolve fail with NO [BADURL ...]. A message over the literal size limit fails with NO [TOOBIG]. Plugins can refuse URLs of a mailbox through server.urlAccessChecksSEARCH MODSEQ search key and the CLOSED response codeUPDATE, CONTEXT and PARTIAL result options of SEARCH and UID SEARCH, and the CANCELUPDATE command. With UPDATE the session gets ADDTO and REMOVEFROM ESEARCH updates as messages start or stop matching, whether this or another session changed them (REMOVEFROM comes before the EXPUNGE response, ADDTO after EXISTS and FETCH). Updates end with CANCELUPDATE or when the mailbox is closed. Server option maxSearchContexts (default 10) limits the updating searches of a session, above it the server answers with NO [NOUPDATE "tag"]. CONTEXT is accepted as a hint and ignored. Message numbers in the search program are taken as they were when the search ran (RFC 5267 section 4.3)UPDATE, CONTEXT and PARTIAL for SORT and UID SORT, the updates carry context positions in sort order"special-use"SEARCH RETURN (MIN MAX ALL COUNT) and UID SEARCH RETURN (...) answer with an ESEARCH response. With CONDSTORE the response includes MODSEQ for a MODSEQ searchSORT RETURN (MIN MAX ALL COUNT) and UID SORT RETURN (...) answer with an ESEARCH response in sort order. With SEARCHRES, SAVE works for SORT as wellIMAP4rev2, UTF8=ACCEPT)$Forwarded, $MDNSent, $Junk, $NotJunk and $Phishing keywords also in mailboxes that do not allow new keywords. Every session starts as IMAP4rev1; after ENABLE IMAP4rev2 it follows RFC 9051: STATUS DELETED is allowed, SEARCH answers with ESEARCH, SELECT and EXAMINE send an untagged LIST response for the mailbox and * OK [CLOSED] when they close one, but no RECENT response, [UNSEEN] code or \Recent flag, mailbox names and quoted strings are UTF-8, SEARCH assumes UTF-8 when no CHARSET is given, a message with 8-bit headers can be appended, message/global parts are described and numbered like message/rfc822, and the items that RFC 9051 removed are BAD (see Strict by design). STARTTLS and LOGINDISABLED (RFC 9051 section 6.1.1) are not loaded, as they change how clients log in; load them when needed. Partial FETCH ranges and the LARGER and SMALLER search keys take 63-bit numbers (number64) after ENABLE, 32-bit ones before it (partial ranges up to 2^53 - 1, the largest exact JavaScript number). A server that advertises only IMAP4rev2, UTF-8 in response text, and OLDNAME are not implementedSUBSCRIBED, REMOTE (there are no remote mailboxes) and RECURSIVEMATCH, return options SUBSCRIBED and CHILDREN, multiple mailbox patterns and the CHILDINFO extended data item. \Noselect mailboxes are listed as \NonExistent in extended LIST responses. With SPECIAL-USE loaded, the SPECIAL-USE selection and return options [RFC6154] combine with the other options. The plain RFC 3501 LIST is not changedSTATUS return option of LIST. Loads LIST-EXTENDED as wellBAD [TOOBIG]. Can not be loaded together with LITERALPLUSMESSAGELIMIT=<n>, where the server option messageLimit sets n (default 1000, any positive number is accepted so that small test mailboxes can hit it). FETCH, STORE, SEARCH, MOVE, UID EXPUNGE and their UID variants only work on the n messages with the highest UIDs (UID EXPUNGE counts the \Deleted ones) and add [MESSAGELIMIT n uid] with the lowest processed UID to the tagged OK, or send it in an untagged NO when the tagged OK already has a response code (like HIGHESTMODSEQ or MODIFIED). SEARCH counts the searched messages, which its top level sequence set, UID, UIDAFTER and UIDBEFORE keys narrow down. COPY, APPEND (MULTIAPPEND), SORT and THREAD of more messages, and a FETCH PARTIAL range (PARTIAL plugin) of more messages, fail with NO [MESSAGELIMIT ...]. EXPUNGE, CLOSE and STATUS are not limited. Adds the UIDAFTER and UIDBEFORE search keys. Can not be loaded together with SAVELIMIT~{n}), and values with NUL are sent back as a literal8. Initial mailbox entries come from a metadata object on the mailbox in storage ("INBOX": { "metadata": { "/private/comment": "My comment" } }), server entries from the metadata option. Server options metadataMaxSize (largest value in octets, default 65536), metadataMaxEntries (entries per mailbox and for the server, default 100) and metadataPrivate: false (refuse /private entries with [METADATA NOPRIVATE]) let you test the client's error handling. /shared/admin on the server is read-only. Annotations move with RENAME (renaming INBOX copies them), DELETE removes them. After ENABLE METADATA (needs the ENABLE plugin), changes made by other sessions are announced with unsolicited METADATA responses. With SPECIAL-USE loaded, the read-only /private/specialuse entry shows the special-use attributes of a mailbox (RFC 6154 section 4)ESEARCH IN (mailboxes "a" subtree "b" subtree-one "c" personal subscribed inboxes selected) RETURN (...) criteria sends one ESEARCH response with UIDs and the TAG, MAILBOX and UIDVALIDITY correlators for every mailbox with matches. Mailboxes that do not exist or are \Noselect are skipped (with ACL also those without the r right, and without l unless named under mailboxes or as a subtree root), a mailbox named twice is searched once, and inboxes is INBOX. SAVE is only allowed when the selected mailbox is the only one searched, UPDATE (with CONTEXT=SEARCH) only applies to the selected mailbox"")NOTIFY SET [STATUS] (filter events) ... and NOTIFY NONE with the selected, selected-delayed, inboxes (same as personal), personal, subscribed, subtree and mailboxes filters and the MessageNew (with fetch attributes for the selected mailbox), MessageExpunge, FlagChange, MailboxName (LIST with OLDNAME for RENAME) and SubscriptionChange events, plus MailboxMetadataChange and ServerMetadataChange with METADATA. Events are sent as soon as they happen, also between commands, while a command runs they wait for its tagged response, and EXPUNGE (or VANISHED) waits longer with selected-delayed and during FETCH, STORE and SEARCH. For a new message in the selected mailbox an IMAP4rev1 session gets EXISTS, the requested FETCH and then RECENT. After the first NOTIFY a session only hears about the events it asked for, also for the selected mailbox; changes made by the session itself are not reported. Other mailboxes are reported with STATUS (UNSEEN when the \Seen count changed, HIGHESTMODSEQ when CONDSTORE is enabled), with ACL only mailboxes with the l and r rights, and granting or revoking l counts as MailboxName. Fetch attributes never set \Seen. server.notifyOverflow([connection]) sends * OK [NOTIFICATIONOVERFLOW] and turns NOTIFY off. AnnotationChange (no ANNOTATE support) is refused with NO [BADEVENT], the fetch attributes of the CONTEXT=SEARCH UPDATE option (RFC 5465 section 7) are not supported"testtoken", the authzid in the GS2 header (n,a=testuser,) is optional. A failed login gets the JSON error result as a continuation request (invalid_token or invalid_request), the client must answer it with AQ== (a single %x01)MAILBOXID for CREATE, SELECT, EXAMINE and STATUS, EMAILID and THREADID for FETCH and SEARCH. Ids are generated (F1, M1, T1, ...) unless the storage sets a MAILBOXID for a mailbox or an EMAILID / THREADID for a message. COPY, MOVE and RENAME INBOX keep the EMAILID and THREADID of a message. Messages are threaded by their Message-ID, In-Reply-To and References headers across all mailboxes, a message joins the thread of the nearest known parent when it is addedPARTIAL result option of SEARCH (RETURN (PARTIAL 1:100), RETURN (PARTIAL -1:-100) counts from the last result) and of SORT with ESORT, and the PARTIAL modifier of FETCH and UID FETCH (UID FETCH 1:* (FLAGS) (PARTIAL -1:-50)), which combines with CHANGEDSINCE. With PARTIAL loaded a command takes only one PARTIAL or ALL result option"preview" string instead. PREVIEW (LAZY) returns NIL until the preview of the message has been generated by a FETCH without LAZY, or comes from storageGETQUOTA, GETQUOTAROOT, SETQUOTA (QUOTASET), the STORAGE, MESSAGE and MAILBOX resources and the DELETED and DELETED-STORAGE STATUS items. INBOX and the personal namespaces share one quota root, other namespaces have none. Configure it with the quota server option, eg. { "root": "User quota", "STORAGE": 10240, "MESSAGE": 1000, "MAILBOX": 100, "soft": false } (STORAGE is in units of 1024 octets, a missing resource is not limited). APPEND, COPY and MOVE (from outside the quota root) fail with NO [OVERQUOTA] when they would go over a limit, and CREATE or RENAME INBOX when they would go over the MAILBOX limit. With "soft": true they succeed with an untagged NO [OVERQUOTA] warning instead. SETQUOTA changes the limits at runtimeENABLE QRESYNC: SELECT/EXAMINE with (QRESYNC (uidvalidity modseq [known-uids] [seq-match-data])) reports VANISHED (EARLIER) and the changed flags, UID FETCH ... (CHANGEDSINCE n VANISHED) works, and expunges (EXPUNGE, UID EXPUNGE, MOVE, other sessions, IDLE) are reported with VANISHED instead of EXPUNGE. Expunged UIDs are remembered with their mod-sequence; UIDs missing from the initial storage count as expunged before the server startedSAVELIMIT=<n> (server option messageLimit, default 1000): only COPY and APPEND (MULTIAPPEND) of more messages fail with NO [MESSAGELIMIT ...]. Can not be loaded together with MESSAGELIMITSAVEDATE FETCH item and the SAVEDBEFORE, SAVEDON, SAVEDSINCE and SAVEDATESUPPORTED SEARCH keys. APPEND, COPY and MOVE set the save date to the current time, messages in storage can set it with a SAVEDATE value (a date-time string or a Date) and get the the time the storage was loaded otherwise (the current time, or the now option). A mailbox with "SAVEDATE": false in storage does not support save dates: FETCH returns NIL and the SEARCH keys use the internal dateSEARCH RETURN (SAVE) stores the result and $ refers to it in FETCH, STORE, COPY, MOVE, UID EXPUNGE, SEARCH and their UID variants. $ must be used alone, not combined with numbers like 1,$SIZE status item (also with LIST-STATUS). The plugin file is status-sizeENABLE UIDONLY, FETCH, STORE, SEARCH, COPY, MOVE, SORT, THREAD and REPLACE, message numbers in the criteria of UID SEARCH, UID SORT, UID THREAD and the ESEARCH command (MULTISEARCH), and the QRESYNC message sequence match data are refused with BAD [UIDREQUIRED] (a synchronizing literal of such a command is refused before it is sent). Every FETCH response becomes a * <uid> UIDFETCH (...) response (the UID item is only included when UID FETCH asks for it), expunges are reported with VANISHED, and SELECT does not send [UNSEEN n]. EXISTS and RECENT are not changed. Load UIDPLUS for UID EXPUNGE and COPYUIDENABLE UTF8=ACCEPT mailbox names are UTF-8 in both directions (storage keeps modified UTF-7 names, so & is an ordinary character), strings that are valid UTF-8 are sent quoted, and SEARCH strings are UTF-8 without CHARSET. UTF8=ONLY, the obsolete APPEND ... UTF8 (...) data item of RFC 6855 and downgrading of 8-bit headers for clients that did not enable UTF-8 (RFC 9755 section 8) are not implementedX-GM-MSGID and X-GM-THRID work with FETCH and SEARCH (every message is its own thread unless the storage sets an X-GM-THRID value for it; with OBJECTID loaded, the messages of a THREADID share the X-GM-THRID of the first message of that thread, so both thread ids group the same messages). X-GM-LABELS works with FETCH, STORE (+, -, .SILENT) and SEARCH: system labels are atoms that start with \ (\Inbox for INBOX, the special-use attribute for special-use mailboxes), other labels are mailbox names, sent and read in the form the session uses for mailbox names (modified UTF-7, or UTF-8 after ENABLE UTF8=ACCEPT) and quoted when they are not atoms. In SEARCH a label that starts with \ is a system label. Setting a label does not change message behavior, for example the message does not get copied to another mailbox. X-GM-RAW supports a subset of the Gmail search syntax: words and "phrases" (TEXT), -term, OR, ( ), { }, from:, to:, cc:, bcc:, subject:, label:, in: (inbox, sent, drafts, trash, spam, anywhere or a label), is: (read, unread, starred, important), larger: and smaller: (with k or m), after: and before: (YYYY/MM/DD) and rfc822msgid:. Other Gmail operators (has:, older_than: ...) are answered with NO"testuser" as the user name and "testtoken" as the access token to log in.All users share the same mailbox tree. With the ACL plugin, the owner (server option aclOwner, "testuser" by default) has every right on every mailbox, and every other user only gets the rights that the ACL of a mailbox grants to their user name or to anyone, minus the negative rights of -username and -anyone (RFC 4314 section 2). ACLs come from the acl property of a mailbox in the storage, or from SETACL:
{
"INBOX": { "acl": { "otheruser": "lrs", "anyone": "l" } },
"": { "folders": { "Shared": { "acl": { "otheruser": "lrswikte", "-otheruser": "t" } } } }
}The rights of other users are enforced as RFC 4314 section 4 describes:
l. SELECT, EXAMINE and STATUS need r, SUBSCRIBE needs li, e, s, w and t, and PERMANENTFLAGS only lists the flags the user can changes for \Seen, t for \Deleted, w for the others) and answers NO [NOPERM] if it could change none of them; a FETCH without s does not set \Seeni on the target and keep only the flags the user has rights for. MOVE also needs t and e on the source (RFC 6851 section 4.2), and so does REPLACE (RFC 8508 section 4.1). APPEND and REPLACE are refused before the message literal is sent, a target the user can not see like a missing onee, CLOSE without e closes the mailbox without expungingk on the nearest existing parent (so other users can not create top level mailboxes), DELETE needs x, RENAME needs x on the mailbox and k on the new parenta, MYRIGHTS needs any of l, r, i, k, x, ar get no STATUS response and are listed with \Noselect (RFC 5819 section 2)l and any of r, s, w, i, p (RFC 5464 section 3.3), and unsolicited METADATA responses only go to sessions with these rightsr on the mailbox, and SETQUOTA needs a on every mailbox of the quota root (RFC 9208 section 6)Missing rights are answered with NO [NOPERM], or with the same error as for a mailbox that does not exist when the user does not have l either, so the existence of the mailbox is not disclosed (RFC 4314 section 6). The rights on the selected mailbox are taken when it is selected. A new mailbox inherits the ACL of its parent and DELETE removes the ACL. The obsolete c and d rights are accepted as kx and et and are added to ACL and MYRIGHTS responses (RFC 4314 section 2.1.1). The rights of the owner can not be changed.
ImapKit 5.0.0 has two breaking changes:
--smtpPort, the smtp option) needs the smtp-server package, it is an optional peer dependency now: npm install smtp-server.XTOYBIRD throws an error that points here.The XTOYBIRD commands map to the control API:
| XTOYBIRD command | Control API |
|---|---|
XTOYBIRD STORAGE | server.control.snapshot() |
XTOYBIRD SERVER | server.control.listMailboxes(), server.control.listUsers() |
XTOYBIRD CONNECTION | server.control.sessions() |
XTOYBIRD USERADD "user" "password" | server.control.addUser('user', { password }), or updateUser() for an existing user |
XTOYBIRD USERDEL "user" | server.control.deleteUser('user') |
XTOYBIRD SHUTDOWN | await server.control.shutdown(), stops accepting connections and waits for the last client |
[MODIFIED ...]* OK [CLOSED] when they close the selected mailbox# break out character ignores the referenceThe source is TypeScript in src/, npm run build compiles it into dist/esm (ES modules) and dist/cjs (CommonJS). Tests use the built-in Node.js test runner (TypeScript test files run through tsx), linting uses ESLint and the TypeScript compiler, and formatting uses Prettier.
npm install
npm test # lint, type check, build and all tests
npm run test:unit # tests only
npm run test:coverage # tests with coverage (Node.js 22.8 or newer)
npm run test:bun # tests under Bun
npm run test:deno # tests under Deno
node --import tsx --test test/fetch.test.ts # a single test file
npm run format # apply Prettier formattingcompare/ holds a development tool that replays the same IMAP commands against ImapKit and a Dovecot server running in Docker and shows where the responses differ (npm run dovecot:start, then npm run compare -- compare/scenarios/fetch.txt). See CLAUDE.md for details.
The storage option (or --storage=<path> for the command) describes the mailbox tree. The keys are namespaces.
storage.json:
{
"INBOX": {},
"INBOX.": {},
"user.": {
"type": "user"
},
"": {
"type": "shared"
}
}storage.json:
{
"INBOX": {},
"": {
"separator": "/",
"folders": {
"[Gmail]": {
"flags": ["\\Noselect"],
"folders": {
"All Mail": {
"special-use": "\\All"
},
"Drafts": {
"special-use": "\\Drafts"
},
"Important": {
"special-use": "\\Important"
},
"Sent Mail": {
"special-use": "\\Sent"
},
"Spam": {
"special-use": "\\Junk"
},
"Starred": {
"special-use": "\\Flagged"
},
"Trash": {
"special-use": "\\Trash"
}
}
}
}
}
}Creating your tests in Node.js is a piece of cake, you do not even need to run the imapkit command. Here is a sample test using the built-in Node.js test runner.
import { describe, it, beforeEach, afterEach } from 'node:test';
import imapkit from 'imapkit';
import myIMAPClient from '../my-imap-client.js';
describe('IMAP tests', () => {
let server;
// Executed before every test, creates a new blank IMAP server
// on a random free port
beforeEach(
() =>
new Promise(resolve => {
server = imapkit();
server.listen(0, resolve);
})
);
// Executed after every test, closes the IMAP server created for the test
afterEach(() => new Promise(resolve => server.close(resolve)));
// A new IMAP client is instantiated that tries to connect to the
// IMAP server. If the client is connected the test is considered as passed.
it('Connect to the server', (t, done) => {
const client = myIMAPClient.connect('localhost', server.address().port);
client.on('ready', () => {
client.disconnect();
done();
});
});
});server.control changes and inspects the server from your test, without an IMAP session. Every change reaches the connected sessions the way a change by another session would: a selected session gets EXISTS (and RECENT in IMAP4rev1) for a new message, EXPUNGE (or VANISHED after ENABLE QRESYNC) for a removed one, an unsolicited FETCH with the UID and the new flags (with MODSEQ after ENABLE CONDSTORE), and BYE when its mailbox is deleted. NOTIFY and CONTEXT=SEARCH sessions get their updates too. ACL does not apply to the control API, but every argument is checked.
const server = imapkit({ plugins: ['IDLE', 'CONDSTORE'] });
const port = await server.start(); // a free port, server.start(1143, '127.0.0.1') for a fixed one
const { uid } = server.control.addMessage('INBOX', { raw: 'Subject: hello\r\n\r\nHi!\r\n', flags: ['\\Seen'] });
server.control.setFlags('INBOX', [uid], ['\\Flagged'], 'add');
server.control.expungeMessages('INBOX', [uid]);
await server.stop();Mailboxes are addressed by their storage name (modified UTF-7, the name a client uses in LIST), messages by mailbox and UID. The methods return plain data and throw an ImapKitError (exported by the package) whose code is NONEXISTENT, ALREADYEXISTS, INVALID, or the RFC 5530 code of a failed mailbox operation (CANNOT, HASCHILDREN ...).
| Method | What it does |
|---|---|
snapshot() | The storage as JSON in the shape of the storage option, imapkit({ storage: server.control.snapshot() }) starts from the same state |
listMailboxes(), getMailbox(path) | Mailboxes with path, delimiter, flags, selectable, subscribed, messages, unseen, uidnext, uidvalidity, permanentFlags (and highestModseq with CONDSTORE) |
listMessages(path, { uids, raw }), getMessage(path, uid) | Messages with uid, flags, internaldate, size (and modseq with CONDSTORE), the source as a Buffer in raw |
sessions() | Connected sessions: session number, user, state, selected mailbox, readOnly, enabled, secure, compressed, remoteAddress |
addMessage(path, { raw, flags, internaldate }, { checks }) | Adds a message like a delivery, returns { uid, uidvalidity }. A string raw is encoded as UTF-8. checks: true refuses the message like APPEND would (QUOTA OVERQUOTA, APPENDLIMIT TOOBIG) |
setFlags(path, uids, flags, mode) | mode is set (default), add or remove |
expungeMessages(path, uids) | Removes messages |
copyMessages(path, uids, target), moveMessages(...) | Returns { uidvalidity, uids: [{ uid, targetUid }] } |
replaceMessage(path, uid, { raw, flags, internaldate }) | Adds the new message and expunges the old one. The content of a UID never changes (RFC 9051 section 2.3.1.1), so the new message gets a new UID |
createMailbox(path, { subscribed }), deleteMailbox(path), renameMailbox(path, newPath) | Like CREATE, DELETE and RENAME |
resetUidValidity(path, { uidvalidity, uids, offset, seed }) | Gives the mailbox a new, greater UIDVALIDITY. uids is keep (default), renumber (1 to n), shuffle (1 to n in a random order, repeatable with seed, so an old UID points to another message) or offset (every UID moves above the old UIDNEXT, plus offset, so old UIDs find nothing). A UID must not change during a session (RFC 9051 section 2.3.1.1), so sessions that have the mailbox selected get BYE. Returns { uidvalidity, uidnext, uids: [{ uid, newUid }] } |
subscribe(path), unsubscribe(path) | Return true if the subscription changed |
listUsers(), addUser(name, { password, xoauth2 }), updateUser(name, {...}), deleteUser(name) | xoauth2 is { accessToken, sessionTimeout }, sessionTimeout is deprecated and ignored (access tokens do not expire). Deleting a user disconnects its sessions, { disconnect: false } keeps them. No credentials in listUsers() |
disconnect(session or { user }, { text, reset }) | Disconnects sessions with an untagged BYE, or resets the TCP connection |
inject(session, data) | Writes bytes to a session as they are, e.g. * OK [ALERT] ... between commands |
reset() | Restores the mailboxes and users of the server options and disconnects every session with BYE, so a long running server can be reused between tests. Script rules stay, with their hits counts |
shutdown({ graceful }) | Stops accepting connections and resolves once the last client is gone, graceful: false closes the sessions |
Plugins add operations for their own data, they exist only when the plugin is loaded:
| Plugin | Methods |
|---|---|
| ACL | getAcl(path), setAcl(path, identifier, rights) (+rights adds, -rights removes, empty rights remove the identifier), deleteAcl(path, identifier), ACLs are { identifier: rights } |
| QUOTA | getQuota() ({ root, limits, usage }, STORAGE in units of 1024 octets), setQuota({ STORAGE, MESSAGE, MAILBOX }) replaces the limits |
| METADATA, METADATA-SERVER | getMetadata(path), setMetadata(path, { entry: value }) ("" is the server, null removes an entry, also the read-only /shared/admin). Sessions after ENABLE METADATA get unsolicited METADATA |
| SPECIAL-USE | setSpecialUse(path, ['\\Sent']) (RFC 6154 attributes and \Important), getMailbox() has specialUse |
| OBJECTID | getMailbox() has mailboxId, getMessage() and listMessages() have emailId and threadId |
A plugin of your own adds operations with server.control.register(name, fn, routes), the routes go to the REST API.
server.start(port, host) resolves