Posts in 'foss'

Mailsift: Extracting structured data from email messages

As a casual user of Gmail, I find its ability to recognize when I’ve received tickets, invoices, and flight confirmations, and to display this information in a structured way, very useful. Flights appear directly in Google Calendar, parcel delivery statuses are tracked, and reservations are easy to find at a glance.

However, my main email address is not Gmail, and I don’t want to migrate to Gmail for a number of reasons (privacy, data sovereignty, vendor lock-in). At the same time, I missed having that automatic extraction: having flight and train bookings appear in my calendar without manual copy-pasting, keeping track of incoming parcels, and having invoices neatly organized.

JSON-LD and schema.org

There is an established standard format for structured data called JSON-LD, which is used by Google and other search engines to extract structured data from web pages. JSON-LD represents linked data using JSON, and it can be embedded directly in HTML documents.

Email messages can also contain structured data in the form of JSON-LD, which can link the information in the email to external data sources. There are standardized schemas for structured data in email messages, such as the schema.org vocabulary, which defines types and properties for describing entities including flight reservations, train trips, hotel bookings, parcel deliveries, and invoices.

For example, an email containing a flight reservation might embed the following JSON-LD snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
  "@context": "https://schema.org",
  "@type": "FlightReservation",
  "reservationNumber": "ABC123",
  "underName": {
    "@type": "Person",
    "name": "John Doe"
  },
  "reservationFor": {
    "@type": "Flight",
    "flightNumber": "AA123",
    "departureAirport": {
      "@type": "Airport",
      "name": "John F. Kennedy International Airport"
    },
    "arrivalAirport": {
      "@type": "Airport",
      "name": "Los Angeles International Airport"
    },
    "departureTime": "2026-11-01T10:00:00-05:00",
    "arrivalTime": "2026-11-01T13:00:00-08:00"
  }
}

When this is present, reading email data is clean and straightforward. The reality, however, is that only a fraction of vendors actually include schema.org markup in their emails. Most airlines, train operators, couriers, and web shops still send regular HTML or plain-text messages with arbitrary layouts that change over time.

Mailsift

To bridge this gap on my own infrastructure, I built mailsift. Written in Rust, it is a daemon and CLI tool that monitors incoming email, extracts structured information, and routes it to standard files and services.

Rather than locking data into an internal database, mailsift embraces the Unix philosophy: it delegates extraction to small, isolated programs and files the resulting structured artifacts into standard formats and protocols:

  • Calendar events & reservations: Turned into iCalendar (.ics) events and pushed directly to a CalDAV server (such as Xandikos) or stored in a local directory.
  • Bills & invoices: Extracted as structured JSON records, organized by year, and optionally synced to a personal finance manager like Firefly III.
  • Parcels: Extracted as delivery records keyed by tracking number, merged across status update emails, and optionally registered with tracking APIs like 17track or Karrio.
  • Tickets & boarding passes: Saved as PDFs, Apple Wallet passes (.pkpass), or images, accompanied by JSON metadata sidecars linking them to the booking.
  • Receipts & orders: Filed as JSON records, synced over WebDAV, or forwarded via email.

How extractors work

Mailsift decouples the pipeline that handles emails from the logic that parses individual vendors. It discovers extractors from a directory of manifests.

The contract between mailsift and an extractor is deliberately simple:

  • Input: The raw RFC822 message is fed to the extractor on stdin.
  • Execution: The extractor runs in a fresh, temporary working directory, with a strict timeout (typically 10 seconds).
  • Output: The extractor writes zero or more named artifact files into its working directory and exits 0.

Extractors can be written in any programming language. In practice, most are small Python scripts that parse HTML with regexes or BeautifulSoup, using a small helper library (mailsift_extractor) that handles Unicode normalization and HTML body stripping.

Filtering and DKIM verification

Spawning a subprocess for every single email in an active inbox would be wasteful. Each extractor therefore has a YAML manifest declaring prefiltering criteria:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
name: easyjet
order: 50
from_domains:
  - easyjet.com
  - "*.easyjet.com"
subject_regex: "(?i)easyJet booking reference"
requires:
  - html
require_dkim:
  - easyjet.com

Before running an extractor, mailsift evaluates the message headers and MIME structure - possibly converting it to an IMAP filter. If the sender domain or subject doesn’t match, or the required MIME parts are missing, the extractor is skipped immediately.

Crucially, the manifest can also require a valid DKIM signature via require_dkim. Mailsift inspects the Authentication-Results: header produced by the receiving mail server. This guarantees that an extractor only processes messages that genuinely originated from the vendor’s domain, preventing forged emails from injecting fake calendar events or bills.

Generic vs. vendor extractors

