Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

node-imap

> 编程语言
Open source

An IMAP client module for node.js.

2.2K stars0 likes1 views
WebsiteGitHub

About

An IMAP client module for node.js.

Description

node-imap is an IMAP client module for node.js.

This module does not perform any magic such as auto-decoding of messages/attachments or parsing of email addresses (node-imap leaves all mail header values as-is).

An upgrade guide from node-imap v0.7.x to v0.8.x can be found here.

Requirements

  • node.js -- v10.0.0 or newer

  • An IMAP server to connect to -- tested with gmail

Installation

bash
npm install imap

Examples

  • Fetch the 'date', 'from', 'to', 'subject' message headers and the message structure of the first 3 messages in the Inbox:
…
  • Retrieve the 'from' header and buffer the entire body of the newest message:
…
  • Save raw unread emails since May 20, 2010 to files:
…

API

Data types

  • MessageSource can be a single message identifier, a message identifier range (e.g. '2504:2507' or '*' or '2504:*'), an array of message identifiers, or an array of message identifier ranges.

  • Box is an object representing the currently open mailbox, and has the following properties:

    • name - string - The name of this mailbox.
    • readOnly - boolean - True if this mailbox was opened in read-only mode. (Only available with openBox() calls)
    • newKeywords - boolean - True if new keywords can be added to messages in this mailbox.
    • uidvalidity - integer - A 32-bit number that can be used to determine if UIDs in this mailbox have changed since the last time this mailbox was opened.
    • uidnext - integer - The uid that will be assigned to the next message that arrives at this mailbox.
    • flags - array - A list of system-defined flags applicable for this mailbox. Flags in this list but not in permFlags may be stored for the current session only. Additional server implementation-specific flags may also be available.
    • permFlags - array - A list of flags that can be permanently added/removed to/from messages in this mailbox.
    • persistentUIDs - boolean - Whether or not this mailbox has persistent UIDs. This should almost always be true for modern mailboxes and should only be false for legacy mail stores where supporting persistent UIDs was not technically feasible.
    • messages - object - Contains various message counts for this mailbox:
      • total - integer - Total number of messages in this mailbox.
      • new - integer - Number of messages in this mailbox having the Recent flag (this IMAP session is the first to see these messages).
      • unseen - integer - (Only available with status() calls) Number of messages in this mailbox not having the Seen flag (marked as not having been read).
  • ImapMessage is an object representing an email message. It consists of:

    • Events:
      • body(< ReadableStream >stream, < object >info) - Emitted for each requested body. Example info properties:
        • which - string - The specifier for this body (e.g. 'TEXT', 'HEADER.FIELDS (TO FROM SUBJECT)', etc).
        • size - integer - The size of this body in bytes.
      • attributes(< object >attrs) - Emitted when all message attributes have been collected. Example attrs properties:
        • uid - integer - A 32-bit ID that uniquely identifies this message within its mailbox.
        • flags - array - A list of flags currently set on this message.
        • date - Date - The internal server date for the message.
        • struct - array - The message's body structure (only set if requested with fetch()). See below for an explanation of the format of this property.
        • size - integer - The RFC822 message size (only set if requested with fetch()).
      • end() - Emitted when all attributes and bodies have been parsed.
  • ImapFetch is an object representing a fetch() request. It consists of:

    • Events:
      • message(< ImapMessage >msg, < integer >seqno) - Emitted for each message resulting from a fetch request. seqno is the message's sequence number.
      • error(< Error >err) - Emitted when an error occurred.
      • end() - Emitted when all messages have been parsed.

A message structure with multiple parts might look something like the following:

…

The above structure describes a message having both an attachment and two forms of the message body (plain text and HTML). Each message part is identified by a partID which is used when you want to fetch the content of that part (see fetch()).

The structure of a message with only one part will simply look something like this:

javascript
[ { partID: '1',
    type: 'text',
    subtype: 'plain',
    params: { charset: 'ISO-8859-1' },
    id: null,
    description: null,
    encoding: '7BIT',
    size: 935,
    lines: 46,
    md5: null,
    disposition: null,
    language: null
  }
]

Therefore, an easy way to check for a multipart message is to check if the structure length is >1.

Lastly, here are the system flags defined by RFC3501 that may be added/removed:

  • \Seen - Message has been read
  • \Answered - Message has been answered
  • \Flagged - Message is "flagged" for urgent/special attention
  • \Deleted - Message is marked for removal
  • \Draft - Message has not completed composition (marked as a draft).

It should be noted however that the IMAP server can limit which flags can be permanently modified for any given message. If in doubt, check the mailbox's permFlags first. Additional custom flags may be provided by the server. If available, these will also be listed in the mailbox's permFlags.

