santoku-imap
View on LuaRocksIMAP4rev1 client over an injected stream driver, with modules for headers, message text, threads and drafts
santoku-imap is an IMAP4rev1 client for the subset of commands a mail application issues. The core takes an injected stream driver, so the same client runs over LuaSocket, node tls in a wasm build, and ngx cosockets under OpenResty. Companion modules parse headers, find and clean message text, thread messages and build drafts.
Details
- The commands are LOGIN, SELECT and EXAMINE, UID SEARCH, UID FETCH, UID STORE, EXPUNGE, APPEND, and LIST with SPECIAL-USE detection.
- UID FETCH includes Gmail's X-GM-THRID and X-GM-MSGID, header fields, partial body ranges and BODYSTRUCTURE.
- The core owns the protocol and nothing else.
- headers parses header blocks and does RFC 2047 decoding.
- bodystructure locates the text part without a download of the message.
- mime turns a fetched body into plain paragraphs, and builds a draft.
- body cuts reply chains and signatures out of that text, and splits forwards.
- thread assembles a forest from References, with an X-GM-THRID fallback.
- Everything here needs a socket and a mailbox, so the examples are shown for reading.
- The examples run in order: connect, the command set, the driver contract, what a fetch returns, headers, bodystructure, message text, reply and forward cleanup, threads, and a draft append.
A client from a driver
Requiring santoku.imap gives a function of a stream driver. Apply it to a driver, and it returns a library whose connect(opts, done) dials the server and calls done(ok, client) once the greeting has arrived.
local imap = require("santoku.imap")(require("santoku.socket.stream"))
imap.connect({
host = "imap.gmail.com",
port = 993,
step_ms = 500,
timeout_ms = 30000,
}, function (ok, client)
if not ok then
return print("connect failed:", client)
end
client.login("me@example.com", "app-password", function (okl, res)
if not okl then
return print("login refused:", res.status, res.text)
end
client.logout(function () end)
end)
end)
return true
Details
- A greeting of * BYE settles with ok false and the server's reason instead.
- Every command on the returned client takes a callback.
- logout closes the connection politely, and close closes it abruptly.
The command set
Commands are tagged and queued. One command is in flight at a time and the rest wait, so the commands run in the order you issue them.
client.login(user, pass, cb)
client.examine(mailbox, cb)
client.select(mailbox, cb)
client.search(criteria, cb)
client.fetch(set, items, cb)
client.store(set, flags, cb)
client.expunge(cb)
client.append(mailbox, flags, message, cb)
client.list(cb)
client.drafts_mailbox(cb)
client.logout(cb)
client.close()
Details
- Callbacks that parse hand back the parsed value:
| Command | Callback value |
|---|---|
| examine, select | { exists, uidvalidity, uidnext } |
| search | an array of numeric uids |
| fetch | one table per message |
| list | { name, attrs } per mailbox |
| drafts_mailbox | the name of the mailbox with the SPECIAL-USE \Drafts attribute |
- The rest hand back the raw result table, { status, text, untagged }.
- status is the IMAP completion word, and untagged holds the server's untagged lines for that command.
- ok is status == "OK". So a NO or BAD arrives as ok false with the server's text, instead of as an error.
- examine opens a mailbox read-only.
- store sends UID STORE with flags passed verbatim.
- append's flags may be nil.
- close drops the socket without a LOGOUT.
The driver contract
A driver is one function, connect(opts, done). opts carries host, port, a data callback and a closed callback, and done receives ok and a conn that exposes write and close.
local driver = {}
driver.connect = function (opts, done)
local conn = {
write = function (data) end,
close = function () end,
step = function (ms) end,
}
done(true, conn)
return conn
end
local imap = require("santoku.imap")(driver)
Details
- Inbound bytes are pushed. The driver calls opts.data(chunk) with every byte the socket produces, in whatever fragments the network produced.
- The core reassembles CRLF lines and IMAP literals from the chunks.
- The driver calls opts.closed(err) once, when the connection is gone.
- A driver on a blocking runtime with no event loop also exposes step(ms). step does one bounded read and delivers it through the same data callback.
- Only pull drivers define step. step returns true after it delivers bytes, and true and "timeout" when none arrived in ms.
- step returns false and an error once the connection is gone.
- The core detects step and pumps it internally during connect and each command.
- So a consumer writes the same callbacks either way. Only the timing differs: synchronous on a pull driver, event-driven on a push driver.
- step_ms (1000) sizes each pump, and timeout_ms (30000) bounds the wait.
- A command that goes timeout_ms with no bytes from the server fails, and the connection is closed.
| Ready-made driver | Runtime | Mode |
|---|---|---|
| santoku.socket.stream | LuaSocket and LuaSec | pull |
| santoku.web.stream | node tls under wasm | push |
| santoku.resty.stream | ngx cosockets | push |
- Anything that implements the contract works.
What a fetch returns
fetch(set, items, cb) takes the uid set and the item list as strings and passes them through, so anything the server understands is available. Each message comes back as a table.
local arr = require("santoku.array")
client.search("UID 1:* SINCE 1-Jan-2026", function (ok, uids)
client.fetch(arr.concat(uids, ","),
"UID X-GM-THRID BODY.PEEK[HEADER.FIELDS (SUBJECT FROM DATE MESSAGE-ID REFERENCES)]",
function (ok2, msgs)
for i = 1, #msgs do
print(msgs[i].uid, msgs[i].thrid, #msgs[i].header)
end
end)
end)
client.fetch("5", "UID BODY.PEEK[TEXT]<0.65536>", function (ok, msgs)
print(msgs[1].body)
end)
local date = require("santoku.imap.date")
client.fetch("7", "UID FLAGS X-GM-LABELS INTERNALDATE RFC822.SIZE", function (ok, msgs)
local m = msgs[1]
print(m.flags["\\seen"], m.labels["\\Inbox"], m.size)
print(date.internaldate(m.internaldate))
end)
print(date.rfc2822("Sat, 27 Sep 2026 08:51:00 -0400"))
Details
| Field | Value |
|---|---|
| uid, size | numbers |
| thrid, msgid | from the Gmail extensions |
| internaldate | the server's string |
| flags | a set of lowercased names |
| labels | a set of X-GM-LABELS as sent |
| structure | from BODYSTRUCTURE |
| parts | each BODY section name mapped to its bytes |
| header | the HEADER section |
| body | the other BODY section |
| items | every item raw, with parenthesized lists such as ENVELOPE as nested tables |
- parts recognizes a partial range like <0.65536> and strips it from the section name.
- Literals are reassembled before the parse. So a header that arrives as {512} followed by 512 bytes is indistinguishable from a quoted string.
- santoku.imap.date turns internaldate, or an RFC 2822 Date header, into epoch seconds. It returns nil for anything it can't parse.
- Use BODY.PEEK instead of BODY, unless you want the message marked read.
Header parsing and decoding
santoku.imap.headers.parse turns the raw header block from a fetch into a table keyed by lowercased field name. decode, ids and address work on single field values.
local headers = require("santoku.imap.headers")
local h = headers.parse(msg.header)
print(h.subject, h["message-id"])
print(headers.decode(h.subject))
local addr, name = headers.address(h.from)
print(addr, name)
local refs = headers.ids(h.references)
print(#refs, refs[1])
Details
- parse joins folded continuation lines first. A repeated field keeps its first occurrence.
- decode applies RFC 2047 to an encoded-word string, and handles both B and Q encodings.
- decode stitches adjacent encoded words that a mailer split across a fold.
- Undecodable base64 falls through as the raw data, and decode doesn't raise.
- ids pulls the angle-bracketed identifiers out of a References or In-Reply-To value, in order.
- address splits a From or To value into the bare address and the display name, and decodes the name on the way.
Text part from BODYSTRUCTURE
santoku.imap.bodystructure's text_part(structure) finds the first text/plain leaf, or else the first text/html one. It returns the IMAP part number with the subtype, encoding, charset and size.
local bs = require("santoku.imap.bodystructure")
client.fetch("5", "UID BODYSTRUCTURE", function (ok, msgs)
local part = bs.text_part(msgs[1].structure)
print(part.part, part.subtype, part.encoding, part.charset, part.size)
client.fetch("5", "BODY.PEEK[" .. part.part .. "]", function (ok2, got)
print(#got[1].body)
end)
end)
Details
- A BODYSTRUCTURE fetch costs one round trip and no body bytes.
- The parsed structure is a tree. Leaves carry type, subtype, params, encoding and size, and a multipart node carries subtype and parts.
- The part number goes in the next fetch. So a multi-megabyte message with attachments costs only the few kilobytes of text you wanted.
Message text as paragraphs
santoku.imap.mime's extract_text(content_type, content_transfer_encoding, raw) returns plain text or nil. paragraphs then collapses that text into an array of whitespace-normalized blocks.
local mime = require("santoku.imap.mime")
local headers = require("santoku.imap.headers")
local h = headers.parse(msg.header)
local text = mime.extract_text(h["content-type"], h["content-transfer-encoding"], msg.body)
local blocks = mime.paragraphs(text, { max_count = 8, max_len = 400 })
for i = 1, #blocks do
print(i, blocks[i])
end
Details
- extract_text decodes base64 and quoted-printable.
- extract_text descends multipart bodies up to four levels, and prefers text/plain over text/html.
- When plain text is absent, extract_text strips tags out of HTML. It decodes numeric entities (é, 😀) and the common named ones to UTF-8.
- An unknown or invalid entity stays as written.
- extract_text never raises. A malformed body returns nil.
- paragraphs bounds its output with three options at once:
- max_len: 2000 bytes per block by default.
- max_count: 64 blocks by default.
- max_total: 16384 bytes overall by default.
- When any bound bites, paragraphs appends a literal [truncated] block.
- Cuts land on a UTF-8 boundary instead of mid-sequence.
Reply chains, signatures and forwards
santoku.imap.body works on the plain text that mime returns. strip(text) drops signatures and quoted reply tails, and segments(text) splits forwards into nested blocks.
local body = require("santoku.imap.body")
print(body.strip("Sounds good.\n\nOn Fri, Sep 4, 2026 at 10:10 AM Bob <bob@example.com> wrote:\n> Lunch?\n"))
local segs = body.segments("FYI.\n\n---------- Forwarded message ---------\n"
.. "From: Alice Example <alice@example.com>\nSubject: Monthly Update\n\nThe forwarded body.\n")
for i = 1, #segs do
print(segs[i].depth, segs[i].text)
end
return #segs
Details
- strip drops a signature after a -- line.
- strip drops a trailing quoted reply with its On ... wrote: attribution.
- strip drops an -----Original Message----- tail.
- Quoting answered inline stays, and so does a leading quote followed by a reply.
- segments strips the text, then splits it into { depth, text } blocks.
- segments turns a Forwarded message header into one Forwarded: subject from sender (date) line. What follows nests one depth deeper.
- segments puts blank lines between list items.
- segments cuts URLs longer than body.URL_MAX (100) bytes with ... at the cut, as cap_urls(text, max) does.
- lines(text) splits on CRLF, CR or LF and drops trailing blank lines.
Threads from References
santoku.imap.thread's forest(msgs) takes an array of messages with msgid, refs, thrid and uid, and returns root nodes of { msg, children }.
local thread = require("santoku.imap.thread")
local headers = require("santoku.imap.headers")
local str = require("santoku.string")
local msgs = {}
for i = 1, #fetched do
local h = headers.parse(fetched[i].header)
msgs[i] = {
uid = fetched[i].uid,
thrid = fetched[i].thrid,
msgid = h["message-id"] and headers.ids(h["message-id"])[1],
refs = headers.ids(h.references),
subject = headers.decode(h.subject),
}
end
local roots = thread.forest(msgs)
local function show (node, depth)
print(str.rep(" ", depth) .. node.msg.subject)
for i = 1, #node.children do
show(node.children[i], depth + 1)
end
end
for i = 1, #roots do
show(roots[i], 0)
end
Details
- forest walks each message's refs from the nearest ancestor outward. The first ref present in the batch becomes the parent.
- That's the standard rule, and it still threads correctly when a mailer rewrites the middle of a chain.
- forest detects and breaks cycles from duplicate or forged Message-IDs, so it doesn't loop.
- forest then groups messages left without a parent by thrid. The lowest uid becomes the root of its group.
- So a Gmail conversation still comes back as one tree when the References headers are missing entirely.
- Children are sorted by uid at every level.
Drafts through APPEND
mime.build(t) assembles an RFC 5322 message from a table, and append sends it as an IMAP literal. drafts_mailbox finds the target mailbox by SPECIAL-USE.
local mime = require("santoku.imap.mime")
local message = mime.build({
from = "me@example.com",
to = "you@example.com",
subject = "Re: the proposal",
date = "Thu, 18 Sep 2026 09:00:00 +0000",
message_id = "draft-1@example.com",
in_reply_to = "abc@example.com",
references = { "abc@example.com" },
paragraphs = { "Looks good.", "One question about the timeline." },
})
client.drafts_mailbox(function (ok, box)
if not ok then
return print("no drafts mailbox:", box.text)
end
client.append(box, "\\Draft", message, function (oka, res)
print(oka, res.status, res.text)
end)
end)
Details
- build writes From, To, Subject, Date, Message-ID, In-Reply-To and References, then a text/plain utf-8 body.
- The body is the paragraphs array joined by blank lines, with line endings normalized to CRLF.
- build wraps a subject outside printable ASCII as a base64 encoded word. encode_word does the same on its own, if you need it elsewhere.
- append computes the byte count for you and handles the continuation handshake internally.
- drafts_mailbox uses SPECIAL-USE instead of a guess at a name, since the name differs across servers and locales.