Extractors fall into two categories:

  1. Generic extractors: schema-ld inspects the HTML for any <script type="application/ld+json"> blocks conforming to schema.org reservations. Another extractor, ics-passthrough, extracts standard iCalendar attachments.
  2. Vendor-specific extractors: For vendors that don’t include structured markup, dedicated extractors parse the message text. For instance, the easyjet extractor looks for booking references and flight tables, producing a standard FlightReservation artifact:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
reservation = {
    "@context": "https://schema.org",
    "@type": "FlightReservation",
    "reservationNumber": f"easyjet-{reference}-{flight_no}",
    "reservationFor": {
        "@type": "Flight",
        "flightNumber": flight_no,
        "departureAirport": {"@type": "Airport", "name": origin},
        "arrivalAirport": {"@type": "Airport", "name": dest},
        "departureTime": dep.isoformat(),
        "arrivalTime": arr.isoformat(),
    },
}
Path(f"{slug}.reservation.json").write_text(json.dumps(reservation))

The collection of extractors is maintained in a separate repository, mailsift-extractors, and currently includes nearly 60 extractors covering airlines (British Airways, KLM, EasyJet, Transavia, Eurostar), transport (NS, SNCF Connect, FlixBus), package carriers (Royal Mail, DPD, DHL, UPS, Evri, PostNL), online orders, and utility bills.

Handling forwarded mail

In real life, travel bookings or receipts are often forwarded by family, friends, or colleagues. By default, forwarded mail would fail sender checks, and DKIM signatures on inline forwards are broken by mail clients.

Mailsift handles this via a trusted_forwarders configuration. When an email arrives from a trusted forwarder, mailsift unwraps the forwarded message:

  • Attachment forwards: If the original email was attached as message/rfc822, mailsift extracts the original message and re-evaluates the vendor’s DKIM signature on the inner message.
  • Inline forwards: Mailsift reconstructs a synthetic RFC822 message from the client’s forwarded quotation header block and quotes, deriving a deterministic Message-ID.

This means hotel confirmations or flight tickets forwarded by a partner still end up in the family calendar automatically.

Running mailsift

Mailsift fits into existing email setups in several ways:

Dovecot Sieve

For local delivery, Sieve provides an elegant integration using the sieve_extprograms plugin. Because Sieve runs during local delivery after Dovecot has validated DKIM and added Authentication-Results:, require_dkim checks work as expected:

1
2
require ["vnd.dovecot.pipe"];
pipe :copy "mailsift";

The :copy flag ensures the email continues to the user’s inbox while a copy is piped through mailsift.

IMAP watching

If you don’t run your own mail server, or want to process mail on an existing remote mailbox, imap-scan connects over IMAP:

$ mailsift imap-scan imaps://[email protected]/INBOX \
    --password-file ~/.config/mailsift/imap.pass \
    --watch

With --watch, mailsift uses IMAP IDLE (RFC 2177) to wait for new messages and process them as they arrive. It supports standard passwords, Kerberos (SASL GSSAPI), and OAuth2 (XOAUTH2) for providers like Gmail and Microsoft 365 via an interactive mailsift imap-auth flow.

Other modes

  • Postfix Milter: mailsift milter runs as an MTA filter, processing messages in real-time as they pass through Postfix.
  • Maildir scan: mailsift maildir-scan walks an on-disk Maildir folder, useful for backfilling historical mail.
  • Replay: mailsift replay message.eml runs extractors on a single saved message file, which is invaluable when writing or testing an extractor.

Web UI and REST API

In addition to routing data to CalDAV and disk, mailsift includes an optional read-only web dashboard (mailsift web):

$ mailsift web --listen 127.0.0.1:8088

The dashboard provides an overview of upcoming trips, arriving packages, unpaid bills, and recent orders. It rescans the artifact directories on request, so it stays in sync with incoming mail without needing a separate database. JSON endpoints (such as /api/parcels.json or /api/bills.json) are also available for custom status scripts or home automation dashboards.

Status and getting involved

Mailsift has been running reliably on my mail server for over a year, and having flights, hotel bookings, and train journeys seamlessly sync into my calendar without relying on proprietary cloud services has been very satisfying.

The project is free software under the GPL-3.0:

Adding support for new vendors only requires writing a small YAML manifest and a Python script with a couple of regexes. If you have vendors you’d like to extract data from, contributions of new extractors are very welcome!

comments.

Inquest, a test result repository in Rust

testrepository

For a long time I’ve used Robert Collins’ testrepository (testr) to run tests in many of the projects I work on. It’s a small, focused tool built around a simple idea: decouple the running of tests from the recording and querying of their results.

The way it works is straightforward. A test runner emits a subunit stream — a compact binary protocol for test results — and testrepository stores those streams in a per-project .testrepository/ directory. Once results are in the repository, you can ask questions like “which tests failed in the last run?”, “re-run only the failures”, “what are the slowest tests?”, or “what changed between this run and the previous one?”.

