Archives a classic Unix mailbox into a local allthemail archive, tagged with the mailbox name, with a SQLite ledger so reruns send nothing.
README.md

allthemail-mbox #

Puts the messages in a classic Unix mailbox into a local all the mail archive: reads the file, takes each message out of its framing, and posts it with the mailbox's name as a notmuch tag and the postmark as notmuch properties. It keeps a SQLite ledger of what it has already archived, so running it again over the same mailbox sends nothing at all.

It is a command, not a daemon, and there is no timer unit. An mbox is a file somebody exported or moved aside; the natural thing to do with one is to import it once.

$ atm-mbox archive --file ~/Downloads/takeout/All\ mail.mbox --name gmail/takeout
gmail/takeout: reading /home/jeff/Downloads/takeout/All mail.mbox
gmail/takeout: read 41238, stored 41238, duplicate 0, known 0, repeated 0, failed 0
$ atm-mbox archive --file ~/Downloads/takeout/All\ mail.mbox --name gmail/takeout
gmail/takeout: reading /home/jeff/Downloads/takeout/All mail.mbox
gmail/takeout: read 41238, stored 0, duplicate 0, known 41238, repeated 0, failed 0

The API documentation is generated from the doc comments and published at https://jeff.jcollie.page/allthemail-mbox/; zig build docs-serve reads it locally.

Where this lives #

The repository lives in three places that carry the same history. The Forgejo instance at https://git.jcollie.dev/jeff/allthemail-mbox is the web-visible one, and is where the tests and the documentation are built:

$ git clone https://git.jcollie.dev/jeff/allthemail-mbox.git

it is mirrored on Tangled at https://tangled.org/jcollie.dev/allthemail-mbox, and it is also on the Radicle peer-to-peer network, where the repository's identifier is

rad:zt1uYNKVWBU4H7vum2ByKQ2sYhUB

and

rad clone rad:zt1uYNKVWBU4H7vum2ByKQ2sYhUB

fetches it from any node that seeds it — which is the only name it has there, a Radicle repository being findable by its ID and nothing else. Cloning also seeds it, which helps keep it available. Any of the three is the whole project.

How it works #

Three pieces, and this is the one that drives the other two:

  • zig-mbox is the mailbox reader. It finds where one message ends and the next begins — which is the whole difficulty of the format — and undoes the quoting that keeps a body from splitting its own message. It persists nothing and knows nothing about archives.
  • 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-mbox is the ledger and the loop between them.

One pass, from the beginning, every time #

The sibling programs — allthemail-gmail and allthemail-o365 — split a run in two, because for them discovery is a cheap API call and fetching is a round trip per message. Here there is nothing to discover. An mbox has no index, no length field and no way to be asked a question: the only way to find out what is in one is to read it from the first byte. Reading it is discovery, so the two halves are one pass.

Every run reads every mailbox from the beginning, and that is deliberate rather than a thing left undone. The obvious saving — remember how many bytes were read last time and start there — is wrong for this format, because an mbox has no stable offsets. Removing a message from one means writing the whole file again without it, which is what every tool that edits an mbox does, and after that every byte position recorded in the ledger points at the middle of something else. A watermark would be right until the first deletion and would then quietly skip mail.

What a full pass costs is a read and a SHA3-512 of a local file, measured in seconds per gigabyte. What the ledger saves is the expensive half: it answers "already archived?" from a point lookup on this machine, so a second run makes no network requests at all.

What is sent #

POST /archive, with the message's bytes canonicalized to CRLF, the mailbox's tags, its configured recipients, and the postmark as properties.

The bytes are canonicalized because the archive canonicalizes what it receives before hashing it. A mailbox out of a Unix mail store is bare LF from end to end, so here that rewrite is the rule rather than the exception — and getting it wrong would name a file the archive will never create.

Why the pre-check is usually not made #

HEAD /message/{hash} asks the archive whether it already holds some bytes, and the sibling programs ask it before every upload: one empty request that can save a twenty megabyte one. This does not ask, unless the submission carries nothing but bytes, and the reason is worth spelling out because the bug it avoids is silent and permanent.

