imap API reference
An IMAP4rev1 client (RFC 3501): tagged commands and untagged "*" responses over the net system library, with plaintext / implicit TLS / STARTTLS and auth by LOGIN, XOAUTH2, CRAM-MD5, or SCRAM-SHA-1 / SCRAM-SHA-256. A practical subset covering both reading and basic folder management, not the full protocol: SELECT a folder, SEARCH it (filtered), FETCH whole messages or named headers, and manage messages - STORE flags, COPY, CREATE a folder, mark + EXPUNGE (so, delete and move). It is not read-only. Retrieved messages come back as strings for the mime module to parse. Uses net, so it needs the default jennifer binary. A session is stateful: connect, selectFolder, search / fetch / fetchHeaders, optional addFlags / expunge, logout. A "NO" / "BAD" completion throws a catchable imap.ImapError (kind "imap") with the status, the RFC 5530 responseCode (AUTHENTICATIONFAILED, TRYCREATE, OVERQUOTA, ...) and the server's text; so does a reply the module cannot read (a FETCH that names no such UID, a SELECT without its EXISTS count, a malformed LIST / STATUS / SEARCH line). A peer that closes mid-dialogue is kind "closed". One fixed command tag is used, which is safe for this synchronous client (one command in flight at a time). Message literals ({N}) are framed over bytes by their byte count, so a multi-byte UTF-8 body is read byte-exact; fetchBytes returns any body (8-bit charsets included) as raw bytes. LOGIN / XOAUTH2 credentials are refused over transport.Security.None unless allowInsecureAuth is set.
Import with import "imap.j" as imap;. See the imap guide for prose and examples.
Contents
| Name | What it is |
|---|---|
addFlags | Add IMAP flags / keywords to a message (UID STORE +FLAGS.SILENT). |
append | Upload message (a full RFC 5322 message - headers, a blank line, then the body, e.g. |
appendWith | Like append, but sets initial flags on the stored message (APPEND with a flag list) - e.g. |
connect | Open a session: greeting, optional STARTTLS, then LOGIN (or the auth mechanism). |
copy | Copy a message (by UID) into another folder (UID COPY). |
createFolder | Create a folder (CREATE). |
criteria | An empty Criteria (matches all messages). |
done | Leave IDLE: send DONE, drain any pending pushes, and read the tagged completion of the IDLE command, re... |
expunge | Permanently remove every message flagged "\Deleted" in the selected folder (EXPUNGE). |
fetch | Retrieve a message (its full body) as a raw string for mime.parse, addressed by its stable UID (... |
fetchAll | Connect, select folder, retrieve every message, and log out. |
fetchBytes | Retrieve a message (its full body) byte-exact, whatever its charset or transfer encoding (`UID FETCH ... |
fetchHeaders | Retrieve only the named header fields of a message (space-separated, e.g. |
fetchMessage | Fetch a message by UID and parse it into a mime.Part tree, ready for mime.attachments /... |
fetchPartial | Retrieve a byte range of a message's body (`UID FETCH ... |
fetchPartialBytes | Like fetchPartial, but returns the byte range as raw bytes, so chunks can be joined byte-exact whatever t... |
flags | Return the flags currently set on a message (by UID) as a space-separated string (e.g. |
folders | List the folders matching pattern (the IMAP LIST "" pattern). |
idle | Enter IDLE (RFC 2177): send IDLE and wait for the server's "+ idling" continuation, leaving the session i... |
logout | End the session and close the connection. |
move | Move a message (by UID) into another folder in one atomic step (UID MOVE, RFC 6851) - the server copies t... |
pollNotification | Like receiveNotification, but wait at most timeoutMs milliseconds (armed with net.setReadDeadline): r... |
receiveNotification | Block until the next server push arrives while idling and return it as a typed Notification ("exists" new... |
removeFlags | Remove IMAP flags / keywords from a message (UID STORE -FLAGS.SILENT), the inverse of addFlags. |
search | Return the UIDs of the messages in the selected folder matching criteria (UID SEARCH). |
selectFolder | Select a folder (e.g. |
status | Query a folder's counts without selecting it (STATUS) - message / unseen / recent totals plus UIDNEXT / U... |
supportsIdle | Report whether the server advertises the IDLE extension (RFC 2177) in its CAPABILITY reply. |
Criteria | struct: A message-search filter. |
Folder | struct: One folder as reported by list. |
ImapError | struct: A failed IMAP operation. |
Notification | struct: One server-pushed mailbox change delivered during IDLE (RFC 2177). |
Options | struct: The parameters for opening an IMAP session. |
Session | struct: An open IMAP session. |
Status | struct: Folder status counts, as reported by status. |
Functions
addFlags
imap.addFlags(session as Session, uid as int, flags as string)Add IMAP flags / keywords to a message (UID STORE +FLAGS.SILENT). Use a keyword like "$cl_1" to colour the message in Thunderbird, or the system flag "\Deleted" to mark it for expunge. The folder is selected read-write by selectFolder, so the store is permitted.
session- the open session
uid- the message UID
flags- the space-separated flags, e.g. "$cl_1" or "\Deleted"
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap")
append
imap.append(session as Session, folder as string, message as string)Upload message (a full RFC 5322 message - headers, a blank line, then the body, e.g. built with the mime module) into folder (APPEND). The folder must already exist. Use this to save a copy to "Sent" after sending, or to store a message a client composed. The message is sent as a byte-counted literal, so any 8-bit / multi-byte content is uploaded exactly.
session- the open session
folder- the destination folder name
message- the full RFC 5322 message
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap"), e.g. a missing folder
appendWith
imap.appendWith(
session as Session,
folder as string,
flags as string,
message as string)Like append, but sets initial flags on the stored message (APPEND with a flag list) - e.g. "\\Seen" for a copy to Sent (already read) or "\\Draft" for a saved draft. flags is a space-separated flag string, as addFlags.
session- the open session
folder- the destination folder name
flags- the space-separated initial flags, e.g. "\Seen"
message- the full RFC 5322 message
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap")
connect
imap.connect(opts as Options)Open a session: greeting, optional STARTTLS, then LOGIN (or the auth mechanism). Over transport.Security.None the cleartext mechanisms (LOGIN, XOAUTH2) are refused unless allowInsecureAuth is set.
opts- the connection and auth parameters
- Returns
Session - the open session
- Throws
ImapError - on a bad greeting, a "NO" / "BAD" login completion, LOGIN / XOAUTH2 over an unencrypted connection without
allowInsecureAuth, bytes the server sent after its STARTTLS reply, or a SCRAM tagged OK that skips the server-final (its signature was then never verified; kind "imap")
copy
imap.copy(session as Session, uid as int, folder as string)Copy a message (by UID) into another folder (UID COPY). The source copy stays until it is deleted, so the standard "move" is copy + addFlags(..., "\Deleted") + expunge - or the atomic move below. The destination folder must already exist - COPY to a missing one is a "NO [TRYCREATE]" error.
session- the open session
uid- the message UID
folder- the destination folder name
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap")
createFolder
imap.createFolder(session as Session, folder as string)Create a folder (CREATE). A server answers "NO" if it already exists (often with an "[ALREADYEXISTS]" response code), so wrap this in try / catch for a create-if-missing.
session- the open session
folder- the folder name to create
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap"), including when the folder already exists
criteria
imap.criteria()An empty Criteria (matches all messages). Set the fields you want to filter on, then pass it to search.
- Returns
Criteria - a zero-value criteria
done
imap.done(session as Session)Leave IDLE: send DONE, drain any pending pushes, and read the tagged completion of the IDLE command, returning the session to command mode so ordinary calls (fetch, search, ...) work again. Pair every idle with a done.
session- the idling session
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap")
expunge
imap.expunge(session as Session)Permanently remove every message flagged "\Deleted" in the selected folder (EXPUNGE). Sequence numbers shift as messages are removed, so mark all the target messages with addFlags(..., "\\Deleted") first and call this once.
session- the open session
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap")
fetch
imap.fetch(session as Session, uid as int)Retrieve a message (its full body) as a raw string for mime.parse, addressed by its stable UID (UID FETCH ... BODY.PEEK[]). Get a UID from search. A message that is not valid UTF-8 (an 8-bit body in a legacy charset) throws; read it with fetchBytes.
session- the open session
uid- the message UID
- Returns
string - the raw message body
- Throws
ImapError - on a "NO" / "BAD" completion, no message with that UID, or a body that is not valid UTF-8 (kind "imap")
fetchAll
imap.fetchAll(opts as Options, folder as string)Connect, select folder, retrieve every message, and log out.
opts- the connection and auth parameters
folder- the folder name
- Returns
list of string - the raw body of every message
- Throws
ImapError - on a bad greeting or a "NO" / "BAD" completion (kind "imap")
fetchBytes
imap.fetchBytes(session as Session, uid as int)Retrieve a message (its full body) byte-exact, whatever its charset or transfer encoding (UID FETCH ... BODY.PEEK[]).
session- the open session
uid- the message UID
- Returns
bytes - the raw message
- Throws
ImapError - on a "NO" / "BAD" completion or no message with that UID (kind "imap")
fetchHeaders
imap.fetchHeaders(session as Session, uid as int, fields as string)Retrieve only the named header fields of a message (space-separated, e.g. "SUBJECT DATE") as a raw header block for mime.parse - far cheaper than fetching the whole body when you only need a few headers. Addressed by UID.
session- the open session
uid- the message UID
fields- the space-separated header names, e.g. "SUBJECT DATE"
- Returns
string - the raw header block (the fields plus the terminating blank line)
- Throws
ImapError - on a "NO" / "BAD" completion, no message with that UID, or headers that are not valid UTF-8 (kind "imap")
fetchMessage
imap.fetchMessage(session as Session, uid as int)Fetch a message by UID and parse it into a mime.Part tree, ready for mime.attachments / mime.textBodies / mime.data. Convenience for the common mime.parse(imap.fetch(...)) pattern; import mime too to walk the result.
session- the open session
uid- the message UID
- Returns
mime.Part - the parsed message tree
- Throws
ImapError - as
fetch(kind "imap")
fetchPartial
imap.fetchPartial(
session as Session,
uid as int,
offset as int,
length as int)Retrieve a byte range of a message's body (UID FETCH ... BODY.PEEK[]<offset.length>), so a large message can be pulled in bounded chunks instead of one huge literal. offset is the 0-based start, length the number of octets (the server returns fewer at end-of-body). Both must be >= 0. A range that is not valid UTF-8 - an 8-bit body, or a cut through a multi-byte character - throws; read ranges with fetchPartialBytes.
session- the open session
uid- the message UID
offset- the 0-based byte offset into the body
length- the number of octets to retrieve
- Returns
string - the requested byte range of the body
- Throws
ImapError - kind "imap" on a bad range, a "NO" / "BAD" completion, no message with that UID, or a range that is not valid UTF-8
fetchPartialBytes
imap.fetchPartialBytes(
session as Session,
uid as int,
offset as int,
length as int)Like fetchPartial, but returns the byte range as raw bytes, so chunks can be joined byte-exact whatever they cut through.
session- the open session
uid- the message UID
offset- the 0-based byte offset into the body
length- the number of octets to retrieve
- Returns
bytes - the requested byte range of the body
- Throws
ImapError - kind "imap" on a bad range, a "NO" / "BAD" completion, or no message with that UID
flags
imap.flags(session as Session, uid as int)Return the flags currently set on a message (by UID) as a space-separated string (e.g. "\Seen $cl_1"), or "" when none. Useful to confirm a STORE actually persisted: a server that does not allow a custom keyword answers OK but drops it, so the keyword will be absent here. Only the FETCH response for this UID counts, not an unsolicited one for another message.
session- the open session
uid- the message UID
- Returns
string - the flags, space-separated (no surrounding parentheses)
- Throws
ImapError - on a "NO" / "BAD" completion or no message with that UID (kind "imap")
folders
imap.folders(session as Session, pattern as string)List the folders matching pattern (the IMAP LIST "" pattern). Use "*" for every folder at any depth, "%" for the top level only, or scope to a subtree with a prefix (all of Archive is the pattern Archive/ then *). The reference is empty, so put any prefix in the pattern. (Named folders, not list, since list is a reserved type keyword.)
session- the open session
pattern- the folder pattern (
*= any depth,%= one level) - Returns
list of Folder - the matching folders (name, delimiter, flags)
- Throws
ImapError - on a "NO" / "BAD" completion or a malformed LIST line (kind "imap")
idle
imap.idle(session as Session)Enter IDLE (RFC 2177): send IDLE and wait for the server's "+ idling" continuation, leaving the session in the idling state so the server pushes mailbox changes (call supportsIdle first - a server that lacks the extension answers with a tagged "NO"/"BAD", surfaced here as an Error). Follow with receiveNotification / pollNotification to read pushes, then done to return to command mode. A server drops an idle session after about 29 minutes, so a long-lived client must periodically done and idle again.
session- the open session
- Throws
ImapError - kind "imap" when the server does not enter IDLE (e.g. a tagged "NO"/"BAD")
logout
imap.logout(session as Session)End the session and close the connection.
session- the open session
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap")
move
imap.move(session as Session, uid as int, folder as string)Move a message (by UID) into another folder in one atomic step (UID MOVE, RFC 6851) - the server copies then removes and expunges the source, so unlike the copy + \\Deleted + expunge dance there is no window with a duplicate and no manual expunge. The destination folder must already exist. MOVE is widely but not universally supported; a server lacking it answers "BAD", so fall back to copy + addFlags(..., "\\Deleted") + expunge when catching that.
session- the open session
uid- the message UID
folder- the destination folder name
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap"), including an unsupported MOVE
pollNotification
imap.pollNotification(session as Session, timeoutMs as int)Like receiveNotification, but wait at most timeoutMs milliseconds (armed with net.setReadDeadline): return the next push if one arrives in time, else the empty sentinel (kind == "") so a poll loop can do other work between checks. Requires an idle first.
session- the idling session
timeoutMs- the maximum time to wait, in milliseconds
- Returns
Notification - the next push, or the empty sentinel on a timeout
- Throws
Error - kind "closed" when the peer closes the connection; a read failure other than the timeout is passed on
receiveNotification
imap.receiveNotification(session as Session)Block until the next server push arrives while idling and return it as a typed Notification ("exists" new-mail / "expunge" / "recent"). Returns the empty sentinel (kind == "") only if the server ends IDLE with its tagged completion. No callbacks - wrap this in a loop, and in a spawn to run it beside other work. Requires an idle first.
session- the idling session
- Returns
Notification - the next push, or the empty sentinel when IDLE ends
- Throws
Error - kind "closed" when the peer closes the connection; a read failure is passed on
removeFlags
imap.removeFlags(session as Session, uid as int, flags as string)Remove IMAP flags / keywords from a message (UID STORE -FLAGS.SILENT), the inverse of addFlags. Removing a flag that is not set is a harmless no-op, e.g. removeFlags(session, uid, "$cl_1") clears that tag, "\Deleted" un-marks a pending delete.
session- the open session
uid- the message UID
flags- the space-separated flags to clear, e.g. "$cl_1"
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap")
search
imap.search(session as Session, criteria as Criteria)Return the UIDs of the messages in the selected folder matching criteria (UID SEARCH). A UID is stable across an expunge - it keeps addressing the same message after others are removed - so the returned ids are the correct input to every other verb here and the basis for "fetch only what is new since last run". The server-side fields become one round-trip (no bodies); if any client-side condition is set - a subjectRegex / fromRegex, hasAttachments, or a since / before carrying a time-of-day - the candidates are then refined by fetching just their headers / structure / INTERNALDATE. An empty imap.criteria() returns every message (UID SEARCH ALL).
session- the open session
criteria- the filter (build with
imap.criteria()+ fields) - Returns
list of int - the matching message UIDs
- Throws
ImapError - kind "imap" on a "NO" / "BAD" completion, an inverted date range (
sinceafterbefore), or a control character in a substring field
selectFolder
imap.selectFolder(session as Session, name as string)Select a folder (e.g. "INBOX") and return its message count.
session- the open session
name- the folder name
- Returns
int - the number of messages in the folder
- Throws
ImapError - on a "NO" / "BAD" completion or a reply without its EXISTS count (kind "imap")
status
imap.status(session as Session, folder as string)Query a folder's counts without selecting it (STATUS) - message / unseen / recent totals plus UIDNEXT / UIDVALIDITY. Handy for a folder badge or a "new mail?" poll on a folder other than the selected one.
session- the open session
folder- the folder name
- Returns
Status - the folder counts
- Throws
ImapError - on a "NO" / "BAD" completion or a missing / malformed STATUS line (kind "imap")
supportsIdle
imap.supportsIdle(session as Session)Report whether the server advertises the IDLE extension (RFC 2177) in its CAPABILITY reply. Call before idle: a server without IDLE answers the IDLE command with a tagged "NO"/"BAD", which idle surfaces as an Error.
session- the open session
- Returns
bool - true when IDLE is advertised
- Throws
ImapError - on a "NO" / "BAD" completion (kind "imap")
Structs
Criteria
A message-search filter. Every field is optional; a zero-value Criteria (from imap.criteria()) matches all messages, so search($s, imap.criteria()) is the old SEARCH ALL. Fields split into two groups by where they run:
Server-side (mapped straight to one IMAP SEARCH, one round-trip, no bodies downloaded; all conditions are ANDed): subject / from / to / text are case-insensitive substring matches (text covers headers + body); since / before are an inclusive-since / exclusive-before range as time.Time values (a zero-value time - the default - ignores the bound). IMAP SEARCH filters by calendar day, so a bound at midnight is a pure server-side search; a bound that carries a time-of-day is additionally refined to the exact instant client-side (against each candidate's INTERNALDATE, the arrival clock SEARCH itself uses), so sub-day ranges just work. seen / unseen / flagged / answered filter on flags; largerThan / smallerThan filter on size in bytes.
Client-side (applied only to the messages the server-side search returns, by fetching just their headers or structure - never full bodies): subjectRegex / fromRegex are RE2 patterns matched against the decoded Subject / From header; hasAttachments keeps only messages whose BODYSTRUCTURE shows an attachment (a heuristic - it looks for an attachment content-disposition, without downloading the body).
def struct Criteria {
subject as string,
from as string,
to as string,
text as string,
since as time.Time,
before as time.Time,
seen as bool,
unseen as bool,
flagged as bool,
answered as bool,
largerThan as int,
smallerThan as int,
subjectRegex as string,
fromRegex as string,
hasAttachments as bool
};subjectSUBJECTsubstring ("" ignores it)fromFROMsubstringtoTOsubstringtextTEXTsubstring (whole message)since- only messages on/after this instant (a zero time ignores it)
before- only messages strictly before this instant (a zero time ignores it)
seen- only
\Seenmessages unseen- only unseen messages
flagged- only
\Flaggedmessages answered- only
\Answeredmessages largerThanLARGERthan n bytes (0 ignores it)smallerThanSMALLERthan n bytes (0 ignores it)subjectRegex- RE2 pattern on the
Subjectheader (client-side, "" ignores it) fromRegex- RE2 pattern on the
Fromheader (client-side) hasAttachments- keep only messages with an attachment (client-side heuristic)
Folder
One folder as reported by list.
def struct Folder {
name as string,
delimiter as string,
flags as list of string
};name- the folder name (ASCII, or modified-UTF-7 for non-ASCII names)
delimiter- the hierarchy separator (e.g. "/" or "."), "" for a flat namespace
flags- the folder attribute flags (e.g. "\HasChildren", "\Noselect")
ImapError
A failed IMAP operation. Every error of kind "imap" is one, so its fields are safe to read once the kind matches.
def struct ImapError {
kind as string,
message as string,
status as string,
responseCode as string,
text as string
};kind- always
"imap" message- the server's completion line, or what went wrong
status"NO"(the command failed) or"BAD"(the server did not accept it) for a tagged completion; "" for another failureresponseCode- the bracketed response code's name (RFC 5530:
AUTHENTICATIONFAILED,TRYCREATE,NONEXISTENT,OVERQUOTA,UNAVAILABLE, ...), "" when none text- the server's human-readable text after the code, "" for another failure
Notification
One server-pushed mailbox change delivered during IDLE (RFC 2177). A kind of "" is the idle-gap sentinel (imap.pollNotification timed out, or the server ended IDLE) carrying no push.
def struct Notification {
kind as string,
number as int
};kind- the push kind: "exists" (new message count), "expunge" (a message was removed), "recent" (recent-count change), or "" (no push / idle gap)
number- the sequence number or count the push carried (0 for the sentinel)
Options
The parameters for opening an IMAP session.
def struct Options {
host as string,
port as int,
security as transport.Security,
user as string,
pass as string,
auth as string,
allowInsecureAuth as bool
};host- the server hostname
port- the server port (e.g. 993 for implicit TLS)
security- the transport:
transport.Security.None(plaintext) /.Tls(implicit) /.Starttls user- the login username
pass- the login password, or the OAuth2 access token when auth is "xoauth2"
auth- the auth mechanism: "" (default - LOGIN), "auto" (probe CAPABILITY and pick the strongest mechanism, falling back to LOGIN), "xoauth2", "cram" (CRAM-MD5), "scram-sha-1", or "scram-sha-256"
allowInsecureAuth- send LOGIN / XOAUTH2 credentials over an unencrypted (
transport.Security.None) connection (default false - they are refused; CRAM-MD5 and SCRAM need no opt-in)
Session
An open IMAP session.
def struct Session {
conn as net.Conn,
rx as channel of bytes
};conn- the underlying connection
rx- the bytes read past the last line or response, shared by every copy of the session (internal)
Status
Folder status counts, as reported by status. A field the server did not return stays 0.
def struct Status {
messages as int,
recent as int,
unseen as int,
uidnext as int,
uidvalidity as int
};messages- total messages (MESSAGES)
recent- messages with the
\Recentflag (RECENT) unseen- messages without
\Seen(UNSEEN) uidnext- the UID that will be assigned to the next message (UIDNEXT)
uidvalidity- the folder's UID-validity value (UIDVALIDITY)