---
title: Email Footers on Autopilot
date: '2026-11-08'
description: 'The end of a work email has several authors who never meet. How Mailingest lets rules pick its footers, in the reader''s language, in order.'
author: Pablo Fernandez
tags:
  - Email
  - Rust
  - Signatures
  - A/B Testing
  - Language Detection
  - Mailingest
source: 'https://www.pablofr.com/blog/email-footers-that-pick-themselves'
---
Scroll to the bottom of any work email and count the authors. The sender wrote their name and phone number. Someone in the department added a team line above the company's address. Legal wrote the confidentiality paragraph. The mail provider put its own line at the very end. None of these people saw the others' text, and nobody chose the order. Each one pasted a block and hoped.

When I built footers into [Mailingest](/blog/giving-an-inbox-to-each-agent), my mail platform, that pile was the problem to solve. The server adds the footers, so the sender doesn't have to remember anything. But then the server has to answer what the person used to answer by instinct: for this message, from this sender, to these recipients, which blocks go at the end, in which order, and in which language?

## Three layers, then four

The first design, on October 15, fixed the order before anything else. Three layers, each written in both HTML and plain text, always in this sequence: the sender's signature, then the system's notices, then the platform's footer, always last.

The signature layer is itself a stack. A mailbox has its own signature, each group it belongs to can add one, its domain can add one, and the organization can add one at the bottom. The most specific goes on top, so "Ana García, Sales Director" sits above "Sales team" which sits above "ACME Iberia". Notices are not chosen by the sender at all: they are what the processing has to say about this message, such as attachments that were removed, the recipient's own unsubscribe link, or the [traceable, secure email](/blog/proving-an-email-is-genuine) notice on sealed mail. The platform footer is Mailingest's line, and an organization can only remove it if its plan allows.

Two weeks in, the three layers weren't enough. An organization couldn't have both a confidentiality paragraph and an environmental line, because the signature layer allows one template per level and the first rule that holds wins. The fix on October 28 was a fourth layer between signatures and notices, the organization's footers, where nothing replaces anything: every rule that holds places its template, stacked by priority. The platform offers a library of them in 28 languages, and the confidentiality one now comes in eight families by country, each citing its own law. The same day the message also gained a header layer at its top, which the organization stacks the same way, with its logo for example.

```
  message body
  -- 
  ┌─────────────────────────────────────────────────────┐
  │ 1. signatures      mailbox   Ana García · Sales     │
  │    (stacked)       group     Sales team             │
  │                    domain    ACME Iberia            │
  │                    org       ACME Corp              │
  ├─────────────────────────────────────────────────────┤
  │ 2. org footers     confidentiality, eco line, ...   │
  ├─────────────────────────────────────────────────────┤
  │ 3. notices         2 attachments removed, sealed    │
  ├─────────────────────────────────────────────────────┤
  │ 4. platform        Mailingest's line, always last   │
  └─────────────────────────────────────────────────────┘
```

*The end of a message, top to bottom: the sender's stacked signatures, the organization's footers, the system's notices, and the platform's line.*