A HEAD says the archive has the bytes. It does not say what is on them, and there is no way to submit tags to an archive without submitting the message again — so skipping the upload skips the tags and the properties with it. That is harmless for a rebuilt ledger over a mailbox this program archived itself, because the tags it would send are the ones already there. It is not harmless for a message that is in two mailboxes, which for a pair of mailing lists is an ordinary Tuesday: the second mailbox would find the bytes held, send nothing, and that message would never carry the second list's tag. Nothing would report it, and the next run would see the ledger say archived and not look again.

So the pre-check runs only when tag_prefix and property_prefix are both null and the mailbox names no tags and no recipients — which is what a bulk re-import into an archive that does not care where mail came from actually looks like, and the case where a pre-check is worth the most. Everywhere else the ledger is what stops the re-upload, and it is the better answer: no request at all rather than one per message.

Tags #

The mailbox's name becomes a tag under tag_prefix, default mbox/:

mailbox tag
name: "lists/zig" mbox/lists/zig
path: "~/mail/inbox.mbox", no name mbox/inbox
tags: ["mailing-list"] mailing-list, under no prefix

The name is a configuration item and not something read out of the file, because there is nothing in an mbox that says what it is. Absent, it is the file's basename with one extension removed — so writing one down is what makes the name survive the file being moved, and the only way to get a / in it.

Tags travel as repeatable X-Archive-Tag headers, one tag per header, commas and all. A name is either a path somebody chose or a string 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.

The postmark #

Every message in an mbox has a line in front of it that is not part of the message:

From jeff@example.com Mon Jan  1 00:00:00 2024

That is the postmark, and what it carries is the envelope sender and the time of delivery. Neither is in the RFC 5322 bytes underneath it, and neither need agree with anything that is: the From: header says who wrote the message and the postmark says who handed it over, which is the address a bounce goes back to and the one a mailing list rewrites. The moment a message is lifted out of the file, both are gone.

So they are recorded, as notmuch properties under property_prefix, default mbox.:

property from
mbox.envelope-from the postmark's address, when it had one
mbox.delivered the postmark's date, exactly as written
mbox.source the mailbox's name
$ notmuch search property:mbox.envelope-from=bounces@lists.example.org

delivered is undecoded on purpose. A great many mailboxes carry a postmark date no parser can read and a good many more carry one that is simply wrong, and rewriting either into an ISO 8601 string would be inventing a fact rather than recording one. Anything wanting a date it can trust has the message's own Date: and Received: headers, which notmuch already indexes.

source is there because tag_prefix may be null and a name may have been truncated to fit notmuch's two hundred bytes. A message found in two mailboxes collects one source for each, because notmuch records a value per delivery rather than replacing.

This works against an allthemail that has never heard of X-Archive-Property or X-Archive-Tag. Unknown headers are ignored there, so they are simply dropped and everything else behaves. There is a test for exactly that.

Which mbox this is #

There are four of them, they are not compatible, and nothing in the file says which:

variant what it stores undoing it
mboxo From becomes >From lossy — a >From the sender wrote is the same bytes
mboxrd any >*From gains one more > exact, and the default here
mboxcl mboxo, plus a Content-Length lossy, like mboxo
mboxcl2 nothing; a Content-Length says where the body ends exact, as long as the length is right

So it is a parameter and never a detection. Getting it wrong is not an error: it is a message whose bytes differ by one character from the one somebody sent, archived for ever under the hash of the wrong thing. mboxrd is the default because it is the only variant whose quoting is reversible, and it is what almost everything modern writes. If you do not know which one a file is, zig-mbox check --variant … says which it is self-consistent under.

What happens to a duplicate #

Two identical messages in one mailbox are one message. The archive is content addressed, so it would hold one file for them whatever this program said; the ledger counts the second as a repeat rather than pretending they are separable, and only one upload is made.

Configuring it #

$XDG_CONFIG_HOME/allthemail-mbox/config.json, or --config, or $ALLTHEMAIL_MBOX_CONFIG:

{
  "allthemail": "http://127.0.0.1:8080",
  "mailboxes": [
    {
      "path": "/home/jeff/mail/lists/zig.mbox",
      "name": "lists/zig",
      "recipients": ["jeff@example.com"],
      "tags": ["mailing-list"]
    }
  ]
}

A mailbox takes path and, optionally, name, variant (one of the four above), recipients, tags, lock and trust_content_length.

recipients is written down because an mbox does not know. The postmark carries the envelope sender, and the To: header is what the author wrote rather than where the message was actually delivered; the one true statement available is whose spool this was, and only the person configuring it can make it. Each one becomes a to/ tag in the archive.

mailboxes may be empty, which is the right shape for somebody who only ever names a file on the command line.

Two 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:

the configuration $XDG_CONFIG_HOME/allthemail-mbox/config.json or --config, or $ALLTHEMAIL_MBOX_CONFIG
the ledger $XDG_DATA_HOME/allthemail-mbox/state.db or database

The ledger is data and not cache because losing it costs a re-read and a re-upload of every configured mailbox. It is kept owner-only, and put back to it if it is found otherwise: there is no credential in it, but it is a description of somebody's mail — every message's size, when it was delivered, who it came from, and which file it was in — and that is not the one file on the machine that should be world-readable.

tag_prefix and property_prefix may each be null, which sends no tags and records no properties. That is a JSON null, which is not the same as leaving the setting out: absent means the default.

Everything else has a default: chunk_size (100), max_message_bytes (64 MiB), max_attempts (5).

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 this is neither, so what it sends is a token — minted from the archive's reading UI, under Tokens, and named by a path:

{
  "allthemail": "http://127.0.0.1:8080",
  "allthemail_token_path": "/run/user/1000/secrets/archive-token"
}

Mint it with read and write. write is what POST /archive needs and is the one that matters; read is for the pre-check, which — see above — is only made when the submission carries no tags and no properties.

A token file holds one value and nothing else. Surrounding whitespace is trimmed, because every editor adds a trailing newline and a header value carrying one is a request no server would answer. chmod 600 it: a credential anyone on the machine can read is refused rather than warned about. It is named by path rather than written down so that nothing secret enters a file that can be generated, committed, or put in the Nix store.

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 run 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.

Commands #

archive Read the mailboxes and put what is in them into the archive.
status What the ledger says is done and outstanding, with recent failures.
retry Clear the attempt counters so failed messages are tried again.
list The configured mailboxes, the tag each one produces, and whether the file is there.

Everything acts on every configured mailbox unless --mailbox NAME says otherwise. --limit N and --dry-run apply to archive.

A dry run reads the mailboxes and writes down what is in them — where each message is, how big it is, what its postmark said — and sends nothing. That is a fact about the file rather than about the archive, and writing it down is what makes a dry run worth having: status afterwards says exactly how much is outstanding.

Importing a file that is not in the configuration #

--file PATH archives a file named on the command line, with --name, --variant, --tag, --recipient and --no-lock beside it. The configuration is still read, for the archive's URL and its token, but it need name no mailboxes at all.

$ atm-mbox archive --file ~/old-spool.mbox --name archive/2009 \
    --variant mboxcl2 --recipient jeff@example.com

Exit status #

0 everything asked for was done
1 something failed, and the next run may well clear it

Two, and not the three the sibling programs have. Their third is for a mailbox whose OAuth grant has expired, which is the one failure no later run can fix without a person; here the only credential is the archive's, and there is nothing between this program and a file to refuse it.

A message that keeps failing stops being retried after max_attempts, so one message the archive will never take does not make every future run busy and noisy; status lists it with the byte offset it is at, and retry clears it.

Building it #

It needs Zig 0.17.0. The development shell and the Nix package take it from nixpkgs, as zig_0_17.

$ nix develop
$ zig build test --summary all
$ zig build
$ zig build fuzz-run -- --iterations 100000
$ zig build fuzz --fuzz             # Zig's fuzzer, with coverage feedback

