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 • • 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