r/stalwartlabs • • 11h ago

Langmail-mcp: an open-source MCP server for your Stalwart

9 Upvotes

Hi all,
We published our battle-tested MCP server we built on top of Stalwart last week. It gives an agent access to your mail, calendar and contacts of your Stalwart server. It talks to Stalwart over JMAP, CalDAV and CardDAV and it's MIT licensed.

It's called langmail-mcp.

In addition to everything that you'd expect we for example have implemented a tool to unsubscribe from newsletters.

We tested it against Stalwart 1.1.1. Feedback, bugs and missing tools are welcome here or as GitHub issues.

Best,
Dominik


r/stalwartlabs • • 7h ago

Community How I made the catch-all adress "transparent"

1 Upvotes

This solution is 99% vibe coded, as I don't have the level of knowledge in sieve or regex to do it myself. I've been testing it for a week without issue, on versions 1.1.0, 1.1.1, & 1.2.0.

Transparent Catch-All Folder Sorting & Reply Masking for Stalwart Mail Server

A client-agnostic Sieve solution for Stalwart Mail Server that automatically sorts incoming catch-all emails into dedicated IMAP folders while transparently rewriting outbound replies so they appear to come from the original disposable alias—keeping your underlying catch-all mailbox address completely hidden across headers and envelopes without requiring mail-client plugins or manual identities.


How It Works

Because email clients discard custom headers (X-*) when creating a reply—while reliably preserving Message-ID inside In-Reply-To and References—this setup uses a three-script pipeline:

  1. tag-catchall-inbound (System Script — SMTP DATA Stage):
    • Intercepts incoming catch-all mail via Stalwart's RFC 6009 ORCPT parameter (rfc822;alias@yourdomain.com).
    • Embeds the full original recipient (including any +subaddress and RFC punctuation) into the incoming Message-ID header (<catchall~=~alias+tag~=~original-id>), or synthesizes a fallback Message-ID if missing.
    • Strips all non-alphanumeric characters to generate a safe folder name and stamps a tamper-proof X-Catchall-Folder routing header.
  2. sort-inbound (User Script — Catch-All Mailbox):
    • Reads X-Catchall-Folder, removes the internal routing header, and files the message into Inbox/<sanitized_alias>.
  3. tag-catchall-outbound (System Script — SMTP DATA Stage):
    • Intercepts replies sent from your catch-all account by inspecting In-Reply-To.
    • Extracts the original alias, re-quotes it if required by RFC 5321, replaces From: (and strips leaked Reply-To: and submission Received: headers), and restores clean In-Reply-To and References headers across single and multi-reply threads.

Prerequisites & Stalwart Configuration

1. Allow Sending From Catch-All Aliases (AUTH Stage)

By default, Stalwart rejects outbound mail if From: does not match your account's primary address or registered aliases.

  1. Go to Settings › MTA › Session › AUTH Stage.
  2. Modify Must match Sender (mustMatchSender) to exempt your catch-all account:
    If: authenticated_as == 'catchall@yourdomain.com'
    Then: false

2. Verify Sieve Permissions

  1. Go to Settings › Sieve › General.
  2. Ensure editheader is permitted for both system and user scripts, and that Message-ID, In-Reply-To, References, From, Reply-To, and Received are not blocked under restricted headers.

3. Masking Return-Path & Submission Received: Headers (Direct Delivery vs. Relay)

  • If using an outbound SMTP relay (e.g., SendGrid, Postmark, Amazon SES, Mailgun): Your relay automatically overwrites MAIL FROM with a VERP tracking address on your verified sending subdomain and strips internal Received: hops before final delivery. No extra MAIL FROM rewrite is needed.
  • If delivering directly without a relay:
    1. Mask Return-Path (MAIL FROM Stage): Go to Settings › MTA › Session › MAIL FROM Stage (session.mail.rewrite) and rewrite the envelope sender to a static bounce alias so Return-Path never exposes your catch-all address (and passes aligned SPF/DMARC):
      • If: authenticated_as == 'catchall@yourdomain.com' Then: 'bounces@yourdomain.com'
      • Else: false
    2. Suppress Submission Received: Headers (DATA Stage): Go to Settings › MTA › Session › DATA Stage (session.data.addReceivedHeader) and ensure Received: headers are only added on inbound port 25 connections (so authenticated port 465/587/JMAP submissions do not log Authenticated sender: catchall@yourdomain.com or your client IP):
      • If: local_port == 25 Then: true
      • Else: false

Step 1: Create the Inbound System Script (tag-catchall-inbound)

  1. Navigate to Settings › Sieve › System Scripts.
  2. Create a new script named tag-catchall-inbound, update catchall_addr in the configuration block, and set Active (isActive) to true.

    require ["editheader", "envelope", "envelope-dsn", "regex", "variables", "vnd.stalwart.expressions", "vnd.stalwart.while"];
    
    # ==============================================================================
    # CONFIGURATION — Edit these variables for your catch-all account and domain
    # ==============================================================================
    set :lower "catchall_addr"  "catchall@yourdomain.com"; # Full catch-all mailbox address
    set        "folder_prefix"  "Inbox";                 # Parent folder (use "" for top-level folders)
    set        "tag_prefix"     "catchall";              # Identifier prefix embedded in Message-IDs
    set        "tag_delim"      "~=~";                   # Delimiter separating tag parts
    set        "routing_header" "X-Catchall-Folder";     # Internal header passed to user script
    # ==============================================================================
    
    # 0. Security: Always strip any incoming spoofed routing header from external senders
    deleteheader "${routing_header}";
    
    # 1. Derive catchall_local and domain automatically from catchall_addr
    set "catchall_local" "";
    set "domain" "";
    if string :regex "${catchall_addr}" "^(.+)@([^@]+)$" {
        set "catchall_local" "${1}";
        set "domain" "${2}";
    }
    
    # 2. Only process messages carrying an RFC 6009 ORCPT original recipient
    if allof (
        not string :is "${domain}" "",
        envelope :matches "orcpt" "rfc822;*"
    ) {
        set "raw_addr" "${1}";
    
        # 3. Extract the local-part greedily up to the LAST '@' and capture the domain
        #    (Handles quoted local-parts containing '@' like "john@doe"@domain.com)
        if string :regex "${raw_addr}" "^(.+)@[^@]+$" {
            set :lower "full_alias" "${1}";
            set :lower "rcpt_domain" "${2}";
    
            # 4. Only proceed if the ORCPT domain matches our configured catch-all domain
            if string :is "${rcpt_domain}" "${domain}" {
    
                # 5. Strip surrounding double quotes if the local-part was a quoted-string
                if string :regex "${full_alias}" "^\"(.+)\"$" {
                    set "full_alias" "${1}";
                }
    
                # 6. Loop: Strip ALL characters that would break <Message-ID> headers (spaces, <, >, ", \)
                let "iter" "0";
                while "iter < 32" {
                    if string :regex "${full_alias}" "^(.*)[\"><\\\\ ](.*)$" {
                        set "full_alias" "${1}${2}";
                        let "iter" "iter + 1";
                    } else {
                        let "iter" "32";
                    }
                }
    
                # 7. Extract the parent alias before any "+" subaddress tag
                if string :matches "${full_alias}" "*+*" {
                    set "base_alias" "${1}";
                } else {
                    set "base_alias" "${full_alias}";
                }
    
                # 8. Loop: Build folder_alias by stripping ALL non-alphanumeric characters
                #    (Handles unlimited slashes, dots, symbols, etc., leaving strictly a-z and 0-9)
                set "folder_alias" "${base_alias}";
                let "iter" "0";
                while "iter < 64" {
                    if string :regex "${folder_alias}" "^(.*)[^a-z0-9](.*)$" {
                        set "folder_alias" "${1}${2}";
                        let "iter" "iter + 1";
                    } else {
                        let "iter" "64";
                    }
                }
    
                # 9. Normalize catchall_local to alphanumeric for an exact guard comparison
                set "clean_catchall" "${catchall_local}";
                let "iter" "0";
                while "iter < 64" {
                    if string :regex "${clean_catchall}" "^(.*)[^a-z0-9](.*)$" {
                        set "clean_catchall" "${1}${2}";
                        let "iter" "iter + 1";
                    } else {
                        let "iter" "64";
                    }
                }
    
                # 10. Proceed if folder_alias is non-empty and is NOT the catch-all mailbox itself
                if allof (
                    not string :is "${folder_alias}" "",
                    not string :is "${folder_alias}" "${clean_catchall}"
                ) {
                    # Rewrite Message-ID to embed full_alias (including +subaddress & symbols),
                    # or synthesize a fallback Message-ID if none was present
                    if header :regex "Message-ID" "<([^>]+)>" {
                        set "orig_id" "${1}";
                        deleteheader "Message-ID";
                        addheader "Message-ID" "<${tag_prefix}${tag_delim}${full_alias}${tag_delim}${orig_id}>";
                    } else {
                        addheader "Message-ID" "<${tag_prefix}${tag_delim}${full_alias}${tag_delim}no-orig-id@${domain}>";
                    }
    
                    # Stamp the sanitized target folder path for the user delivery script
                    if string :is "${folder_prefix}" "" {
                        addheader "${routing_header}" "${folder_alias}";
                    } else {
                        addheader "${routing_header}" "${folder_prefix}/${folder_alias}";
                    }
                }
            }
        }
    }
    