require('imap') returns one object: Connection.

Connection Events

  • ready() - Emitted when a connection to the server has been made and authentication was successful.

  • alert(< string >message) - Emitted when the server issues an alert (e.g. "the server is going down for maintenance").

  • mail(< integer >numNewMsgs) - Emitted when new mail arrives in the currently open mailbox.

  • expunge(< integer >seqno) - Emitted when a message was expunged externally. seqno is the sequence number (instead of the unique UID) of the message that was expunged. If you are caching sequence numbers, all sequence numbers higher than this value MUST be decremented by 1 in order to stay synchronized with the server and to keep correct continuity.

  • uidvalidity(< integer >uidvalidity) - Emitted if the UID validity value for the currently open mailbox changes during the current session.

  • update(< integer >seqno, < object >info) - Emitted when message metadata (e.g. flags) changes externally.

  • error(< Error >err) - Emitted when an error occurs. The 'source' property will be set to indicate where the error originated from.

  • close(< boolean >hadError) - Emitted when the connection has completely closed.

  • end() - Emitted when the connection has ended.

Connection Properties

  • state - string - The current state of the connection (e.g. 'disconnected', 'connected', 'authenticated').

  • delimiter - string - The (top-level) mailbox hierarchy delimiter. If the server does not support mailbox hierarchies and only a flat list, this value will be falsey.

  • namespaces - object - Contains information about each namespace type (if supported by the server) with the following properties:

    • personal - array - Mailboxes that belong to the logged in user.
    • other - array - Mailboxes that belong to other users that the logged in user has access to.
    • shared - array - Mailboxes that are accessible by any logged in user.

    There should always be at least one entry (although the IMAP spec allows for more, it doesn't seem to be very common) in the personal namespace list, with a blank namespace prefix. Each property's array contains objects of the following format (with example values):

…

Connection Static Methods

  • parseHeader(< string >rawHeader[, < boolean >disableAutoDecode]) - object - Parses a raw header and returns an object keyed on header fields and the values are Arrays of header field values. Set disableAutoDecode to true to disable automatic decoding of MIME encoded-words that may exist in header field values.

Connection Instance Methods

Note: Message UID ranges are not guaranteed to be contiguous.

  • (constructor)([< object >config]) - Connection - Creates and returns a new instance of Connection using the specified configuration object. Valid config properties are:

    • user - string - Username for plain-text authentication.
    • password - string - Password for plain-text authentication.
    • xoauth - string - Base64-encoded OAuth token for OAuth authentication for servers that support it (See Andris Reinman's xoauth.js module to help generate this string).
    • xoauth2 - string - Base64-encoded OAuth2 token for The SASL XOAUTH2 Mechanism for servers that support it (See Andris Reinman's xoauth2 module to help generate this string).
    • host - string - Hostname or IP address of the IMAP server. Default: "localhost"
    • port - integer - Port number of the IMAP server. Default: 143
    • tls - boolean - Perform implicit TLS connection? Default: false
    • tlsOptions - object - Options object to pass to tls.connect() Default: (none)
    • autotls - string - Set to 'always' to always attempt connection upgrades via STARTTLS, 'required' only if upgrading is required, or 'never' to never attempt upgrading. Default: 'never'
    • connTimeout - integer - Number of milliseconds to wait for a connection to be established. Default: 10000
    • authTimeout - integer - Number of milliseconds to wait to be authenticated after a connection has been established. Default: 5000
    • socketTimeout - integer - The timeout set for the socket created when communicating with the IMAP server. If not set, the socket will not have a timeout. Default: 0
    • keepalive - mixed - Configures the keepalive mechanism. Set to true to enable keepalive with defaults or set to object to enable and configure keepalive behavior: Default: true
      • interval - integer - This is the interval (in milliseconds) at which NOOPs are sent and the interval at which idleInterval is checked. Default: 10000
      • idleInterval - integer - This is the interval (in milliseconds) at which an IDLE command (for servers that support IDLE) is re-sent. Default: 300000 (5 mins)
      • forceNoop - boolean - Set to true to force use of NOOP keepalive on servers also support IDLE. Default: false
    • debug - function - If set, the function will be called with one argument, a string containing some debug info Default: (no debug output)
  • connect() - (void) - Attempts to connect and authenticate with the IMAP server.

  • end() - (void) - Closes the connection to the server after all requests in the queue have been sent.

  • destroy() - (void) - Immediately destroys the connection to the server.

  • openBox(< string >mailboxName[, < boolean >openReadOnly=false[, < object >modifiers]], < function >callback) - (void) - Opens a specific mailbox that exists on the server. mailboxName should include any necessary prefi

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言