@wtfalch/email
The estate's mail, in three entries with no code in common:
@wtfalch/email/mailbox reading and writing messages (RFC 8620/8621)
@wtfalch/email/imip proposing and declining a time (RFC 5546/6047)
@wtfalch/email/postmaster administering the server (Stalwart's `x:` extension)
They share a subject, a scope and a repository, and nothing else. There is
deliberately no root entry: an entry named for a seam that does not exist is
worse than no entry at all.
/mailbox is for the person who has an address — inbox, threads, compose —
running in their browser as them, able to touch only their own mail. /imip
composes and parses the scheduling messages /mailbox sends and receives as
ordinary mail, behind its own entry so the calendar parser it needs never
rides along with a plain inbox. /postmaster is for whoever runs the server —
who gets a mailbox, what name is on it, who holds a key — running server-side
with an administrator credential, and never touching the contents of
anybody's messages.
The post office holds the analogy: one is the letters, one is what's inside a
particular kind of envelope, the other is the pigeonholes.
Status
Published: yes, v0.15.1, 2026-09-28.
@wtfalch/email/mailbox
Read and write mail over JMAP: session, mailbox tree, threads, bodies and
attachments, search, identities, submission and push. RFC 8620 and 8621, over
jmap-jam, so it is not tied to
Stalwart the way its neighbour is.
import { MailClient, mailboxes, findRole, listThreads, thread } from '@wtfalch/email/mailbox';
const client = new MailClient({
sessionUrl: 'https://email.example.com/.well-known/jmap',
bearerToken: accessToken, // the signed-in person's, from the issuer
});
const tree = await mailboxes(client);
const page = await listThreads(client, findRole(tree, 'inbox').id, { limit: 50 });
A login usually reaches more than one mailbox. client.accounts() lists them,
the person's own first: a shared mailbox such as hr@ is an ordinary account
the server puts in the same session with isPersonal: false, because the
account is a member of it. A client stays on the account it was built with, so
opening another one is new MailClient({ …, accountId }) with the id from that
list — which is what keeps one client's cached session honest.
One folder can also be shared on its own, finer than a whole account:
shareMailbox(client, mailboxId, accountId, rights) grants another account
some of RFC 8621 §2's ten rights (mayReadItems, mayAddItems, …) on that one
mailbox, and unshareMailbox takes them back. Both patch Mailbox/set at
shareWith/<accountId> rather than sending the whole shareWith map, so
granting or revoking one account's access never touches another's, and needs
no read first. findPrincipals(client, query) turns an email address or a
name into the colleague's accountId and display name (JMAP principals, same
domain as the login only; an empty list is nobody, two entries is a choice),
and lookupPrincipal returns the one match or null, or throws ambiguous.
sharedPeople(client, mailboxId) goes the other way: for one folder it lists
each account in shareWith with the person's name, email and rights,
sorted by name, in one Principal/query and one Principal/get. An account
the directory cannot name comes back with its account id as name and email.
mailboxes() returns each node's own myRights (what the
signed-in login may do there) and shareWith (who else can, and with what),
both always present, every right explicit — RFC 8621 requires myRights, and
the wire has been seen to fill in every unrequested right on shareWith as
false too, which buildTree also does for a caller-built value that leaves
some out.
A page of threads is one round trip: the query, the newest message per
thread, the threads' member ids and the members are four method calls chained
by JMAP result reference in a single request.
Delta sync, for a follower that has to notice new or moved mail without
holding a full JMAP client of its own — the gap Activity's mail source had to
work around by writing one. emailChanges(client, { sinceState }) and
mailboxChanges(client, { sinceState }) are RFC 8620 §5.2's /changes:
{ oldState, newState, hasMoreChanges, created, updated, destroyed }, id lists
only. Watch both — a thread moving folders changes Mailbox, not Email
membership, so a follower that only watches Email never notices a move.
emailHeaders(client, ids) reads created/updated back as a header-only
projection (id, threadId, mailboxIds, from, subject, preview,
receivedAt, inReplyTo, keywords) that never fetches a body or an
attachment. When the server can no longer diff from sinceState, both
changes calls throw a MailError typed cannotCalculateChanges —
isCannotCalculateChanges(error) tells a caller apart from any other failure,
so it knows to resync (list what it wants fresh, and start delta sync again
from the state that read returns) rather than retry. Works the same with a
service credential for someone else's account (MailClientOptions.accountId
plus a bearer or app-password credential the caller holds, not the signed-in
session's own) — Activity's calendar source already does this for calendars.
replyDraft and forwardDraft are pure — give them a message and they
compute the recipients, the subject prefix, the In-Reply-To and References
chain and the quoted body, with no client and no network, so a composer can
call them on every keystroke. send creates the draft, submits it, and files
it in Sent; a delay in seconds holds it there first, and cancel unsends
it while undoStatus is still 'pending' — the only honest sign the window
is still open, since a server not set up for held delivery answers 'final'
regardless. queued lists everything still held, soonest first, for a
"scheduled" view that survives a reload: it filters its query on undoStatus
rather than reading the field off an unfiltered one, since that filter is
what makes the server recheck each submission against the mail queue and
demote one that already went, instead of answering a stale 'pending'. Every
row it returns is safe to hand straight to cancel. submissions lists the
account's sent mail newest first, each with a state (scheduled, sending,
delivered, failed, canceled) read from undoStatus and the server's
deliveryStatus, plus the email's subject and to; options.states and
options.limit (default 100) narrow it, and a failed row carries the
recipient's smtpReply as failure. resend sends a message that is already
in Sent again, with the identity matching its From, and files nothing. saveDraft stores a
draft in Drafts so it outlives the compose sheet, and given the id it returned
last time, replaces that draft instead of adding one (messages are immutable,
so the id changes each save). send(…, { draftId }) sends and removes the
saved draft. Both refuse an id that is not a $draft, since replacing is a
destroy. attach uploads a file
and gives back what a draft carries; the
upload is refused before any of it is sent when the file is over the
session's maxSizeUpload, which client.session() reports alongside
maxSizeAttachmentsPerEmail.
setRead, setFlagged, moveThread, moveToRole and removeFromMailbox
change mail rather than read it, and every one of them takes a thread.
RFC 8621 has no Thread/set — a thread is derived from its messages — so
each resolves the members and patches all of them in one Email/set, because
a conversation half-archived or half-read is not a thing anybody asked for.
They resolve when the server has accepted the change; nothing here is
optimistic, since the count is the one number people trust.
await setRead(client, threadId, true);
await moveToRole(client, threadId, 'archive', { mailboxes: tree });
setLabel puts a label on a thread without moving it: the keyword
$label:<name>, lowercased, since keywords are case-insensitive. A name a
keyword cannot hold (a space, any of (){]%*"\) is refused, not rewritten.
ThreadSummary.labels carries the labels on any message in the thread.
listLabels reads the newest 500 messages (scan to change it), because
JMAP can search for a keyword but cannot list them.
snoozeThread moves a thread into a top-level Snoozed mailbox, made on first
use, and stamps it $snoozed:<unix seconds>. JMAP has no snooze, so nothing
brings it back on its own: the host runs wakeSnoozed(client, now) on a
timer, and each thread whose time has come goes back to the Inbox, unread.
vacationResponse reads the account's out-of-office responder and
setVacationResponse sets it — RFC 8621 §8's VacationResponse, over the
urn:ietf:params:jmap:vacationresponse capability Stalwart advertises. It is
a singleton, never created or destroyed, so a set is always an update; a field
left out of the call keeps whatever the server already has, and null clears
it. clearVacationResponse is the shorthand for turning it off — isEnabled: false — without touching the dates or the message, so switching it back on
does not need them resupplied.
The reply has an audience: 'anyone' (default), 'company' (senders in the
account's own domain, taken from the first identity) or 'nobody' (dates and
text kept, no reply). With the sieve capability the away reply is the vacation
section of the account's one active script, next to the mail rules, and the
server's own VacationResponse is kept isEnabled: false so it never replies
twice; a hand-written active script refuses an enabling write (conflict) but
can still be turned off. Without the capability only 'anyone' works and the
JMAP object is used as before.
await setVacationResponse(client, {
isEnabled: true,
fromDate: '2026-09-28T00:00:00Z',
toDate: '2026-10-05T00:00:00Z',
subject: 'Out sick',
textBody: 'I am out sick until October 5th.',
});
// …later
await clearVacationResponse(client);
Note that a stock Stalwart account has no Archive mailbox — it creates
Inbox, Drafts, Sent Items, Junk Mail and Deleted Items — so moveToRole(…, 'archive') throws there rather than doing nothing, and a caller should offer
the action only where findRole(tree, 'archive') finds one.
Per-account filtering rules are Sieve, over the same JMAP endpoint — RFC
9661, urn:ietf:params:jmap:sieve. sieveScripts lists every script on the
account (name, isActive, blobId); sieveScriptText reads one's source.
saveSieveScript(client, name, text) creates a script from text, or
replaces one's content when given { scriptId }, uploading it as a blob the
same way attach uploads a file. validateSieveScript compiles text on
the server without saving it, for a check before committing. Exactly one
script is active per account: activateSieveScript(client, id) makes it the
one that runs, and deactivateSieveScripts turns filtering off entirely.
deleteSieveScript is refused while its target is the active script — the
server's own guard, deactivate first. Stalwart's SieveScript is
only a name, an active flag and a blob of Sieve source, so rules live in
this package: rulesToSieve(rules) writes Sieve for a list of MailRules
(from/to/cc/subject contains, has attachment, list-id present; move to a
folder, add a keyword, mark read, forward a copy, stop), and
sieveToRules(script) reads back only a script that function wrote, using a
marker line at the top, and gives null for a hand-written or edited one.
Every value is quoted and escaped, so it cannot end its string early.
The React
@wtfalch/email/mailbox/react draws it, on @wtfalch/design ^0.30.0.
Breaking: the floor moved from ^0.28.0 to ^0.30.0. 0.30.0 ships a
rewritten Toggle -- a busy state drawn as an opacity pulse and a new spring
on the knob, keyed to the new --dur-spring token -- and this package
follows the same rule PR #126 set: the peer tracks the design minor this
package actually builds and tests against, never a range wide enough to
claim an untested one. No estate host runs design 0.30 yet -- Archon peers
0.29.0, Agora's app resolves 0.28.0 -- so a host on an older design must
upgrade @wtfalch/design to 0.30.x before taking this @wtfalch/email
release; installing this range against an older design is a peer conflict,
not a silent downgrade.
Mail is the whole client — mailboxes, list, message, composer,
search, a toolbar, and a command palette on Cmd-K — and the only piece that
holds state or fetches.
MailboxTree, ThreadList, ThreadView and Composer take their data as
props and know nothing about a client, so an application with its own layout
takes the four and skips the shell. HtmlBody, which ThreadView draws a
message's HTML with, is exported on its own too. Import @wtfalch/email/mailbox/mail.css
after the design stylesheet.
Three layouts, and the middle one is not decoration. Three panes above
1150px, an icon rail and two panes above 860px, one pane at a time below it.
That last is why usePanes is a hook and not a media query: at one column the
list and the message are the same space, so which of them is showing is state
the shell has to hold.
The keyboard is the point. Arrows and j/k move through the list, which
is a single tab stop rather than fifty; c writes, r/a/f answer,
e/#/u/s file, / searches and ? lists them all. They are ignored
while a field has focus, or c could never be typed into a subject.
Opening a conversation marks it read, which is what opening means — and
only when there is something unread in it, because a set that changes
nothing still moves the account's state and wakes every other client's push
connection.
A file is on the draft only once it has uploaded. Attach opens the file
picker, and a file dropped anywhere on the composer is taken too. Until its
upload lands it sits in the list with a spinner and Send waits, because a
message that went while a file was on its way arrives without it. One that
failed says why and can be tried again; one over the server's limits is
refused before a byte is sent. Either stays in the list, and Send keeps
waiting, until it is retried or removed. Composer takes the upload as an
onAttach prop, since it holds no client, and Mail supplies attach.
HTML is drawn in a frame it cannot climb out of. Mail arrives from
strangers, and a client that injects their markup into its own document is one
script tag from being read by them. So HtmlBody never does. Three walls,
each of which holds if the other two fall:
- A sandboxed frame. A
srcdoc iframe with no allow-scripts, no
allow-forms and no allow-top-navigation: nothing in it runs, submits or
replaces the page. Links open a tab of their own. It has
allow-same-origin, deliberately, so the view can size the frame to the
message; that is safe only because nothing in it can run, and
FRAME_SANDBOX is pinned by a test that fails if allow-scripts joins it.
- A content policy of its own.
default-src 'none', inline styles and
nothing else, form-action and base-uri closed, no fonts, and images from
data: only.
- A sanitiser. An allowlist of elements and attributes, walked over an
inert
DOMParser document, for what the other two do not stop — a <meta>
refresh, a <base>, a ping, a relative address that would fetch from this
application. CSS is read back through the CSSOM rather than matched with a
pattern, so u\72l( is caught as the url( it is.
Remote images wait to be asked for. An image on the sender's server tells
the sender the message was opened, when and from where, so they are withheld
and the reader is told how many, with a button that shows them for that
message. Inline cid: pictures are part of the message and are drawn — fetched
through fetchInline, behind the same credential as everything else.