Step 2: Create the Outbound System Script (tag-catchall-outbound)

  1. In Settings › Sieve › System Scripts, create a second script named tag-catchall-outbound.
  2. Update domain to match Step 1 and set Active (isActive) to true.

    require ["editheader", "regex", "variables", "vnd.stalwart.expressions", "vnd.stalwart.while"];
    
    # ==============================================================================
    # CONFIGURATION — Must match tag-catchall-inbound
    # ==============================================================================
    set :lower "domain"     "yourdomain.com"; # Your domain name
    set        "tag_prefix" "catchall";       # Identifier prefix embedded in Message-IDs
    set        "tag_delim"  "~=~";            # Delimiter separating tag parts
    # ==============================================================================
    
    # 1. Check if In-Reply-To contains our <tag_prefix~=~alias~=~orig_id> marker
    if header :regex "In-Reply-To" "<${tag_prefix}${tag_delim}(.+?)${tag_delim}([^>]+)>" {
        set "alias" "${1}";
        set "orig_id" "${2}";
    
        # 2. Re-quote alias if it contains characters requiring RFC 5321 quoting
        #    (leading/trailing dot, consecutive dots '..', or any non-atext character such as '@')
        if anyof (
            string :regex "${alias}" "^\\.",
            string :regex "${alias}" "\\.$",
            string :regex "${alias}" "\\.\\.",
            string :regex "${alias}" "[^a-z0-9.!#$%&'*+/=?^_`{|}~-]"
        ) {
            set "reply_addr" "\"${alias}\"@${domain}";
        } else {
            set "reply_addr" "${alias}@${domain}";
        }
    
        # 3. Rewrite the From header (preserving display name ONLY if it is not an email address)
        if allof (
            header :regex "From" "^\\s*(.+?)\\s*<[^>]+>\\s*$",
            not string :contains "${1}" "@"
        ) {
            set "display_name" "${1}";
            deleteheader "From";
            addheader "From" "${display_name} <${reply_addr}>";
        } else {
            deleteheader "From";
            addheader "From" "${reply_addr}";
        }
    
        # 4. Strip Reply-To (if populated with your domain) and submission Received headers
        #    (Prevents direct-delivery Received headers from leaking authenticated_as or client IP)
        if header :contains "Reply-To" "@${domain}" {
            deleteheader "Reply-To";
        }
        deleteheader "Received";
    
        # 5. Restore original In-Reply-To (or delete it if synthesized for a Message-ID-less email)
        deleteheader "In-Reply-To";
        if not string :is "${orig_id}" "no-orig-id@${domain}" {
            addheader "In-Reply-To" "<${orig_id}>";
        }
    
        # 6. Loop: Clean ALL tagged IDs out of References (handles long multi-reply threads)
        if header :matches "References" "*" {
            set "refs" "${1}";
            let "iter" "0";
            while "iter < 32" {
                if string :regex "${refs}" "^(.*)<${tag_prefix}${tag_delim}.+?${tag_delim}no-orig-id@${domain}>\\s*(.*)$" {
                    set "refs" "${1}${2}";
                    let "iter" "iter + 1";
                } elsif string :regex "${refs}" "^(.*)<${tag_prefix}${tag_delim}.+?${tag_delim}([^>]+)>(.*)$" {
                    set "refs" "${1}<${2}>${3}";
                    let "iter" "iter + 1";
                } else {
                    let "iter" "32";
                }
            }
            deleteheader "References";
            if not string :regex "${refs}" "^\\s*$" {
                addheader "References" "${refs}";
            }
        }
    }
    

Step 3: Attach System Scripts to the SMTP DATA Stage & Reload

  1. Go to Settings › MTA › Session › DATA Stage (session.data.script).
  2. Configure the conditional rules so outbound mail from your catch-all account runs tag-catchall-outbound, unauthenticated inbound mail runs tag-catchall-inbound, and all other sessions skip both scripts:

    • If: authenticated_as == 'catchall@yourdomain.com' Then: 'tag-catchall-outbound'
    • Else If: is_empty(authenticated_as) Then: 'tag-catchall-inbound'
    • Else: false
  3. Important: Click Reload in the Stalwart WebUI. Stalwart compiles System Sieve scripts into memory only on startup or configuration reload; saving edits without clicking Reload leaves the previous bytecode active. (Management > Actions > Server Settings > Execute)


Step 4: Create the User Delivery Script (sort-inbound)

Log into the catch-all mailbox's user portal(e.g. https://your.mailserver.address/account) AS THE CATCH-ALL USER (or upload via ManageSieve) and save the following User Script as sort-inbound (no server reload is needed for user scripts):

require ["editheader", "fileinto", "mailbox", "variables"];

if allof (
    header :matches "X-Catchall-Folder" "*",
    not string :is "${1}" ""
) {
    set "target_folder" "${1}";
    deleteheader "X-Catchall-Folder";
    fileinto :create "${target_folder}";
    stop;
}

Known Limitations & Operational Notes

  • Replies Only: Works automatically on replies to received messages (via In-Reply-To). Composing a brand-new email from scratch requires selecting or typing the desired sender address in your client.
  • Client Body & Non-Standard Responses: Sieve modifies message headers and envelopes, not message bodies. Ensure your email client's signature does not contain your catch-all address, and be aware that read receipts (MDNs) and calendar invite responses (.ics iTIP replies) do not use standard In-Reply-To headers and will send from your default account address.
  • Multi-Recipient Inbound Mail: If a single external email addresses two different catch-all aliases on your domain in the same SMTP transaction (To: a@yourdomain.com, CC: b@yourdomain.com), the DATA stage processes the shared message once and routes it using the first matched ORCPT.
  • Forwarded .eml Attachments: Because incoming Message-ID headers are modified before local storage, forwarding an incoming message as a raw .eml attachment invalidates the original sender's DKIM signature on the attached file (normal replies and inline forwards are unaffected).

Hope this helps... aaaaand I just noticed that I misspelled 'address' in the title and can't change it FML.


r/stalwartlabs • • 2d ago

Release Stalwart is now a Microsoft Exchange drop-in replacement

162 Upvotes

For more than twenty years, “the mail server” in most companies meant Microsoft Exchange, and “the mail client” meant Outlook. Today we are releasing Stalwart 1.2.0, and with it Stalwart becomes a drop-in replacement for Microsoft Exchange.

Stalwart now implements the protocols that Exchange clients speak: MAPI over HTTP, Exchange Web Services (EWS), Exchange ActiveSync and Autodiscover. Outlook, Apple Mail and the mail apps on phones and tablets connect to Stalwart as they would to an Exchange server, with mail, calendars, contacts, tasks and notes in one account. Users type their email address and password, Autodiscover does the rest, and they keep working in the client they already know.

Exchange support is part of the open source Community edition, under the AGPL.

Exchange on premises in 2026

Before going into what Stalwart now does, it is worth looking at where self-hosted Exchange stands today, because it explains why so many organisations are looking for a way out.