The killer feature, for me, has always been the failing-test loop. When a big test suite breaks, you don’t want to re-run the whole thing after every fix — you want to iterate on just the failures, and only re-run the full suite once they’re all green. testrepository made that workflow ergonomic long before most language-specific test runners had anything comparable, and many of them still don’t have a good answer for it.

testrepository has served me well for over a decade, but it has been largely unmaintained for a while, and I had some ideas of improvements that I wanted to try out. So I wrote a Rust port, which has since grown a number of features of its own.

Inquest

Inquest is a Rust port of testrepository that has since grown a number of features of its own. The binary is called inq.

Goals

The goals are deliberately modest:

  • a single static binary, no Python runtime required
  • no need to write a dedicated config file for most projects
  • compatible enough with testrepository’s workflow that I can switch projects over without retraining my fingers
  • a richer on-disk format that captures more about each run (git commit, command line, duration, exit code, concurrency)
  • good support for the languages I actually use day-to-day: Rust, Python, Go, and Node.js
  • mostly Do What I Mean (DWIM), e.g. getting me to know as quickly as possible what tests are failing and why, and being clever about doing this

Inquest reads and writes subunit v2 streams, so anything that can produce subunit (directly or via one of the many converters) can feed into it.

Quick start

Inquest can usually figure out how to run your tests on its own. In a Rust, Python, Go or Node.js project:

 $ cd my-project
 $ inq

Or if the auto-detection doesn’t work, you can ask it to generate a config file and then run the tests:

 $ inq auto
 $ inq run

inq auto writes an inquest.toml describing how to invoke the test runner; inq run runs the tests, captures the subunit stream, and stores the results in a .inquest/ directory.

For a Rust project the generated config looks like:

 test_command = "cargo subunit $IDOPTION"
 test_id_option = "--test $IDFILE"
 test_list_option = "--list"

After the first run, the usual queries work:

 $ inq stats             # repository-wide statistics
 $ inq last              # results of the most recent run
 $ inq failing           # only the failing tests
 $ inq slowest           # the slowest tests in the last run
 $ inq run --failing     # re-run only what failed last time

The last one is the workflow I use most often: run the full suite once, fix the obvious failures, then iterate on inq run --failing until the list is empty.

A few things that aren’t in testrepository

Some of the features that have grown in inquest beyond the original testrepository functionality:

  • Timeouts. --test-timeout, --max-duration, and --no-output-timeout will kill a test process that is hanging or has stopped producing output. --test-timeout auto derives a per-test timeout from the historical duration of that test, which is handy for catching tests that hang.

    Once the test runner is killed, the test is marked as failed and the next test is started, so a broken test doesn’t hold up the whole suite.

  • Ordering --order can be used to run tests in a specific order, e.g. to run the slowest tests first, to run the tests that failed most recently first, or to run the widest variety of tests first to maximize the chance of finding a failure early on.

  • Live progress. inq running tails the in-progress subunit stream on disk and reports observed/expected test counts, percent complete, elapsed wall-clock time, and an ETA derived from each test’s historical duration. Useful when a CI run is taking longer than you’d like.

  • Flakiness ranking. inq flaky ranks tests by pass↔fail transitions in consecutive runs in which the test was recorded, so chronically broken tests rank low and genuinely flapping tests rank high.

  • Comparing runs. inq diff <A> <B> shows what changed between two test runs — newly failing, newly passing, and tests that flipped state — which makes it easy to see whether your last change actually fixed (or broke) anything.

  • Bisecting git history. inq bisect <TEST> drives git bisect to find the commit that broke a given test. It defaults the known-good and known-bad commits from the recorded run history (the most recent run where the test passed, and the most recent where it failed), so in the common case there is no need to remember either — just point it at the test name and let it work.

  • Richer run metadata. inq info shows the git commit, command line, duration, exit code, and concurrency for a run, with a flag for whether the working tree was dirty when the run started. Combined with inq diff this makes it much easier to triangulate when a regression was introduced.

  • Rerun a previous run verbatim. inq rerun <ID> re-runs exactly the tests of a previous run, in the same order, forwarding the same -- arguments that the original run used. inq rerun -1 repeats the latest.

  • Web based view. inq web serves a web-based view of the repository, with a dashboard of recent runs and detailed views of individual runs and tests.

Web UI

Most of the time I drive inquest from the command line, but for browsing historical results of a large suite — spotting flapping tests, drilling into a single test’s run history, or just getting a visual sense of which parts of the suite are hurting — a web view is more pleasant. inq web starts a local server with exactly that:

 $ inq web

The repository overview shows totals and a per-test history grid where each cell is one run, coloured by outcome. Bands of red make it easy to pick out tests that have been broken for a long time, and isolated red cells in an otherwise green column point at flaky tests.