For Zig 0.16.0, use the zig-0.16 branch or the v0.1.0 tag, which hold the last of this program to build with it.

Or as a package:

$ nix build
$ ./result/bin/atm-mbox 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 an allthemail up on a loopback socket, writes real mailboxes into a temporary directory, and runs whole imports between them: a first pass, a second that sends nothing, a lost ledger, a message in two mailboxes, two identical messages in one file, a body whose quoting has to be undone before it is hashed, a bounce with no envelope sender, a dry run, a 503, a verdict on a message against a verdict on its tags, a file that is not a mailbox, an archive that ignores the property 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 mailboxes there are real, which is the difference between this and the same file in the sibling projects. They have to stand a fake Gmail or a fake Graph up because there is no way to have the real one in a test; an mbox is a file, so the only thing modelled here is the archive. 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.

tests/fuzz.zig holds the properties. The one that earns its keep is that every message the scanner yields out of any file at all becomes a submission the archive would accept — a hashable body, a tag it will take, properties it will take — because a submission the archive refuses is a 400 for the whole request and therefore a message lost rather than a tag lost. An mbox is the format where that matters most: it has no checksum, no length field and no version, so a damaged mailbox is byte-for-byte indistinguishable from a strange one, and nobody exports an mbox that was not already years old. The loop found two real gaps while this was being written — a property prefix with a control character in it, and a path with no basename at all.

tests/nixos/roundtrip.nix is the other kind of test: a real atm with a real notmuch database, the real atm-mbox binary, and real HTTP between them. It runs as a flake check, because it needs a machine rather than a process:

$ nix flake check

It is there for claims that are 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 a mailbox of bare LFs is what would catch; that the quoting really was undone before the bytes were hashed, which only the stored file can show; that a name survives as a tag, comma and non-ASCII included; that the postmark arrives as properties and a bounce records no envelope sender; and that a message in two mailboxes ends up as one file carrying both tags.

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 a 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 is Zig's own fuzzer, which steers by coverage; the fuzz test binary is compiled with LLVM because the self-hosted backend that Debug uses by default emits no coverage instrumentation, and without it the fuzzer has nothing to steer by. zig build fuzz-run is tools/fuzz.zig, a loop of our own that drives the same targets from a corpus of seeds, with no coverage feedback and a fixed seed, so that a run is the same on every machine; that is the one the workflow runs.

What is deliberately not here #

  • Delivery. This reads mailboxes; it never writes one. Point it at an export, an archive, or a spool that has been moved aside — not at a file something is still delivering into, because a shared flock does not stop an MDA that does not take one.
  • Removing messages from the mailbox. An import that emptied the file as it went would be the one operation with no way back. zig-mbox's filter does it, deliberately, somewhere else.
  • Detecting the variant. Nothing in an mbox says which one it is, and a guess that is wrong corrupts every body it touches.
  • A timer. See the top of the file.
  • Maildir, MH, mbx. Other formats.

Licence #

MIT. The project follows REUSE; reuse lint passes.

References cited #

  • Hall, E. The application/mbox Media Type. RFC 4155. Internet Engineering Task Force, September 2005. Informational. https://www.rfc-editor.org/info/rfc4155. The nearest thing the mbox format has to a specification — it is explicitly a description of what exists rather than a standard — and the source of the account of the postmark and of why an mbox has no framing but a blank line.
  • Resnick, P., ed. Internet Message Format. RFC 5322. Internet Engineering Task Force, October 2008. Draft Standard, updated by RFC 6854. https://www.rfc-editor.org/info/rfc5322. What the bytes between two postmarks are, and what this program hands the archive unchanged.
  • Notmuch contributors. notmuch-properties(7) — Message property API. Notmuch Documentation, version 0.40. https://notmuchmail.org/doc/latest/man7/notmuch-properties.html. That a property is a key/value pair in the index rather than in the message, that one key may carry several values — which is what makes mbox.source answerable for a message found in two mailboxes — and the request that an extension report the keys it uses so that the namespace does not collide.