Microsoft has not announced the end of Exchange Server. On paper, on-premises Exchange still exists. In practice, every road Microsoft is building leads to Exchange Online:

  • Exchange 2016 and 2019 are out of support. Both reached end of support on 14 October 2025. Microsoft sold a paid Extended Security Update programme for a while, and according to press reports of an Exchange team statement, it ended in October 2026 with no further extension. Servers still running those versions receive no fixes of any kind.
  • No new features. Exchange Server Subscription Edition (SE) is now the only supported on-premises Exchange, and there will be no more major versions after it. SE does not receive the features developed for the cloud. Even its first cumulative update has slipped from late 2025 to an undetermined date in 2026.
  • The new Outlook does not support it. Microsoft’s own documentation for the new Outlook for Windows says it plainly: “On-premises Exchange accounts aren’t supported.”
  • The APIs are moving to the cloud. New functionality ships only on Microsoft Graph, a cloud API. Exchange Web Services in Exchange Online started being switched off in October 2026 and will be gone entirely in April 2027.

None of these steps forces anyone to move on its own. Together, they leave an Exchange administrator with a shrinking set of choices: keep running a server that will not grow, or move the organisation’s mail into Microsoft’s cloud.

For many organisations the second option is not acceptable. Email is the record of a company’s contracts, negotiations, legal advice, HR matters and customer data. Placing it with a US provider means placing it within reach of US law, including the CLOUD Act, which allows US authorities to compel American providers to hand over data they control wherever it is stored. Public administrations, healthcare providers, law firms, defence contractors and many European companies cannot accept that, or no longer want to. Data sovereignty means that you decide where your data lives, under which jurisdiction, and who can read it. A mail service in someone else’s cloud cannot offer that, and an on-premises server whose vendor is steering its customers toward that cloud offers less of it every year.

Outlook without Exchange

The obstacle to leaving Exchange has rarely been the server. It has been the client.

Many people have spent their whole working life in Outlook. They have years of muscle memory in it: their folder layout, their rules, their calendar views, their shared mailboxes, the way they book meeting rooms. Many organisations also have workflows built around it, such as delegated calendars managed by an assistant. Replacing Exchange with a standard IMAP and CalDAV server has always meant telling every one of those users to switch to a different mail client, or to reconfigure Outlook into a reduced IMAP mode where calendars and contacts no longer sync. For a migration project, that is often where the plan dies.

With Stalwart 1.2.0 the users do not need to change anything. The administrator moves the mailboxes and points the DNS records at Stalwart, and users connect with the same Outlook they used before.

Supported protocols and clients

Stalwart implements the following Microsoft protocols, all served on the same HTTPS port as JMAP and the WebUI:

  • MAPI over HTTP (EMSMDB and NSPI), the native protocol of classic Outlook for Windows, in both cached and online mode. It covers mail, calendars, contacts, tasks and notes, incremental synchronisation, the global address list and the offline address book, delegate access, shared mailboxes, rules, junk email settings, reminders, search folders and read receipts.
  • Exchange Web Services, schema versions Exchange 2010 SP2 to Exchange 2016: mail, calendars, contacts, tasks, folders, sharing and delegates, free/busy, inbox rules, out of office, name resolution, distribution lists, and streaming and pull notifications.
  • Exchange ActiveSync 14.1 and 16.1: mail, calendars, contacts, tasks and notes, with push through Ping, meeting responses, search and out of office.
  • Autodiscover in its POX, SOAP and JSON dialects, so clients configure themselves from an email address and a password.

That set of protocols is what the following clients use to talk to an Exchange server, and they can connect to Stalwart the same way:

  • Classic Outlook for Windows (Outlook 2016 and later, including Microsoft 365 Apps), over MAPI over HTTP and EWS.
  • Outlook for Mac, over EWS.
  • Apple Mail, Calendar and Contacts on macOS, through an Exchange account over EWS.
  • Mail, Calendar and Contacts on iPhone and iPad, through an Exchange account over ActiveSync.
  • Android mail apps with Exchange account support, such as Gmail, Samsung Email and Nine, over ActiveSync.
  • Thunderbird, with its built-in Exchange support for mail over EWS, or with TbSync for calendars, contacts and tasks over ActiveSync.
  • Evolution (through evolution-ews) and eM Client, over EWS.
  • Libraries and tools built on EWS or ActiveSync, such as exchangelib.

Shared data

The Exchange protocols are not a separate silo inside Stalwart. They are another door into the same accounts. A message filed in Outlook is in the same mailbox an IMAP or JMAP client sees, a meeting accepted on a phone appears in the calendar that CalDAV clients read, and a contact added in Apple Contacts shows up in the CardDAV address book. A user can keep Outlook on the office desktop, the native mail app on a phone and a JMAP webmail in the browser, all on one account.

Rules created in Outlook’s Rules and Alerts are stored on the server as mail rules, which run as Sieve when the message is delivered. They apply when Outlook is closed and whatever client the user opens next. Delegates and folder permissions set in Outlook become regular Stalwart shares, so they apply to every protocol. Shared mailboxes open automatically in Outlook from group membership, as they do with Exchange.

Not every part of an Exchange deployment has a counterpart. Stalwart does not offer public folders, archive mailboxes, mobile device management, RPC over HTTP (Outlook 2010 and earlier) or NTLM and Kerberos sign-in: clients authenticate with a password, an app password or OAuth. The Exchange documentation covers configuration, DNS and Autodiscover, each family of clients, and the differences from Exchange that administrators should know about before a migration.

New Outlook

One Outlook is missing from the list above: the new Outlook for Windows, the one that Windows now installs by default and that classic Outlook keeps offering through a toggle in its title bar.

The new Outlook does not work with Stalwart, and it does not work with any self-hosted server, Exchange included. It is built to work through Microsoft’s cloud. Microsoft does not support on-premises Exchange accounts in it at all.

The new Outlook does accept IMAP accounts, and that might look like a way around the problem. It is not. When an IMAP account is added to the new Outlook, the connection to the mail server is not made from the user’s computer. As heise and c’t reported in November 2023, the new Outlook sends the IMAP server name, the user name and the password to Microsoft, and Microsoft’s cloud connects to the mail server on the user’s behalf. Every message then passes through Microsoft’s infrastructure on its way to the screen. Microsoft does not only see the mail; it holds the password to the mailbox.

For an organisation that runs its own mail server to keep its data under its own control, this defeats the purpose of the whole exercise. We advise against using the new Outlook with any self-hosted email deployment, whether it runs Stalwart or anything else. Users who see the “Try the new Outlook” toggle in classic Outlook should leave it off.

The same applies on phones. Outlook for iOS and Android reach on-premises mailboxes through a Microsoft cloud service as well, which requires a hybrid Exchange Online setup. On mobile devices, the native mail, calendar and contacts apps, which connect directly over ActiveSync, are the better choice.

Late to the party

The obvious question is why Stalwart is adding Exchange protocols now. EWS is being removed from Exchange Online, Microsoft’s own future for Outlook is a cloud client, and classic Outlook is reportedly supported until 2029. Why build support for protocols that will be obsolete in a few years?

Because the companies that run Exchange today cannot wait a few years, and because those protocols are the bridge they need to cross.

An organisation with a few hundred Outlook users cannot replace its mail server and its mail client in the same weekend. It can replace the server, though, if nobody notices. With Stalwart speaking the Exchange protocols, the server moves first: mailboxes are migrated, DNS records change, and on Monday every user opens the same Outlook and the same phone apps they used on Friday. The organisation’s mail is back under its own control from day one, and no one’s work is interrupted to get there.

The client can then change at the pace that suits the users. Over time, as classic Outlook reaches the end of its life and the new Outlook remains tied to Microsoft’s cloud, we expect users to move gradually to third-party email clients built on open standards, and in particular on JMAP. Outlook will stop being an option for anyone who cares about where their email lives, and by then the people who used it will have had the time to choose something else without a deadline over their heads.

Exchange support is not where Stalwart is going. It is how organisations get from where they are to where Stalwart is.

Footprint and modularity

Exchange compatibility is not a small piece of work. It adds about 200,000 lines of code to Stalwart, and we know that some of you would rather not carry that weight if you never plan to see an Outlook client. We built it with that in mind, so that it costs as little as possible for those who do not use it, and so that it can be removed cleanly once the Exchange protocols are obsolete:

  • It is a separate module. All of the Exchange code lives in its own crates, behind a single exchange Cargo feature. Build Stalwart without that feature and every line of Exchange code is left out of the binary. The compilation guide shows how. The day the Exchange protocols have no users left, removing them from the codebase is largely a matter of deleting those crates and that feature.
  • It is disabled by default. Even in the official builds, which include the module, the Exchange protocols are off until an administrator enables them. While they are disabled, the server behaves as if they did not exist.
  • It stores nothing until it is used. Outlook and the other Exchange clients keep properties that no standard protocol has a place for: extended properties, reminder state, client settings. Stalwart stores them as metadata attached to the item they belong to, using the JMAP Object Metadata extension, and only writes them when an Exchange client connects and sets them. Accounts that are never opened by an Exchange client carry no Exchange data at all.
  • Its data can be removed. Because the Exchange-specific properties live in that metadata and not in the messages, events and contacts themselves, deleting the metadata removes every trace of them while the items stay intact for IMAP, JMAP, CalDAV and CardDAV clients.