Inquest web UI repository overview, with a grid of per-run results

Drilling into an individual test gives you its full run history, a duration sparkline, and per-run pass/fail status:

Inquest web UI per-test view with run history and duration sparkline

Migrating from testrepository

If you already have a .testrepository/ directory full of historical runs, inq upgrade will migrate it into the new .inquest/ format, with a progress bar for the impatient.

The legacy .testr.conf (INI) format is still understood, so existing projects don’t have to be converted to inquest.toml immediately — though the TOML format is preferred for new projects.

Trying it

The source is on GitHub at jelmer/inquest. To install from source:

 $ cargo install inquest

In a project with a Rust, Python, Go or Node.js test suite:

 $ inq

Bug reports and patches are welcome.

comments.

Xandikos, a lightweight Git-backed CalDAV/CardDAV server

For the last couple of years, I have self-hosted my calendar and address book data. Originally I just kept local calendars and address books in Evolution, but later I moved to a self-hosted CalDAV/CardDAV server and a plethora of clients.

CalDAV/CardDAV

CalDAV and CardDAV are standards for accessing, managing, and sharing calendaring and addressbook information based on the iCalendar format that are built atop the WebDAV standard, and WebDAV itself is a set of extensions to HTTP.

CalDAV and CardDAV essentially store iCalendar (.ics) and vCard (.vcf) files using WebDAV, but they provide some extra guarantees (e.g. files must be well-formed) and some additional methods for querying the data. For example, it is possible to retrieve all events between two dates with a single HTTP query, rather than the client having to check all the calendar files in a directory.

CalDAV and CardDAV are (unnecessarily) complex, in large part because they are built on top of WebDAV. Being able to use regular HTTP and WebDAV clients is quite neat, but results in extra complexity. In addition, because the standards are so large, clients and servers end up only implementing parts of it.

However, CalDAV and CardDAV have one big redeeming quality: they are the dominant standards for synchronising calendar events and addressbooks, and are supported by a wide variety of free and non-free applications. They’re the status quo, until something better comes along. (and hey, at least there is a standard to begin with)

Calypso

I have tried a number of servers over the years. In the end, I settled for calypso.

Calypso started out as friendly fork of Radicale, with some additional improvements. I like Calypso because it is:

  • quite simple, understandable, and small (sloccount reports 1700 LOC)
  • it stores plain .vcf and .ics files
  • stores history in git
  • easy to set up, e.g. no database dependencies
  • written in Python

Its use of regular files and keeping history in Git is useful, because this means that whenever it breaks it is much easier to see what is happening. If something were to go wrong (i.e. a client decides to remove all server-side entries) it’s easy to recover by rolling back history using git.

However, there are some downsides to Calypso as well.

It doesn’t have good test coverage, making it harder to change (especially in a way that doesn’t break some clients), though there are some recent efforts to make e.g. external spec compliance tests like caldavtester work with it.

Calypso’s CalDAV/CardDAV/WebDAV implementation is a bit ad-hoc. The only WebDAV REPORTs it implements are calendar-multiget and addressbook-multiget. Support for properties has been added as new clients request them. The logic for replying to DAV requests is mixed with the actual data store implementation.

Because of this, it can be hard to get going with some clients and sometimes tricky to debug.

Xandikos

After attempting to fix a number of issues in Calypso, I kept running into issues with the way its code is structured. This is only fixable by rewriting sigifnicant chunks of it, so I opted to instead write a new server.

The goals of Xandikos are along the same lines as those of Calypso, to be a simple CalDAV/CardDAV server for personal use:

  • easy to set up; at the moment, just running xandikos -d $HOME/dav —defaults is enough to start a new server
  • use of plain .ics/.ivf files for storage
  • history stored in Git

But additionally:

  • clear separation between protocol implementation and storage
  • be well tested
  • standards complete
  • standards compliant

Current status

The CalDAV/CardDAV implementation of Xandikos is mostly complete, but there still a number of outstanding issues.

In particular:

  • lack of authentication support; setting up authentication support in uwsgi or a reverse proxy is one way of working around this
  • there is no useful UI for users accessing the DAV resources via a web browser
  • test coverage

Xandikos has been tested with the following clients:

Trying it

To run Xandikos, follow the instructions on the homepage:

1
./bin/xandikos --defaults -d $HOME/dav

A server should now be listening on localhost:8080 that you can access with your favorite client.

comments.

Kiln using Dulwich

http://blog.fogcreek.com/kiln-harmony-internals-the-basics/

Nice to see that #Kiln is also using #Dulwich for some of its Git support. Unfortunately I haven’t been able to spend as much time on it recently as it deserves (busy changing jobs and countries), but hopefully that will change soon.

comments.