- Zig 88%
- Nix 12%
allthemail-o365 #
Mirrors a Microsoft 365 mailbox into a local all the mail archive: walks every folder, fetches every message as raw RFC 5322, and posts it to the archive with the folder it was in and the categories on it as notmuch tags. It keeps a SQLite ledger of what it has seen and what it has stored, so a run that is interrupted — and over forty thousand messages, a run will be interrupted — costs the work in flight and nothing more.
It is a command, not a daemon. Point a systemd timer at it.
$ atm-o365 login --account jeff@example.com
$ atm-o365 sync
jeff@example.com: syncing
jeff@example.com: discovered 41238, stored 41238, duplicate 0, retagged 0, moved 0, gone 0, failed 0
$ atm-o365 sync
jeff@example.com: discovered 12, stored 12, duplicate 0, retagged 3, moved 1, gone 1, failed 0
The API documentation is generated from the doc comments and published at
https://jeff.jcollie.page/allthemail-o365/; zig build docs-serve reads it
locally.
Where this lives #
- https://git.jcollie.dev/jeff/allthemail-o365 — the primary home.
- https://tangled.org/jcollie.dev/allthemail-o365 — mirror.
git clone https://git.jcollie.dev/jeff/allthemail-o365.git
On Radicle, the peer-to-peer forge, the repository is
rad:z27zvNS2eMBAUHvQWXD8hKGh5FrQQ, which is the only name it has there — a
Radicle repository is found by its ID and nothing else — so seeding or cloning
it goes:
rad clone rad:z27zvNS2eMBAUHvQWXD8hKGh5FrQQ
Cloning also seeds the repository, which helps keep it available on the network.
How it works #
Three pieces, and this is the one that drives the other two:
- zig-o365 is the read-only Microsoft Graph mail client. It lists folders, walks the per-folder delta queries, fetches the RFC 5322 bytes behind a message, and batches. It persists nothing.
- all the mail is an append-only, content-addressed archive indexed by notmuch. It stores whatever it is given and explicitly does not fetch mail.
- allthemail-o365 is the ledger and the loop between them.
It is the Gmail sibling, and four things are genuinely different #
allthemail-gmail is the same idea against the other service, and this is not a rename of it. Four things are different in a way that reaches all the way down into the schema:
A message is in one folder, not carrying a set of labels. So a tag is a
folder path — the inbox is o365/inbox, a subfolder of it is
o365/inbox/zig, Sent Items is o365/sent — and Outlook's categories, which
are the nearest thing here to a Gmail label, become o365/category/<name>.
Which folder is the inbox is not something a message says: a message carries an
opaque parentFolderId and nothing else, and the well-known names only work
in a URL. So the well-known folder ids are resolved once, cached in the ledger,
and used to name the top of each path — which is also what makes a mailbox
whose inbox is called Posteingang produce the same tags as one whose inbox is
called Inbox.
Change tracking is per folder. There is no mailbox-wide history feed, no
history id, nothing that answers "what changed in this mailbox". There is a
delta query per folder, each ending with an @odata.deltaLink to resume from,
so the ledger keeps one checkpoint per folder rather than one per mailbox.
A delta walk with no stored link is a full listing of the folder that ends with
a token, which means the first run and the recovery from a stale token are the
same code path. Graph answers a token that has aged out with 410 Gone and
resyncRequired; that is not a failure to retry, it is the designed fallback,
and it costs one listing of that folder.
A partial delta walk has no resume point. The @odata.nextLink in the
middle of a delta walk is a $skiptoken, which is not a delta token and
expires in hours, so the checkpoint is written only when the walk reaches the
end. An interrupted walk starts again — cheaply, because everything it already
discovered is written down and discovery is idempotent.
A move changes a message's id. A message moved between folders arrives in
one folder's delta as a removal and in another's as something new, with nothing
in either to connect them. The bytes are the same bytes, so the archive already
holds them — which would make the HEAD /message/{hash} pre-check say "already
there" and skip the upload that would have added the new folder's tag.
internetMessageId is what survives a move, so the ledger stores and indexes
it. An id whose Message-ID: is already archived under a different id is
recognised as a move, the pre-check is skipped, and the message is posted again
so the new tag lands. The archive then carries both tags, which is the honest
thing for an append-only archive to say about a message that has been in two
places.
Why it does not re-upload #
The archive names a message by the SHA3-512 of its CRLF-canonical bytes. This
program computes that name itself and asks HEAD /message/{hash} before
uploading anything, so a re-run over a mailbox that is already archived is a
few thousand empty requests rather than a few gigabytes.
That means there are two implementations of one hash, and if they ever disagree every pre-check misses silently and the archive grows a copy per run. They are pinned together by the same NIST vector on both sides, and a disagreement at run time is logged as an error rather than shrugged off.
Fetching, and the one open question #
The delta listing already carries everything but the bytes — parentFolderId,
internetMessageId, receivedDateTime and the categories all come back in it
— so the fetch is exactly one thing: GET /me/messages/{id}/$value, the
message as it arrived.
That is one round trip per message, which over a whole mailbox is the
difference between a sync that finishes overnight and one that does not, so it
is done through $batch: twenty $value fetches in one POST. zig-o365 is
explicit that whether Graph serves $value inside a batch is not something its
test suite can settle, so this treats it as a question rather than an
assumption — a batch that comes back with nothing usable in it turns batching
off for the rest of the run, says so, and the messages are fetched one at a
time instead. batch_mime: false skips the experiment.
A batch of whole messages is large, and how large is not knowable in advance: Graph's message listing carries no size at all, so unlike the Gmail sibling there is not even an estimate to budget with. A response that overruns is not an error, it is a signal to split the chunk and try both halves.
Tags #
| Outlook | tag |
|---|---|
| the inbox | o365/inbox |
Sent Items |
o365/sent |
Junk Email |
o365/spam |
Deleted Items |
o365/trash |
a folder zig inside the inbox |
o365/inbox/zig |
a category Receipts, 2025 |
o365/category/Receipts, 2025 |
They travel as repeatable X-Archive-Tag headers on POST /archive, one tag
per header, commas and all. A folder name is arbitrary text somebody typed, and
allthemail refuses a bad tag with a 400 for the whole request — which
costs the message, not the tag — so control characters are dropped and
over-long tags are truncated on a codepoint boundary.
When a folder is renamed the bytes have not changed, so nothing is fetched again: every message in it is marked, re-submitted, and the archive recognises the hash, leaves the file alone and adds the new tag. A category change works the same way.
This works against an allthemail that has never heard of X-Archive-Tag.
Unknown headers are ignored there, so the tags are simply dropped and
everything else behaves. There is a test for exactly that.
Configuring it #
$XDG_CONFIG_HOME/allthemail-o365/config.json, or --config, or
$ALLTHEMAIL_O365_CONFIG:
{
"allthemail": "http://127.0.0.1:8080",
"accounts": [
{
"address": "jeff@example.com",
"tenant": "common",
"client_id_path": "/run/credentials/allthemail-o365.service/client-id"
}
]
}
That is the whole of it. Three paths are worked out rather than written down, each from the base directory that kind of thing belongs in — via known-folders, so they are the ones the rest of the machine already agrees on rather than three more hand-rolled ladders:
| the configuration | $XDG_CONFIG_HOME/allthemail-o365/config.json |
or --config, or $ALLTHEMAIL_O365_CONFIG |
| the ledger | $XDG_DATA_HOME/allthemail-o365/state.db |
or database |
| an account's tokens | $XDG_CACHE_HOME/allthemail-o365/<address>.json |
or token_path |
The ledger is data and not cache because losing it costs a full listing of
every folder of every mailbox — minutes of somebody's Graph quota — while a
lost refresh token costs one atm-o365 login and nothing else.
Nothing in this file is a secret, which is the point of naming the
application id rather than writing it down: it can be generated, committed, or
put in the Nix store, and the credential arrives separately — from systemd's
LoadCredential, from agenix, or from a file you wrote by hand. It is needed
at all because the token store deliberately holds only the tokens, and every
refresh is a request made as the application, so a sync run from a timer days
after signing in has nobody to type it.
The file holds one value and nothing else. Surrounding whitespace is trimmed,
because every editor adds a trailing newline and the identity platform rejects
a credential with one attached without mentioning newlines. A file with a space
or a line break in the middle is refused as not being a credential — that is
almost always a JSON document somebody pointed at instead of the value inside
it. chmod 600 it: a credential anyone on the machine can read is refused
rather than warned about.
The ledger is kept owner-only too, and put back to it if it is found otherwise. There is no credential in it, but it is a map of the mailbox — every message id, when it arrived, which folder it is in and what that folder is called — and that is not the one file on the machine that should be world-readable.
The application registration #
doc/entra-application.md is the step-by-step: which tile in the portal, which four permissions, and what each error code means when one of them is wrong. The short version:
Register it in Entra ID as a public client — a desktop application — with a
redirect URI of http://localhost/callback and no secret. A program shipped
to somebody's laptop cannot keep one, and PKCE is what protects the
authorization code instead. client_secret_path exists for a confidential
client and is absent by default.
The name localhost rather than the literal 127.0.0.1 that RFC 8252 section
8.3 asks for, because Entra ID ignores a reply URL's port only for that
name — which is what lets a URL registered once match the port the kernel hands
login on the day. The literal needs the port too, and a port fixed in advance
is one another program on the machine can be sitting on; it also cannot be added
through the portal's redirect URI box at all, only by editing the application
manifest. --redirect-host ip with a matching --port is there for whoever has
done that. The path is compared, so register /callback — the path this
listens on — and not a bare http://localhost.
The scopes asked for are openid, offline_access, User.Read and
Mail.Read; nothing here writes to the mailbox, and every request it makes is
a GET. offline_access is the one that catches everybody: without it no
refresh token comes back and the grant dies in about an hour, which for
something run from a timer means it never works twice. It is the Microsoft
equivalent of Google's access_type=offline, and it is not implied.
What was asked for is not always what was granted — a tenant that consents only
to Mail.ReadBasic answers a request for Mail.Read with the narrower one,
and Mail.ReadBasic cannot fetch message content at all. login says so
rather than leaving it to surface as a refusal forty thousand messages into a
walk.
tenant is common for an application registered multi-tenant, or the
organisation's GUID or verified domain for one registered against a single
tenant.
The other settings #
tag_prefix may be null, which sends no tags at all. Everything else has a
default:
chunk_size |
20 | Messages per $batch. Graph rejects more outright. |
max_attempts |
5 | Before a message stops being retried every run. |
batch_mime |
true |
Fetch the content through $batch; see above. |
include_hidden |
false |
Walk hidden folders, which are mostly Outlook's own bookkeeping. |
skip_detritus |
true |
Leave out Sync Issues, Recoverable Items, the search folders and their neighbours. |
skip_folders |
[] |
Folders to leave out by tag path; a named folder takes its children with it. |
skip_detritus is the one worth a sentence. Recoverable Items holds
everything that has ever been shift-deleted or emptied out of Deleted Items, so
a mirror that walks it is a mirror of the mailbox's whole history rather than of
the mailbox. Turn it off deliberately, if that is what you want.
user_id on an account names a shared mailbox to read instead of the signed-in
user's own, which needs Mail.Read.Shared.
Authenticating to the archive #
allthemail's auth is off by default, and an archive with it off wants no
credential: the configuration above sends none, and that is the right shape for
an archive on loopback or behind something that authenticates for it.
With auth on, every endpoint but /health wants a passkey session or an API
token. A passkey ceremony needs a human and a browser and a timer is neither,
so what this sends is a token — minted from the archive's reading UI, under
Tokens, and named by a fourth path:
{
"allthemail": "http://127.0.0.1:8080",
"allthemail_token_path": "/run/credentials/allthemail-o365.service/archive-token"
}
Mint it with read and write both. They are not the same endpoint:
| scope | reaches | without it |
|---|---|---|
write |
POST /archive |
nothing can be archived at all |
read |
HEAD /message/{hash} |
every message is uploaded, held or not |
A write-only token works, and costs the whole of what the pre-check exists to
save: the archive answers 200 OK for bytes it already holds, so nothing is
lost or stored twice, but a mailbox that is already mirrored is uploaded again
rather than asked about. The first 403 is the last pre-check attempted — one
warning, and then the run stops asking — so it is a bandwidth bill rather than
a flood of failures.
A token file is read exactly like the application id: one value, whitespace trimmed, and refused if anyone but its owner can read it. It is named rather than written down for the same reason, so nothing secret enters the configuration.
A 401 stops the run where it stands. It says nothing about any message —
with no credential the archive accepts, every message after it would be refused
identically — so the sync gives up with a line saying which file to look at
rather than marking forty thousand messages failed and spending an attempt on
each. The ledger is untouched, and the next run with a working token does the
lot. With more than one mailbox configured, the second is not started either:
it is one archive for all of them, and it would answer the same after another
walk of somebody's Graph quota.
With Home Manager #
There is a module, so none of the above has to be written by hand:
{
inputs.allthemail-o365.url = "git+https://git.jcollie.dev/jeff/allthemail-o365.git";
# in your Home Manager configuration
imports = [ inputs.allthemail-o365.homeManagerModules.default ];
services.allthemail-o365 = {
enable = true;
onCalendar = "hourly";
settings = {
allthemail = "http://127.0.0.1:8080";
# Only if the archive has `auth` on; see above.
allthemail_token_path = "/run/user/1000/secrets/archive-token";
accounts = [
{
address = "jeff@example.com";
client_id_path = "/run/user/1000/secrets/o365-client-id";
}
];
};
};
}
That writes the configuration, puts atm-o365 on your PATH, and installs a
systemd user timer. Persistent is on, so a laptop that was shut when the
timer should have fired syncs when it comes back rather than waiting out the
interval — which matters, because a delta token left unused for long enough
ages out into a full listing of every folder.
A user service and not a system one: what it syncs is one person's mail, with one person's OAuth grant, into an archive that person can read.
The credential paths are still yours to fill, the archive token among them.
Do not use home.file for any of them — that puts them in the Nix store, where
they would be world-readable and the program would refuse them. agenix,
sops-nix, or a file written by hand and chmod 600.
Run atm-o365 login --account <address> once before the timer is any use.
Commands #
login --account ADDR |
Sign in and store the refresh token. Opens a loopback listener and prints a URL. --port N, --redirect-host localhost|ip, --timeout N. |
sync |
Bring the archive up to date. --account, --limit N, --full, --dry-run. |
status |
What the ledger says is done and outstanding, with recent failures. |
retry |
Clear the attempt counters so failed messages are tried again. |
folders |
Re-read the folder tree and show the tag each folder produces. |
Everything but login acts on every configured account unless --account says
otherwise. The exit status is non-zero if anything failed, which is what a timer
unit wants.
--full throws away every folder's delta token and the cached well-known
folder ids, so the whole mailbox is listed again. It is what to reach for when a
folder has appeared that the cache does not know about — an archive folder
switched on, say. It costs a listing and never a re-upload.
A message that keeps failing stops being retried after max_attempts, so one
permanently broken message does not make every future run busy and noisy;
status lists it and retry clears it.
Building it #
It needs Zig 0.17.0, which the development shell and the Nix package take from
nixpkgs. For Zig 0.16.0, use the zig-0.16 branch, or the v0.1.0 tag it was
made from.
$ nix develop
$ zig build test --summary all
$ zig build
$ zig build fuzz-run -- --iterations 100000
Or as a package:
$ nix build
$ ./result/bin/atm-o365 version
The Nix build fetches the Zig dependencies itself and then forbids the network:
build.zig.zon.nix is generated from build.zig.zon by zon2nix and
handed to Zig with --system, so a dependency missing from it is a build error
naming the package rather than a silent reach for the network. Regenerate it
whenever a dependency moves:
$ nix develop -c zon2nix --17 --nix=build.zig.zon.nix build.zig.zon
Testing it #
tests/e2e.zig stands a fake Graph and a fake allthemail up on loopback
sockets and runs whole syncs between them: a first walk of every folder, a
paged delta listing, a second run that uploads nothing, a lost ledger that
re-checks instead of re-uploading, a category change that re-tags without a
second copy, a folder rename that does the same, a delta token that has aged
out, a message moved between folders, a batch too large to fetch in one piece,
a Graph that will not serve $value inside a batch, an archive that ignores
the tag header, and an archive with auth on — with a token that reaches
everything, with one that reaches only POST /archive, and with none at all. The fake archive is built to allthemail's documented
behaviour rather than to this program's expectations, so a change on either
side that breaks the contract fails there.
tools/fake-graph is that same fake Graph as a program, so it can be pointed
at by a real allthemail-o365 binary rather than linked into a test. Its
mailbox is chosen rather than arbitrary: a message with bare LF line endings, a
category with a comma in its name, a folder with a non-ASCII name, and a
message in Sent Items — the four things that only a real archive can prove are
handled, because they are about what notmuch ends up holding. Set graph in
the configuration to point at it.
tests/fuzz.zig holds the properties: that the canonicalizer agrees with
itself and is idempotent, that no folder name or category can produce a tag the
archive would refuse, that a folder path always ends in the folder's own name,
that a reply from the archive either parses or is reported malformed, and that
a configuration either validates completely or is rejected. The last of those
carries a security property as well as a robustness one: no configured tenant
may contain a path separator, because the tenant goes into the path of the
token endpoint and one carrying a / would send the sign-in somewhere else
entirely.
tests/nixos/roundtrip.nix is the other kind of test, and the only one that
is not a model of anything: a real atm with a real notmuch database, a real
allthemail-o365, real HTTP between them, and fake-graph standing in for the
one thing that cannot be real. It runs as a flake check, because it needs a
machine rather than a process:
$ nix flake check
It is there for claims about what ends up in somebody's notmuch database rather than about this program's reasoning, and so cannot be settled by a fake: that the two implementations of the hash agree, which the fixture with bare LF line endings is what would catch; that a folder path survives as a tag, non-ASCII included, and a category with a comma in it arrives as one tag; that a well-known folder is tagged by its conventional name; and that the pre-check really does stop a re-run uploading the mailbox a second time.
It runs a second archive beside the first with auth turned on, because what
a real allthemail answers an unauthorized client — 401 against 403, and
which of them says insufficient_scope — is the whole of how this program
tells "stop the run" from "stop pre-checking". Its tokens are seeded into the
archive's state file rather than minted, since minting one takes a passkey
ceremony and a ceremony takes a browser and a human; what allthemail stores is
a digest of the token's text, which Nix can compute, so they are
indistinguishable from tokens it minted itself. The archive's own metrics are
then what settle the claim that a read-scoped token turns five uploads into
five questions.
Run the suite optimized as well as in Debug — zig build test -Doptimize=ReleaseSafe, which CI does. It is not a formality: one bug found
that way in the sibling project was a write through std.Io.Reader.ending, a
@constCast of a const, which a Debug build survives and an optimized one
dies on.
zig build fuzz --fuzz hands those targets to Zig's own fuzzer, which steers by
coverage; build.zig has LLVM compile the fuzz test binary, because the
self-hosted backend Debug otherwise uses emits no coverage instrumentation and
leaves the fuzzer blind. tools/fuzz.zig drives the same targets with a loop of
its own from a corpus of seeds — no coverage, but bounded and reproducible from
a seed — and that is what CI runs.
References #
What this documentation says about the identity platform is quoted from Microsoft's own pages rather than remembered, and the formats it names are the published ones. Every specification and vendor page the code and the documentation lean on, and what each is leaned on for — the tools and libraries this is built with are linked where they come up instead:
Standards #
- Resnick, P., ed. (2008). Internet Message Format. RFC 5322.
doi:10.17487/rfc5322 — what
$valuehands back and what is posted to the archive: the message as it arrived, headers and all. - Denniss, W., and Bradley, J. (2017). OAuth 2.0 for Native Apps. BCP 212,
RFC 8252. doi:10.17487/rfc8252 — section 7.3 for the loopback port
being whichever one the kernel hands out, section 8.3 for the literal
127.0.0.1this deliberately does not use. - Sakimura, N., Bradley, J., and Agarwal, N. (2015). Proof Key for Code Exchange by OAuth Public Clients. RFC 7636. doi:10.17487/rfc7636 — what protects the authorization code in place of the client secret a program on somebody's laptop cannot keep.
Microsoft identity platform #
- Microsoft (2026). How to register an app in Microsoft Entra ID. Microsoft Learn — the portal path, the account types, and where the client and tenant ids are read off.
- Microsoft (2026). How to add a redirect URI to your application. Microsoft Learn — the platform tiles, and which one a desktop program's redirect URI belongs under.
- Microsoft (2025). Redirect URI (reply URL) best practices and limitations.
Microsoft Learn — the localhost exceptions: the port ignored
for the name alone, the path compared anyway,
[::1]unsupported, and the manifest edit anhttp://127.0.0.1URI needs. - Microsoft (2025). Public and confidential client apps (MSAL). Microsoft Learn — which flows actually require Allow public client flows, and so why this one leaves it off.
- Microsoft (2025). Microsoft Entra authentication & authorization error
codes. Microsoft Learn — the wording of
AADSTS50011,AADSTS65001,AADSTS700016andAADSTS7000218, quoted in the troubleshooting table of doc/entra-application.md.
The dates are the ones the pages carry. Microsoft revises them in place, so a quotation that no longer matches is a page that has moved on rather than one that was read wrong — which is why each carries its date here and a link to follow, rather than being paraphrased and left to be taken on trust.
Licence #
MIT. The project follows REUSE; reuse lint passes.