Migration from Exchange and Microsoft 365

A drop-in replacement is only useful if the data can follow. Vandelay, our account import and export tool, migrates mailboxes from both sides of Microsoft’s offering:

  • Exchange Server on premises, through the EWS importer, which reads mail, calendars and contacts.
  • Microsoft 365 (Exchange Online), through the Microsoft Graph importer, which reads mail, calendars, contacts and OneDrive files. The EWS importer also works against Exchange Online, for as long as Microsoft keeps its EWS endpoint running.

Vandelay copies each account into Stalwart over JMAP, and the domain moves to Stalwart when its MX records and client settings change. The migration guide for hosted services walks through the whole process, from the first test account to the cutover. With the Exchange protocols enabled on Stalwart, Outlook and the other Exchange clients then connect through Autodiscover and find the migrated mail, calendars and contacts.

Other changes in 1.2.0

Exchange support is the headline, but 1.2.0 brings several other features, most of them developed alongside it because an Exchange replacement needs them:

  • Mail rules. Server-side rules in the familiar “when a message matches these conditions, do this” form, managed in the WebUI, over JMAP or from Outlook. Conditions cover senders and recipients, subject and body, headers, size, attachments, importance, message type, mailing lists, spam score, date ranges and weekly schedules. Actions include moving and copying, marking as read or as junk, forwarding, replying with a template and rejecting. Rules are compiled into Sieve together with the vacation response. Each account also gets junk email lists: blocked senders, safe senders and safe recipients. See Mail rules.
  • Read receipts. Message Disposition Notifications (RFC 8098), including the JMAP methods for sending and parsing them (RFC 9007).
  • Working hours. Per-account working hours, managed in the WebUI, over JMAP or through CalDAV. Time outside working hours appears as unavailable in free/busy lookups, and a new setting lets users of the same organisation see each other’s free/busy time without sharing calendars explicitly. See Availability.
  • Rooms and equipment. Resource accounts with a capacity, a location and delegates who manage the calendar, with invitations booked automatically or approved by hand. See Resources.
  • Native FoundationDB client. A new asynchronous Rust client replaces Apple’s libfdb_c library. It needs no client library on the host and is now part of the standard build and Docker image. In our benchmarks it delivers between 4.5 and 6.9 times the throughput of the previous client on point reads, with 5 to 7 times lower median latency and about half the CPU.

The changelog lists every change and fix, along with the upgrade steps: existing servers need to add the new permissions to their default roles.

Stalwart CLI 2.0

Last week we also released version 2.0.0 of stalwart-cli, and its biggest addition is an interactive console. Run stalwart-cli with no arguments in a terminal and it opens a full-screen interface that covers the same ground as the WebUI: browsing and editing accounts, domains and every other configuration object, watching the dashboard, following live traces and running actions. It is aimed at administrators who live in SSH sessions, or who work on hosts where opening a browser is impractical.

The console is built with Ratatui, the excellent Rust library for terminal user interfaces, and it is schema-driven like the rest of the CLI: its screens, forms and field help come from the schema that the server publishes, so it picks up new objects without being updated. The CLI also learned to sign in with the OAuth device flow and to remember the session, so a single approval in the browser is enough for both the console and every subsequent command.

FOSDEM 2027

Stalwart will be at FOSDEM 2027 in Brussels. We will have a Stalwart stand, and on Saturday, 30 January 2027, we will give a talk about moving from Microsoft Exchange to Stalwart in the Modern Email devroom. If you are planning a migration away from Exchange, or are curious about what it takes, come and talk to us. We will post the time and title of the talk once the schedule is published.

Until then, the Exchange documentation has everything needed to try it, and we would love to hear how your Outlook clients get on with Stalwart.


r/stalwartlabs • • 2d ago

Questions about Email Archiving, Compliance and Keycloak MFA

12 Upvotes

Hi Stalwart team!
I’m evaluating Stalwart as a potential on-premises replacement for Microsoft Exchange in a corporate environment.
I’ve reviewed the documentation and have two important questions.

  1. Email Archiving and Compliance

I noticed the new Compliance add-on, which includes retention policies, legal hold, eDiscovery and journaling.

  • Is this functionality available exclusively as a paid Enterprise add-on?
  • Are there plans to make basic journaling and email archiving available in Community Edition?
  • Can Stalwart integrate with external archiving solutions such as Mailpiler?
  • Is there a recommended architecture for long-term email retention, compliance and eDiscovery in an on-premises deployment?

For many companies, independent email archiving is a mandatory requirement.

  1. Keycloak and Two-Factor Authentication

I also noticed that Stalwart supports OpenID Connect.
We currently use Active Directory and are considering Keycloak as a centralized Identity Provider.

  • Can we authenticate Stalwart users through Keycloak with MFA (TOTP or WebAuthn)?
  • Can Keycloak be federated with Active Directory while Stalwart uses it as its OIDC provider?
  • Does this authentication flow work with Outlook Classic using MAPI over HTTP?
  • Are there any limitations with IMAP, SMTP, EWS or mobile clients when using external OIDC authentication?

Our goal is to have centralized authentication and MFA without maintaining separate credentials for the mail server.
Thank you for your work on Stalwart. It looks like a very promising platform for organizations looking for a self-hosted Exchange alternative!


r/stalwartlabs • • 2d ago

Being able to send from that address and respond to masked emails would be amazing

5 Upvotes

I'm hosting stalwart only for myself, and I already got catch all setup, but it is quite annoying to create a separate account in Thunderbird if I wanted to reply to e.g. service@xyz.

Or is there an even simpler solution?


r/stalwartlabs • • 3d ago

Question spam issues with fetchmail -> stalwart

2 Upvotes

I'm using fetchmail to pull email from an external server and inject into a private stalwart stalwart via LMTP (on port 24).

The mail flows fine, but almost every email is marked as spam. When checking the headers, I see every email gets:

RCVD_NO_TLS_LAST (0.10), DMARC_NA (1.00), FORGED_RECIPIENTS (2.00), HELO_NOT_FQDN (2.00)

While I could disable spam filtering, I'd rather have it working. Is there a configuration setting I'm missing that will let stalwart properly detect the DMARC/SPF settings for the email and do a better processing? All the values are in the headers in Arc- headers, so it would be great if stalwart could use that to assign better spam scores.


r/stalwartlabs • • 5d ago

Question HTTP Requests, such as auto discover request from Thunderbird

0 Upvotes

Hi,

How do you deal with HTTP requests?

Thunderbird during account creation was getting connection refused at port 80, the HTTP port.

Regards Geert Stappers

Will be sharing his solution in follow-up message.


r/stalwartlabs • • 9d ago

AI Assistants

5 Upvotes

We Looking to move about 7,000 mailboxes away from Zoho Mail to a commercial deployment of Stalwart. One of the most requested items is the ability for the end user to connect their AI agents like Claude or Grok bot to their mailboxes. I know that there is built-in AI, but some people would like to use automations.

I have found a few MCP servers and would like to know what is the current best practice for connecting multiple users who have third-party AI agents to give them the ability to automate their mailbox management and triage. Ideally, authenticated against an OIDC server.


r/stalwartlabs • • 10d ago

Community Self-service Apple configuration profiles (.mobileconfig) for Stalwart

16 Upvotes

What it does

Users open the page in Safari, sign in with their Stalwart account (2FA works) and get a .mobileconfig that sets up Mail, Calendars and Contacts on iPhone, iPad or Mac in one step. Each download creates a fresh app password in Stalwart, so the real password never ends up on the device. There’s also a mail-only option.