In the text part, the blocks follow the `-- ` line (dash, dash, space) from [RFC 3676](https://www.rfc-editor.org/rfc/rfc3676.html#section-4.3), which mail clients already treat as the start of a signature. In HTML, each block goes in its own `<div>` before `</body>`, sanitized with [ammonia](https://github.com/rust-ammonia/ammonia) as it's composed, never trusted when it's saved. A test sends all 583 library templates, every language included, through the renderer and the sanitizer and checks that every inline style, image and link comes out whole. Mail that is signed or encrypted by the client is never touched, because changing it breaks the signature.

One early decision didn't survive. The design said that if a message has only a text body, the footers go in as text and no HTML body is created. Then Apple Mail turned out to send unformatted messages as `text/plain` alone, and a signature designed with a photo and a layout arrived as a few lines of text. Since November 8, a message with a single text body gets an HTML version made from it, paragraphs kept, so the signature shows as it was designed.

## Rules borrowed from Exchange

Who decides which signature a mailbox gets, or whether replies carry the full footer? I looked at how others do it before writing anything. Microsoft's [mail flow rules](https://learn.microsoft.com/en-us/exchange/security-and-compliance/mail-flow-rules/manage-mail-flow-rules) in Exchange were the closest fit: each rule has conditions and a priority, one of its actions is to [apply a disclaimer](https://learn.microsoft.com/en-us/exchange/security-and-compliance/mail-flow-rules/disclaimers-signatures-footers-or-headers), and it can stop the rules after it from running. Signature products like [Exclaimer](https://exclaimer.com/) add [scheduled campaign banners](https://exclaimer.com/product/campaigns/) on top. Mailingest took the first model whole and left campaigns for a second phase.

A template is content with no scope. A rule says where and when it applies:

- **Conditions:** a glob on the sender's address (`ventas-*@acme.test`), whether the recipients are internal or external, specific recipient domains, new message or reply, and a tag the API can send. An unset condition always holds.
- **Action:** a template, or nothing at all, which leaves the level empty on purpose.
- **Order:** a priority, lower first, then the rule's id so the result is the same every time.
- **`stop`:** on by default. The first rule that holds decides the level.
- **`suppress_below`:** a department signature can replace the company one instead of stacking over it.

A level's default template is just a rule with no conditions and a large priority number, so it needs no concept of its own. Within each level, the choice is this:

```rust:crates/mail/src/footer.rs
fn choose_ordered<'a>(
    rules: impl Iterator<Item = &'a FooterRule>,
    facts: &Facts<'_>,
) -> Option<&'a FooterRule> {
    let candidates: Vec<&FooterRule> = rules.filter(|r| r.enabled && applies(r, facts)).collect();
    let first = candidates
        .iter()
        .position(|r| r.template_id.is_some() || r.stop)?;
    let found = candidates[first];
    if found.weight.is_none() {
        return Some(found);
    }
    // ...weighted rules: the A/B group, below
```

The first rule that holds and either places a template or has `stop` wins. An empty rule without `stop` lets the search continue, which is how you write "no special signature for this case, keep looking". The whole resolution is a pure function of the organization's rules and the message's context, so it's tested without a database, and the rules of each organization are cached in memory for 30 seconds: composing a footer can't cost a query per message.

```
  level        rules, by priority             result
  ─────────    ───────────────────────────    ──────────────────
  mailbox      first that holds wins     ──▶  Ana García · Sales
  group        one level per group       ──▶  Sales team
  domain       subdomain, then parents   ──▶  ACME Iberia, suppress_below
  org          not reached               ──▶  ·
```

*Each signature level picks at most one template with its rules; a level with suppress_below stops the levels under it from stacking.*

The API can override one thing per message. `footer.signature` with a template id replaces only the mailbox level, and the groups, domain and organization still stack under it. `footer.signature: false` drops the whole signature layer, which is what transactional mail wants.

The organization's footers have the opposite problem: since they stack, nothing stopped the same footer from being turned on twice. The same template turned on for the whole organization and again for one domain was placed twice in that domain's mail. Since October 30, a template turned on at several scopes is placed once, by the most specific one, with that scope's parameters.

## Campaigns and a coin that always lands the same

The second phase, on October 18, added time and chance. A rule can carry `starts_at` and `ends_at`. Outside that window it doesn't exist for the resolution, and the next rule is tried as if its conditions had failed. The window is checked per message, against the moment the message is composed, so a campaign starts and ends on the second even though the rules are cached; only an edit to a rule takes up to 30 seconds to show. The holiday closure footer uses this directly: give it the dates of the closure and the rule computes its own window, starting some days before so people see it coming.

A/B testing is a weight on the rule, from 1 to 10,000. When the first rule that holds has a weight, it stands for its group: every weighted rule at the same level and priority whose conditions hold for this message. One is picked with odds proportional to its weight. The pick is a hash, not a random number:

```rust:crates/mail/src/footer.rs /seed/
fn pick_variant<'a>(group: &[&'a FooterRule], seed: Uuid) -> &'a FooterRule {
    let total: u64 = group
        .iter()
        .map(|r| r.weight.unwrap_or(1).max(1) as u64)
        .sum();
    // FNV-1a over the seed and the group's first id, then the SplitMix64
    // finalizer so close seeds (UUIDv7 share their leading bytes) spread out.
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for byte in seed.as_bytes().iter().chain(group[0].id.as_bytes()) {
        h ^= u64::from(*byte);
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h = (h ^ (h >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    h = (h ^ (h >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    h ^= h >> 31;
    let mut point = h % total;
    // ...walk the group until point falls inside a variant's weight
```

The seed is the email's id. A retry, or the personalized copy each recipient of a newsletter gets, lands on the same variant, and every replica of the delivery service agrees, which is why the hash is written out instead of taken from Rust's standard library, whose output can change between builds. Each group hashes with its own first id, so the variant picked for the signature says nothing about the one picked for the platform footer. A variant with no template is allowed: it's the control group, and its sends count too.

The counting stays off Postgres. When a message goes out, delivery adds its recipients to a per-day Redis hash for each variant it carried, with a `SET NX` marker per email so a partial retry doesn't count twice: two Redis operations per email, and only for email that carries a variant. A task copies the totals to Postgres every five minutes, and the copy only ever raises a day's number. What it counts is sends per variant per day, and that's all. Bounces and complaints aren't attributed to variants, and opens and clicks aren't joined to them either, so today the A/B tells you each variant went out to the share you asked for, not which one did better.

## The reader's language, not the sender's

The library is in 28 languages, which raises the question the person at the keyboard never had to answer: which one? A Spanish company writing to a client in English shouldn't end the message with a Spanish confidentiality paragraph. The order, since October 29:

```rust:crates/classify/src/language.rs
if let Some(lang) = explicit(message) {
    return (lang, LanguageSource::Explicit);
}
let user = preference.language.map(|l| (l, LanguageSource::User));
if let (Some(user), false) = (user, preference.auto) {
    return user;
}
if let Some(lang) = detected(message) {
    return (lang, LanguageSource::Detected);
}
if let Some(user) = user {
    return user;
}
match domain_language {
    Some(lang) => (lang, LanguageSource::Domain),
    None => (Lang::FALLBACK, LanguageSource::Default),
}
```

What the message declares comes first (`Content-Language`, or the `lang` of its `<html>`). Then what it's written in. Then the sender's language: the address's setting, else the organization's, else the language they use the website in. Then the domain's, then English. The first version put the sender's language ahead of detection; about twenty minutes later I flipped the default, so the sender's language is the fallback for text too short to tell. Only a sender who fixes a language explicitly puts it first.

Detecting the language of an email is mostly deciding which words to ignore. A reply in English that quotes three paragraphs of Spanish is an English email. So before anything is detected, the detector strips what the sender didn't write: lines starting with `>`, the "On … wrote:" line (31 attribution verbs across languages) and everything after it, forwarded blocks, Outlook's quoted headers, the signature after `-- ` or after a sign-off alone on its line ("Saludos,", "Best regards", 52 of them), "Sent from my iPhone", and every URL, address, word with digits and word in capitals. One of the tests:

```rust:crates/classify/src/language.rs
let reply = "Thanks, we will check it today.\n\nOn Tue, 27 Oct 2026 at 10:14, Carlos <c@x.test> wrote:\n> Hola, el pedido no ha llegado.\n> Un saludo";
assert_eq!(own_words(reply).trim(), "Thanks, we will check it today.");
```

What's left is cut into segments of whole sentences, at least 60 letters each and at most 300 characters. A short text is read whole. A long one is read at its first, middle and last segments, plus three more picked by a xorshift seeded with the text's FNV-1a hash, so the same message reads the same way on every retry. Each segment votes with its letters times the detector's confidence, the subject at half weight, and a language wins with 60% of the weight, a mean confidence of at least 0.2, and at least 20 letters and four words. One clear sentence is enough. "Hola, gracias" is not, and falls through to the sender's language.

```
  body ──▶ own words ──▶ segments ──▶ vote ──▶ language
             │             │            │
             │             │            └─ ≥ 60% of the weight, else fall back
             │             └─ first, middle, last + 3 seeded picks
             └─ no quotes, no signature, no URLs, no codes
```

*Detection reads only the sender's own words, samples whole sentences from across the text, and falls back when the vote isn't clear.*

The detector is [whatlang](https://github.com/greyblake/whatlang-rs). I measured it against [lingua](https://github.com/pemistahl/lingua-rs), which is more accurate on a sentence alone, with the same cleaning, sampling and vote in front of both, on a corpus of 41 emails and 148 single sentences in 28 languages. It was on an M-series Mac under heavy load from other builds (load average between 12 and 149), so the absolute times are pessimistic and the ratios are what count:

| Detector, with the same pipeline | 41 emails right | 148 sentences: right / undecided / wrong | CPU per message | Memory per process |
|---|---|---|---|---|
| whatlang | 41 | 128 / 18 / 2 | about 41 µs | +2 MB |
| lingua, low accuracy | 40 | 142 / 3 / 3 | about 380 µs | +110 MB |
| lingua, high accuracy | 41 | 143 / 3 / 2 | about 630 µs | +114 MB |

Lingua decides more sentences, but an undecided sentence isn't an error, it falls back to the sender's language. Both make two mistakes in 148, and whatlang's are Danish read as Norwegian on a sentence that is the same in both, and a five-word Russian sentence read as Ukrainian. Lingua would cost 9 to 15 times the CPU, over 100 MB more in every process that classifies mail, and 150 MB of models in the binary. The 0.2 confidence threshold came from the same run: at 0 there were 10 wrong sentences, at 0.15 five, at 0.2 two.

Mail coming in to temporary inboxes uses the same detection but never the account's language, since the person reading it isn't the account.

## A word that takes it off

The last piece is for the person who wants none of it, just this once: a reply to a friend from a work address, a one-line "thanks" that doesn't need a legal paragraph. It isn't shipped yet. It's on the branch I'm working on today, not on `main`.

The sender writes a word in the message. `!nopie` leaves the organization's footers off, `!nofirma` the signature, `!nocabecera` the header block at the top, and `!nada` all three. The defaults are Spanish words; each address can list up to five words of its own per layer instead, or none. The word is removed from the message before it's signed, along with the line or paragraph it leaves empty, and nobody can use it until an administrator turns it on for the organization or for a domain. Until then, `!nopie` is text like any other.

The first version this morning only counted the word as the last thing the sender wrote. Twenty-eight minutes later it counted anywhere in the sender's own text, as a whole word in any case, because people don't put it where you'd expect. What "own text" means is the same lesson as the language detection: a reply that quotes an old message carrying a word must not lose its footers because of it.

```rust:crates/mail/src/opt_out.rs
let reply = "Vale !nofirma\n\nEl lunes, Ana escribió:\n> !nopie\n";
let (text, off) = strip_text(reply, &words());
assert_eq!(text, "Vale\n\nEl lunes, Ana escribió:\n> !nopie\n");
assert_eq!(off, ONLY_SIGNATURE);
```

The `!nofirma` the sender typed goes, and the signature with it. The `!nopie` inside Ana's quoted message stays exactly where it was and counts for nothing. In HTML the same reading stops at a `<blockquote>`, Gmail's quote block or Outlook's reply header.

```
  word          header   signature   org footers   notices   platform
  ──────────    ──────   ─────────   ───────────   ───────   ────────
  !nocabecera   off      ·           ·             always    always
  !nofirma      ·        off         ·             always    always
  !nopie        ·        ·           off           always    always
  !nada         off      off         off           always    always
```

*A word removes only the layers the sender's organization controls; notices and the platform footer always stay.*

The notices and the platform's footer stay whatever the message says. The word reaches only what the sender's own organization put there. The attachments notice and the unsubscribe link aren't the organization's to remove. The word is read where the footers are composed, so a message sent through the API, one submitted over SMTP from a mail client and the footer preview all behave the same way.

## What the person used to decide

Put the pieces back together and they're the decisions a careful person made by hand at the bottom of every email: which of my signatures fits this reply, whether this client needs the legal text, which language they read, whether this one should just say thanks. Each became a rule, a priority, a vote or a word, evaluated per message from a cache, with no database query. The cost is that the decisions now live somewhere the sender can't see while typing, which is why the preview, the endpoint that shows exactly what a message will end with and which rule placed each block, mattered more than any one rule. A rule system you can't preview is just a footer that changes on its own.