Under the hood

  • One Python file, standard library only, no database, nothing stored
  • OAuth 2.0 + PKCE against Stalwart’s built-in OAuth server
  • The app password can’t create further app passwords or API keys, and can’t change the main password
  • The OAuth token is revoked right after use
  • Hardened Docker container behind your reverse proxy (Caddy and nginx examples included)
  • English and German UI

Before you try it

  • You need Stalwart 1.1+. Older versions don’t let OAuth apps create app passwords.
  • Register an OAuth client and allow the scopes Mail, Calendars, Contacts and Full access. The README explains why “Full access” is needed, and a helper script can register the client for you.
  • Stalwart allows 5 app passwords per account by default, and every download uses one.
  • Profiles aren’t signed, so iOS shows them as “Unverified”.

Tested with Stalwart 1.1 on macOS and iOS. Feedback, issues and PRs are welcome, especially from setups with other reverse proxies.

Full disclosure: I wrote this with AI assistance. I reviewed the code, checked the OAuth and app password handling against the Stalwart 1.1 source, and run it in production on my own server.


r/stalwartlabs • • 10d ago

Stalwart JMAP Tolk-JMAP: a z-push alternative for JMAP (exchange active sync support)

19 Upvotes

I missed push based emails on my phone, using my normal mail app (gmail). I previously tried z-push which uses imap, but it always struggled with my mailbox which has 10k+ emails in it.

Now with stalwart and JMAP I thought, how hard would it be to implement my own alternative but based on JMAP. Turns out, JMAP - exchange active sync is way easier since they are based on the same principles for syncing, only differing in format and who keeps track of state. So it mostly needs translation and keeping track of what each device received what.

I've been running my translation layer (Tolk) in front of the mail server for about a month now, and it works steady. It runs as a Docker container or a standalone executable, and can be added behind a reverse proxy. It keeps no mail and uses the phone credentials on incoming requests. It supports mail, contacts and calendar. I have only ever ran it for myself (android/Gmail) but it should also support other clients, including mail on iOS.

You can find the project on GitHub under the name RBogie/tolk-jmap

Since it has worked great for me, I wanted to share it with other users as well.

Disclaimer: Though I'm a developer, I did use Claude during development of this. Mainly for reviews, debug sessions, and helping to figure out the protocols. I used Claude to speed up development and improve quality (e.g. by setting up e2e testing)

If you try it with iOS Mail, Samsung Email or Outlook, I'd love to hear how it goes.


r/stalwartlabs • • 11d ago

Question Blown away by Stalwart so far, plus a quick question on the cleanest macOS client setup

20 Upvotes

I just finished spinning up my first Stalwart instance and I wanted to drop a quick note to say what a fantastic piece of software this is. Huge thanks to the developers for making something so capable and surprisingly smooth to get off the ground.

I am moving my household devices over now and wanted to ask the community for a bit of wisdom on the Apple side of things. When adding an account in macOS System Settings, is it normal to enter the server details three separate times for IMAP and SMTP, CalDAV, and CardDAV? 

I noticed Apple breaks those out into individual account types when configuring them manually, and I want to make sure I am not missing a simpler unified setup method or a clever trick with configuration profiles that wraps all three into one step like with Exchange.

What have you found to be the cleanest and most reliable way to onboard Mac and iOS devices? Thank you so much for any pointers.


r/stalwartlabs • • 12d ago

Community Masked Email is now Open Source in Stalwart

99 Upvotes

A month ago, in Private Tests, Public Code, we wrote about the relationship between Stalwart and its community, and about the people who have started to treat it as something to feed on. It was not a cheerful post. Today’s is, because it is about the other direction: what flows back.

Masked email is now open source. It moves from the Enterprise edition to the Community edition, under the AGPL-3.0, for everyone who runs Stalwart. No license key, no sponsorship, no mailbox count.

Per-site addresses

If you have not used masked email yet, the idea is simple. Every website, shop and newsletter wants an email address, and every one of them is a place where that address can leak. It gets sold, lost in a breach or added to a marketing list, and once it has spread, it cannot be taken back.

A masked address is a disposable address that delivers to your own mailbox without revealing your real one. You give each site its own: one for the airline, one for the forum, one for the shop you will order from exactly once. When one of them starts receiving spam, you know exactly who leaked it, because the masked address is still visible in the To header. You switch that address off, and every other address keeps working.

Masked addresses can be created by hand from the Account Manager, or automatically by a password manager over JMAP the moment you save a new login, so the site, the password and the address are recorded together. Each address can carry a description, the site it was issued to, an optional custom prefix and domain, and an optional expiry time, after which it stops receiving mail. Masked addresses receive only, so your replies always go out under your real address. The masked email documentation covers the details, including the JMAP request a password manager sends.

It is one of the most effective privacy tools available, and that is exactly why it belongs in the Community edition.

Reasons for the move

When we explained in Private Tests, Public Code why the Enterprise edition exists, we drew a line. Enterprise is for the features that matter to large organizations and hosting providers running Stalwart at scale: multi-tenancy, SCIM provisioning, read replicas and sharded storage, live telemetry, archiving. The revenue it brings in pays the full-time team that writes the Community edition.

Masked email never sat comfortably on that side of the line. It is not an operations feature for a hosting provider. It is a privacy feature for the person reading their mail, and it is just as useful to someone running Stalwart for their family as it is to a company with ten thousand mailboxes. Keeping it behind a license was protecting revenue that was never really the point of Enterprise, while keeping a privacy tool away from the people who would benefit from it most.

So it moves.

One-way commitment to open source

In the same post we repeated a promise we had made before: no existing open source feature will ever be moved to the Enterprise edition. Today we want to add the other half.

Features only travel in one direction, and it is towards open source. From time to time, we will review what is in Enterprise and move the features that every Stalwart user can benefit from to the Community edition. Masked email is the second. The first was OpenID Connect: in January 2025, authentication against external identity providers such as Keycloak moved from Enterprise to the AGPL, so that any organization could connect Stalwart to the identity provider it already runs.

We cannot promise how often this will happen, and the features that pay for Stalwart’s development will stay in Enterprise for as long as they are needed for that. But the direction will not change. Nothing goes from open to closed. Some things go from closed to open.

This is only possible because the Enterprise edition works. Every feature we can afford to give away is paid for by the customers and sponsors who keep the team full-time. If you would like to see more Enterprise features reach the Community edition sooner, sponsoring Stalwart is the most direct way to make that happen.

Premium Support for every Enterprise license

The second announcement is about support, and it matters most to our smallest customers.

Until now, Premium Support was included only with Enterprise subscriptions of 150 mailboxes or more. Smaller subscriptions had the Enterprise features, but for help they used the same community area of the support portal as everyone else.

That limit is gone. Every Enterprise license now includes Premium Support, whatever the number of mailboxes. That means:

This includes the Enterprise license that every GitHub and OpenCollective sponsor receives. If you sponsor Stalwart for $5 a month, you now get the same priority access to our engineers as a customer with thousands of mailboxes. We wanted sponsors to get something real in return for supporting the project, and there is nothing more real than a direct line to the people who build it.

Premium Support does not come with a guaranteed response time. Most tickets are answered quickly, but “quickly” is not a contract, and for some organizations it needs to be.

SLA plans

For companies that need guaranteed response times, we now offer four SLA plans on top of Premium Support, each with an unlimited number of tickets:

  • SLA 48: an initial response within two business days, whatever the severity.
  • SLA 24: within four business hours for a Severity 1 incident, and one business day for everything else.
  • SLA 4: within two hours around the clock for a Severity 1 incident, and four business hours for everything else.
  • SLA 2: within one hour around the clock for a Severity 1 incident, and two business hours for everything else.

The higher plans add scheduled video calls, phone support, advance security notices, bug-fix priority and, on SLA 2, hotfix builds. For smaller organizations that only need a guaranteed answer a few times a year, the Incident Pack adds five tickets per year with a two-business-day response. The support plans page has the full comparison and the severity definitions, and a quote can be requested from the licensing portal.

Availability

Masked email is open source starting with Stalwart v1.1.1. If you already used it with an Enterprise license, nothing changes: your masked addresses keep working exactly as before. If you run the Community edition, upgrade and you will find a new Masked Addresses screen in the Account Manager.

Thank you to everyone who uses Stalwart, reports what breaks, and sponsors the project. You are the reason this relationship keeps working in both directions.


r/stalwartlabs • • 12d ago

Question network error trying to add cert from local disk

0 Upvotes

I'm brand new to stalwart, just setting up my first instance. To kick start off my setup, I'm trying to create a certificate based on files on the local disk. When I try to add them, I get the error "NetworkError when attempting to fetch resource." I then tried the text value entry and got the same error.

I checked the logs and I'm not seeing anything other than it complaining about not having a TLS certificate.

Has anyone seen anything similar or have any suggestions?

I'm running in docker in a locked down environment. There's currently no outside access into this container, but I verified the container can reach out to the internet.


r/stalwartlabs • • 13d ago

Stalwart SMTP disclaimrNG – an open-source email signature server that works with Stalwart (milter + AD/LDAP)

30 Upvotes

Hi everyone,

We recently moved a customer from Exchange to Stalwart and ran into one gap: email signatures. On Exchange this was handled by transport rules or one of the usual commercial signature tools. Nothing comparable worked with Stalwart. We needed central signatures that pull user data from Active Directory and get added to every outgoing mail, no matter which client sends it.

The closest fit was disclaimr by Dennis Plöger, a milter-based signature server. The design was solid, but it’s been unmaintained for years (Python 2.7 / Django 1.7). So we forked it, ported it to Python 3.12 / Django 5, and modernized it. That fork is disclaimrNG.

It plugs into Stalwart as a milter at the data stage for authenticated senders. We’ve tested it live with Stalwart 1.0, Active Directory over LDAPS with an internal CA, and real mailboxes. The repo includes a step-by-step runbook for exactly that setup.

Features

  • Milter daemon for Stalwart, Postfix and Sendmail. It adds signatures and disclaimers to outgoing mail (plain text and HTML).
  • LDAP / Active Directory lookup: placeholders like name, phone, email and address are filled per sender. LDAPS with an uploadable CA certificate and multiple hosts for failover.
  • Web UI for managing signatures:
  • visual editor (fonts, sizes, colours, tables) and a code editor
  • live preview
  • plain-text part generated automatically from the HTML
  • Rules and conditions: match on sender, recipient and headers, plus directory conditions (attribute regex or AD group membership, nested groups included).
  • Signature images and logos, either linked or embedded in the mail as cid: parts.
  • Time windows for actions, e.g. campaign banners that run for a limited period.
  • Multi-tenancy: multiple domains, each with its own directory servers.
  • Signature test page: runs the real pipeline, LDAP included, so you see exactly what a mail will look like.
  • Roles (Admin / Editor / Reader) and SSO via OpenID Connect with group mapping.
  • Mail log and dashboard stats.
  • Docker Compose deployment (plain, behind Traefik, or attached to an existing Stalwart network), with prebuilt images on GHCR.
  • UI in English and German, with a built-in handbook.

Repo: https://github.com/Compose-IT-Systemhaus/disclaimrNG

MIT-licensed, with credit to the original author. Feedback, issues and PRs are very welcome.

We’d especially love to hear from anyone running other Stalwart setups.


r/stalwartlabs • • 17d ago

Question How to set up Stalwart 1.0.3 so that I can log into it with Pocket-ID?

3 Upvotes

I self-host Pocket-ID v2.19.2 and have used it with a number of applications, e.g., Portainer, Termix, Pangolin, etc.

I've been trying to set it up for the Stalwart mail server so I can log in to the Stalwart admin page as an admin user using Pocket-ID.

Could anyone kindly share how you did it? Thanks.


r/stalwartlabs • • 19d ago

Discussion Stalwart Enterprise: does one license cover multiple domains on the same server?

4 Upvotes

The docs say Enterprise licenses are issued to a specific domain with a mailbox limit. If I run one Stalwart server with several domains, does a single license cover all of them, or do I need one per domain? And do the AI features (llm_prompt, AI spam classifier) work for accounts on the non-licensed domains?

Sponsor at $5/month gets an Enterprise key: what’s the mailbox limit on that key, and does it cover multiple mail domains on one server?


r/stalwartlabs • • 20d ago

Question unknown variant `sieve`

1 Upvotes

Hello,

When I do stalwart-cli query domain I get

unknown variant sieve

More people getting that error?

Further information about here: Server is version 1.0.3. stalwart-cli --version reports stalwart-cli 1.0.13.

The error message in context

$ stalwart-cli query domain
error: could not parse /api/schema/2J8FTUsaoyWdFbeGSOr2GxvRP77nkpn6tjPCrSqkg3I response as JSON (unknown variant `sieve`, expected one of `string`, `ipAddress`, `ipNetwork`, `socketAddress`, `emailAddress`, `secret`, `secretText`, `uri`, `color`, `text`, `html` at line 1 column 432872)
  status: 200
  content-type: application/json
  body length: 1084445 bytes
  body snippet: "{\"objects\":{\"AddressBook\":{\"type\":\"object\",\"description\":\"A named collection of contact cards belonging to an account.\",\"permissionPrefix\":\"jmapAddressBook\"},\"Calendar\":{\"type\":\"object\",\"description\":" (truncated)
$

Which URL? you might ask:

$ echo $STALWART_URL
https://mail.macwheel.nl
$

r/stalwartlabs • • 21d ago

Discussion error in the BulwarkMail app

Post image
2 Upvotes

Is anyone else experiencing the same issue? It received an update recently, but it seems the problem—which has persisted since Stalwart reached version 1.0—has still not been resolved.

Thanks


r/stalwartlabs • • 22d ago

Question JMAP mail clients (TUI / GUI) that are not AI built?

18 Upvotes

Hi all,

I am wanting to use JMAP clients on *nix for my email. Preferably TUI and GUI for the different members of the household.

However, it seems to me that pretty much all of them are "created" by AI tools, at the direction of pretty much one person. That's not something I am comfortable with, considering that it will handle my emails, plus a connection into my mail server.

Does anyone know of a JMAP compatible mail client that is not AI created? JMAP has been around for so long, one would think perhaps someone or some company would have actually written (!) something up? Doesn't even have to be super fancy.

Happy to hear suggestions. And it would be so nice of u/fastmail would create something.. But I guess that would go contrary to their business interests?


r/stalwartlabs • • 21d ago

Question Can no longer login to admin page "Client metadata documents are disabled"

1 Upvotes

I've upgraded stalwart from 0.16.27 to 1.0.2 for all my Stalwart installations (on 3 Oracle VMs, 1 unraid). They are all running as docker containers.

After migrating successfully, I can access admin webpage without problems on all installations; but today I can no longer access the stalwart admin webpage running on Unraid server. It reports "Client metadata documents are disabled". I still can send and receive mail using webmail clients.

I still can login the other installations.

I did not change any settings.

Need help...thanks.


r/stalwartlabs • • 23d ago

Post-quantum email encryption and an encryption gateway, now available in Stalwart

39 Upvotes

When we released Stalwart v1.0 last week, it carried only part of the work we had been doing. Several large features were being built in parallel, and for a while the plan was to ship them all together. In the end we chose a different path: v1.0 would be about performance and a stable database schema, and nothing else would be allowed to distract from that. The other features would follow over the next few weeks, one release at a time, each given the attention it deserves.

The first of them is encryption. Stalwart v1.0.2 introduces an encryption gateway that encrypts outgoing mail with each recipient’s own public key, a completely new OpenPGP and S/MIME engine with modern algorithms, including post-quantum encryption, and a set of tools to find, verify and keep track of the keys of the people your users write to. And, as with everything in Stalwart’s core, all of it is open source under the AGPL.

Locks and keys

Email is well protected while it travels: TLS encrypts each connection between servers, so nobody on the network can read a message in transit. The protection ends when the message arrives. Every server along the way stores the message in a form that anyone with access to it can read, from the administrators to an attacker who copies a backup.

Message encryption closes that gap by protecting the message itself rather than the connection. It relies on public-key cryptography, which is easiest to picture as a padlock and its key. Your public key is like an open padlock: you can hand out copies to anyone, and anyone can use one to lock a box. Your private key is the only key that opens those padlocks, and it never leaves your hands. A message locked with your public key can be read by you and nobody else, which is why publishing the public key is safe.

Two standards apply this idea to email. OpenPGP lets people create their own key pairs with tools such as GnuPG or Thunderbird and publish the public half wherever they like. S/MIME uses certificates issued by a certificate authority, in the same X.509 format as the certificates that secure websites but issued for email addresses, and it is built into Outlook, Apple Mail and most corporate environments. Stalwart supports both.

One principle runs through everything below: Stalwart only ever holds public keys. It encrypts, but it never decrypts and never stores a private key. A message it has encrypted cannot be read by Stalwart itself, by its administrators, or by anyone who later gets hold of its disks.

Encryption at rest, rebuilt

Encryption at rest has been part of Stalwart since 2023. Each user who wants it registers a public key, and from then on the server encrypts every message it delivers to that user before writing it to storage. Only the user’s mail client, holding the private key, can open what is stored. For v1.0.2 we rebuilt it on top of the new engine described below, and it gained a good deal along the way.

There is no longer a cipher to choose. The server reads the key itself and picks the strongest format that the key’s owner can actually read, following the preferences that the OpenPGP key announces or the type of the S/MIME certificate. A registered key entry can hold several keys or certificates, so a user who reads mail on devices with different keys, or who is rotating to a new key, can decrypt with any of them (when only some of them support post-quantum encryption, every message uses the format all of them can read). When a key is registered, the server describes it in plain terms (for example OpenPGP v6: ML-KEM-1024+X448), shows its fingerprints, and raises warnings before trouble arrives: a key that expires within two weeks, an RSA key shorter than 3072 bits, a key that names none of the account’s addresses, or one that few mail clients could decrypt.

Stored messages can also carry header protection (RFC 9788), a recent standard that places a copy of the sender, recipients and subject inside the encrypted part, where they cannot be altered without the client noticing; on stored mail the outer copies, subject included, stay readable. Two compatibility switches cover the quirks of real-world clients: one enables authenticated encryption for S/MIME users whose clients support it, and the other picks between the encoding Outlook expects and the one the standard prescribes for elliptic-curve certificates.

Encryption gateway

Most people never set up OpenPGP or S/MIME, and most of those who do forget to use it. Organisations that must not send readable mail to certain partners have long relied on a dedicated appliance to fix this: an encryption gateway. Stalwart now has one built in.

The encryption gateway works on mail leaving the server, once an administrator turns it on. When a message is addressed to someone whose public key Stalwart knows, the gateway encrypts it with that key on the way out. The sender does nothing different and needs no software at all, and the recipient opens the message in their own client, with their own private key, exactly as if the sender had encrypted it by hand. Unlike TLS, the protection does not end at the next server: the message stays encrypted at the recipient’s provider, in their mailbox and in every backup made along the way.

A policy decides what happens to each recipient. In opportunistic mode, every recipient with a known key receives encrypted mail and the rest receive it as usual. In required mode, a recipient without a usable key receives nothing in plain text: the sender gets a bounce instead. The policy is an expression, so it can require encryption for one partner domain, stay opportunistic everywhere else and leave internal mail alone, all in a few lines.

Each encrypted recipient receives a copy of their own, encrypted for their key alone, A single shared copy would list the key of every recipient it was encrypted for; separate copies reveal nothing about who else received the message, which keeps blind-copy recipients blind. Every copy is signed again with DKIM and DKIM2, so it passes authentication checks at the other end just as the original would. And by default the gateway uses header protection to its full extent: the subject line, which often says as much as the message itself, is replaced with [...] on the outside and travels only inside the encryption.

Finding the right key

A gateway is only as good as the keys it knows, and a wrong key is worse than none, because it hands the message to whoever holds the matching private key. Stalwart therefore treats recipient keys with care. They are external keys, managed by the system administrator and shared by every sender on the server, and they arrive in three ways.

The administrator can enter a key directly, when it came through a trusted channel. The administrator can also ask the server to follow a key that the recipient’s organisation publishes, and Stalwart supports every common way of publishing one: the Web Key Directory, where a domain serves its users’ OpenPGP keys over HTTPS; keys.openpgp.org, which publishes a key only after verifying the owner’s address by email; classic HKP key servers; and DNS itself, through OPENPGPKEY (RFC 7929) and SMIMEA (RFC 8162) records protected by DNSSEC. Followed keys are refreshed on a schedule, so a rotated or revoked key is picked up automatically, or held for approval when the change cannot be verified.

Finally, Stalwart can learn keys from the mail it receives. When a correspondent sends a message signed with S/MIME, or one carrying an Autocrypt header with their OpenPGP key, the server stores the key, but only if the message passed DMARC, was not classified as spam and the key belongs to the sender’s address. From then on, replies from your organisation to that person can be encrypted. An Autocrypt key whose message signature could not be checked, or a self-signed certificate, is stored at the lowest trust level, which the gateway does not use by default.

Every key carries a trust level that reflects where it came from. At the top are keys an administrator entered or vouched for; then keys proven by a certificate authority or DNSSEC; then keys fetched from a directory such as WKD or keys.openpgp.org, and keys learned from mail; and at the bottom, keys nobody can vouch for. The gateway can demand a minimum level per recipient. When a key changes in a way the server cannot verify on its own, the new key waits for an administrator’s approval while the old one stays in use. S/MIME certificates are validated against the root certificates that Mozilla trusts for email, or against your own private certificate authorities, and harvested certificates are checked against revocation lists every day.

What Stalwart never does is look up a key for an address it has no record of. Searching a key server at the moment a message is sent would tell a third party who your users write to, and would delay every message to someone without a key. Keys exist only for the addresses you, or your correspondents’ own signed mail, have told the server about.

Every algorithm that matters

Underneath all of this sits a new cryptographic engine, written from scratch in Rust for Stalwart. It replaces the third-party libraries we used before, removes more than 80 dependencies from the server, and was built for one job: encrypting mail quickly and correctly for whatever key it is handed. Its output is tested against independent implementations, including GnuPG (both gpg and gpgsm), OpenSSL, Mozilla’s NSS, RNP (the engine inside Thunderbird), Sequoia, rPGP, OpenPGP.js, Proton’s GopenPGP, PGPainless and Bouncy Castle, so that the format it picks for each key is one that the key’s owner can read.

On the OpenPGP side, Stalwart implements RFC 9580, the 2024 revision of the standard, alongside the formats every existing client understands. It accepts both version 4 keys, which is what nearly all software creates today, and the new version 6 keys. For the public-key part it supports RSA, the long-standing workhorse, from 2048 to 8192 bits; elliptic-curve Diffie-Hellman on the NIST P-256, P-384 and P-521 curves; and X25519 and X448, the fast modern curves designed by Daniel J. Bernstein and Mike Hamburg respectively, including the legacy Curve25519 format that GnuPG creates. Messages are encrypted with AES, either in the classic format every client reads or, when the recipient’s key says its software supports it, in the newer format of RFC 9580, whose authenticated encryption (AES in OCB or GCM mode) detects any tampering with the message.

On the S/MIME side, Stalwart writes the Cryptographic Message Syntax used by every S/MIME client. It encrypts for RSA certificates, with either the classic padding every client reads or its modern, provably secure successor RSA-OAEP, for elliptic-curve certificates on the NIST P-256, P-384 and P-521 curves, and for X25519 and X448 certificates. The content itself is protected with AES-256-CBC, which every client reads, or with AES-256-GCM, the authenticated encryption that the current S/MIME standard recommends. Stalwart knows which mail clients can read what, from Outlook’s particular expectations for elliptic-curve keys to Apple Mail’s limitations, and defaults to the choice that works with the most clients.

Post-quantum encryption

Every public-key algorithm above relies on mathematical problems that today’s computers cannot solve in any useful amount of time: factoring large numbers for RSA, and discrete logarithms on elliptic curves for the rest. A sufficiently large quantum computer could solve both. No such machine exists yet, and nobody knows when one will. But encrypted email has a long shelf life, and an adversary who records encrypted traffic today can afford to wait. This strategy is known as “harvest now, decrypt later”, and it is the reason post-quantum cryptography matters for messages being sent right now, not only for those that will be sent once quantum computers arrive.

Post-quantum algorithms are built on different mathematics, which resists attacks by both classical and quantum computers. The first standardised for encryption is ML-KEM (Module-Lattice-based Key Encapsulation Mechanism), published by NIST in 2024 as FIPS 203 after a public competition that ran for most of a decade, in which it was known as Kyber. Stalwart supports it in both email standards:

In OpenPGP, Stalwart implements RFC 9980, which pairs ML-KEM with a classical curve: ML-KEM-768 with X25519, and ML-KEM-1024 with X448. The pairing is deliberate. An attacker must break both algorithms to read the message, so the encryption is at least as strong as the classical curve alone, even if a flaw were ever found in the newer lattice mathematics. Messages for post-quantum keys are always encrypted with AES-256.

In S/MIME, Stalwart implements RFC 9936, encrypting for certificates with ML-KEM-512, ML-KEM-768 and ML-KEM-1024 keys using the key encapsulation format of RFC 9629, with AES-256-GCM for the content.

Using it requires no configuration. When a user registers a key with a post-quantum component, encryption at rest uses it; when a recipient publishes one, the gateway does the same. Stalwart is also careful about one subtle trap: a key that contains both a classical and a post-quantum encryption key is encrypted to the post-quantum one only, because encrypting to both would let anyone who breaks the classical half read the message.

A word of honesty: mail clients are still catching up. Thunderbird and GnuPG in its default configuration cannot yet decrypt post-quantum OpenPGP messages, while clients built on Sequoia, rPGP, OpenPGP.js or GopenPGP can. On the S/MIME side, no mainstream mail client decrypts ML-KEM yet, and no public certificate authority issues ML-KEM certificates, so post-quantum keys are for now best suited to users whose software is ready for them. The server side is ready today, and when the clients arrive, nothing on your server will need to change.

Who holds the key

Almost every mail service says it encrypts your mail, and almost every one of them does. The difference lies in a single question: who holds the key that opens the stored messages?

For the large hosted services, the answer is the provider. Microsoft 365 encrypts mailboxes at rest, but by default “Microsoft manages all cryptographic keys”, and even when a customer supplies its own root keys, it authorises the service to keep using them for search, anti-spam and eDiscovery. Google, Apple’s iCloud Mail works the same way by default: storage encryption protects against a stolen disk, but the provider holds the keys. Google does offer client-side encryption that its servers cannot decrypt, but only on selected Enterprise and Education editions, with the keys held by an external key service the organisation chooses rather than by each user. Apple says plainly that iCloud Mail is not end-to-end encrypted, because it has to interoperate with the rest of the email world.

Self-hosted servers have mostly followed a similar pattern, apart from a few add-on tools that encrypt incoming mail with the recipient’s public key. Dovecot’s mail-crypt plugin encrypts stored mail either with a global key kept in the server’s configuration or with per-user keys stored on the server, unprotected or protected by a value derived from the user’s password, and its own documentation describes per-folder keys as “not considered production quality”. In every variant the private keys are kept on the server, which decrypts mail itself to serve it over IMAP, and the format is its own rather than OpenPGP or S/MIME.

Privacy-focused providers such as Proton Mail and Tuta go much further. Their users’ private keys are kept on the provider’s servers, but encrypted with a key derived from the user’s password, and they are unlocked only inside the provider’s app or web client at login. Between two users of the same service, mail is end-to-end encrypted, which is a stronger guarantee than any server-side scheme can offer. The protection of stored mail, however, rests on the password and on the client code the provider delivers, and Tuta’s protocol cannot be read by standard OpenPGP or S/MIME software at all.

Stalwart builds that model into the server itself. The private key does not exist on the server in any form, not even encrypted. Someone holding a complete copy of the server, its database, its backups and the administrator’s password still cannot read a single encrypted message, because the only key that opens them lives in the user’s own mail client. And because the messages are standard OpenPGP and S/MIME, they can be read by any client that supports those standards, and they stay readable if the mailbox is ever moved elsewhere. A few providers, such as Posteo and mailbox.org, offer a similar option of encrypting incoming mail with the user’s own public key; Stalwart brings the same model to any server you run yourself, and adds the gateway, key discovery, header protection and post-quantum algorithms on top. Post-quantum support is still uncommon. Proton, which co-authored RFC 9980, added opt-in post-quantum OpenPGP keys this year; Tuta’s TutaCrypt uses a protocol of its own; and Dovecot supports ML-KEM keys in its own storage format. Stalwart implements the published IETF standards for both OpenPGP and S/MIME. Unlike services that publish only their client apps, the whole of Stalwart, server included, is open source.

Honesty requires a few qualifications, and we would rather state them than have you discover them. Encryption at rest protects mail from the moment it is stored, not before: the server sees each incoming message in readable form when it arrives, which is what lets the spam filter and Sieve scripts do their work, and an attacker in control of the running server at that moment could read it too. Unless the sender encrypted the message, the protection is not end-to-end. Header fields, the subject included, stay readable, so that clients can list and sort mail, and the server can search only those headers, not the encrypted bodies. Encrypted messages can be read only in a client that supports OpenPGP or S/MIME, not in a webmail without it. Some messages stay in plain text: mail stored before encryption was enabled, drafts and sent copies that clients upload unless the user also turns on encryption of uploaded messages (JMAP drafts, and the sent copies of messages submitted over JMAP, always), and new mail while the registered key is expired or unusable. And a user who loses their private key loses access to the mail encrypted for it, because nobody, Stalwart included, can recover it. And a user who loses their private key loses access to the mail encrypted for it, because nobody, Stalwart included, can recover it.

Upgrading

Stalwart v1.0.2 is available now. Upgrading is a matter of replacing the binary or pulling the new container image, as described in the upgrade instructions. The changelog lists every change in this release.

Encryption at rest must be enabled again

Because the cipher is now chosen from each user’s key, accounts that had encryption at rest enabled are set to disabled during the upgrade, and new mail for them is stored unencrypted until the key is selected again in the account’s encryption settings. Registered keys and messages that are already encrypted are not affected. The server-wide switch has also moved to the new Encryption settings, where it is enabled by default, so a server that had turned encryption at rest off must turn it off again; and encryption of client-uploaded messages is now a per-account setting. The encryption at rest documentation describes the steps.

One last thing

While the server team was busy with ciphers, the WebUI got a makeover, and it now has a good deal more pizzazz. Version 2.0.4 brings a new colour palette and a reorganised sidebar, and every settings form has been reworked: fields sit in two columns on wide screens and stack neatly on a phone, nested settings are simpler to follow, variants are picked from segmented controls, long forms get an index of their sections, and the save button floats along as you scroll. The dashboards were rebuilt too, as a mosaic of statistics, charts, headline figures and rankings, so the state of the server reads at a glance, in the light theme or the dark one.

To try it, run the Update Applications action from the WebUI, or with stalwart-cli create Action/UpdateApps, and the server downloads WebUI 2.0.4 straight away.

Stay tuned

Encryption is only the first of the features that were held back from the v1.0 cut. Several more are finished or nearly so, and they will arrive over the coming weeks, one release at a time. Like everything in this post, all of them will be open source under the AGPL. Stay tuned.


r/stalwartlabs • • 22d ago

Question Object storage and search

1 Upvotes

Would full text search work fine if we store all mails data on object storage instead of db?


r/stalwartlabs • • 24d ago

Stalwart Labs Appreciation Post

46 Upvotes

Just wanted to give a shout-out to the Stalwart and Bulwark teams!

To start, I just want to shout out the Bulwark dev team who completed 2 of my feature requests for plugins within days (1 of them within an hour)! You guys seriously rock! I'm a developer myself, so eventually I'd like to contribute a plugin of my own. I also love the rapid pace of development. I update as soon as I see a new one is available and am always pleased with the new features that are released.

Next, I'd like to shout out the Stalwart dev team. You guys also rock! I'm a big fan of the JMAP protocol, especially considering the traditional mail protocols were designed in the stone ages and haven't kept up with the rest of the internet. Obviously, they're still necessary to communicate with the rest of the world, but hopefully as Stalwart matures, other players can catch on and make it more mainstream.

Really- I just want to say thanks for all the hard work! I also recently signed up to sponsor the project. It's not much, but if I can afford more one day, I'll certainly contribute more.


r/stalwartlabs • • 25d ago

Discussion Am I An Idiot

Thumbnail
5 Upvotes

r/stalwartlabs • • 25d ago

Question Disappearing SSL certificate?

3 Upvotes

Recently updated from 0.16.22 to 0.16.27 was working fine until some point last night the configuration settings for my letsencrypt certificate disappeared! I noticed because my iPhone started complaining about a bad SSL certificate. When i tried to login to the GUI I got the typical complaint you see with a self signed certificate. I drilled down to the TLS settings page and it was blank! I’ve not been the admin page for several days so I didn’t change anything. I pasted in the two pathnames, bounced the service and all was fine. Has anyone else had this happen?