Skip to main content
AIVO Logo
Cybersecurity & Resilience

Ever Wondered Why Your Emails End Up in SPAM? The Ultimate Engineering Guide with Stalwart

Nicolas BAUD

Nicolas BAUD

Fractional CTO & AI/IS Architect • AMOA Consulting

Published on
Reading time 9 MIN
Ever Wondered Why Your Emails End Up in SPAM? The Ultimate Engineering Guide with Stalwart

Introduction: The Sending Illusion

In the minds of many software engineers, sending an application email seems like the simplest task on earth: open a TCP socket on port 587, make an SMTP call, and watch the packet leave for the destination.

Yet, in 2026, the reality is unforgiving: the modern email ecosystem has evolved into a zero-trust, hostile network.

Every single day, billions of phishing attempts and automated spam campaigns hit mail servers globally. In response, enterprise receiving providers (Google Workspace / Gmail, Microsoft 365, Proton, Yahoo) have erected sophisticated algorithmic fortifications. To pass through their gates without getting relegated to the dreaded SPAM purgatory, an email must survive a multi-layered cryptographic, networking, and protocol gauntlet.

Recently, while configuring a sovereign self-hosted corporate mail stack powered by Stalwart Mail Server (a modern all-in-one mail server written in 100% Rust), we tackled a classic real-world dilemma: legitimate appointment confirmation emails consistently landing in Gmail’s spam folder, despite a spotless TLS certificate and a pristine server reputation.

Here is the comprehensive engineering post-mortem and practical architectural guide explaining why your emails end up in SPAM—and how to lock down your deliverability once and for all.


1. The Modern Gauntlet: How Inbound Email Is Actually Verified

Before inspecting common traps, let’s trace what happens under the hood when a sending server (such as your Stalwart instance) initiates delivery to Google’s or Microsoft’s MX servers:

+---------------------------------------------------------------------------------------+
|                 THE INBOUND VERIFICATION GAUNTLET (GMAIL / OUTLOOK)                   |
+---------------------------------------------------------------------------------------+

  [ Stalwart Server ]
   IPv4: 198.51.100.42
   IPv6: 2001:db8:a1b2::42
           │
           │  1. TCP port 25 connection & SMTP Handshake
           ▼
+───────────────────────────────────────────────────────────+
| STEP 1: Network & FCrDNS Validation (PTR)                 |
|  - Reverse DNS lookup on connecting IP (IPv4 AND IPv6)    | ──► Mismatch ? ──► [ SPAM / REJECT ]
|  - Bidirectional consistency with A/AAAA records         |
+──────────────────────────┬────────────────────────────────+
                           │ PASS (email.your-domain.com)
                           ▼
+───────────────────────────────────────────────────────────+
| STEP 2: SMTP Negotiation & EHLO Greeting                  |
|  - Sending client announces its FQDN: EHLO email.your-domain.com ──► "EHLO localhost" ? ──► [ SUSPECT ]
+──────────────────────────┬────────────────────────────────+
                           │ PASS
                           ▼
+───────────────────────────────────────────────────────────+
| STEP 3: SPF Verification (RFC 7208)                       |
|  - DNS TXT lookup on envelope Return-Path domain          | ──► Multiple spf1 TXTs ? ──► PermError
|  - Is connecting IP authorized in the SPF record?         | ──► Missing IP ? ──► SoftFail / Fail
+──────────────────────────┬────────────────────────────────+
                           │ PASS
                           ▼
+───────────────────────────────────────────────────────────+
| STEP 4: DKIM Cryptographic Signature Validation           |
|  - Public key retrieval via DNS TXT (selector._domainkey) | ──► Invalid signature ? ──► FAIL
|  - Body & header cryptographic integrity check            |
+──────────────────────────┬────────────────────────────────+
                           │ PASS
                           ▼
+───────────────────────────────────────────────────────────+
| STEP 5: DMARC Policy & Alignment                          |
|  - Does visible 'From:' domain match SPF/DKIM domains?    | ──► Misaligned ? ──► Quarantine/Reject
+──────────────────────────┬────────────────────────────────+
                           │ PASS
                           ▼
+───────────────────────────────────────────────────────────+
| STEP 6: MIME Hygiene & Content Heuristics                 |
|  - multipart/alternative present (text/plain mandatory)   | ──► Raw HTML only ? ──► SPAM Score ++
|  - Canonical RFC 5322 Message-ID & legitimate headers     |
+──────────────────────────┬────────────────────────────────+
                           │ CONFORMANT
                           ▼
                 ┌───────────────────┐
                 │    USER INBOX     │
                 │   (100% INBOX)    │
                 └───────────────────┘

If even one single link in this verification chain snaps, your message will be diverted away from the user’s primary inbox.


2. Five Invisible Traps That Send Your Emails to Purgatory

Trap 1: Forward-Confirmed Reverse DNS (FCrDNS) and the IPv6 Surprise

FCrDNS is the very first gatekeeper of any receiving mail transfer agent. The algorithm validates two reciprocal conditions:

  1. The source IP connecting to port 25 has a reverse DNS record (PTR) resolving to a fully qualified domain name (FQDN), such as email.your-domain.com.
  2. That domain name email.your-domain.com resolves forward (A or AAAA) back to that identical IP address.
+-----------------------------------------------------------------------+
|       FCrDNS TRUST LOOP (FORWARD-CONFIRMED REVERSE DNS)               |
+-----------------------------------------------------------------------+

        Forward Lookup (A / AAAA)
        email.your-domain.com  ───────►  198.51.100.42 (IPv4)
                               ───────►  2001:db8:a1b2::42 (IPv6)
                               ▲                  │
                               │                  │
                               │ Reverse (PTR)    │
                               └──────────────────┘

The Default Cloud / VPS Trap

When launching a virtual server on OVH, Hetzner, or AWS, the default reverse DNS points to generic provider infrastructure (e.g. vps-xxxxxx.vps.ovh.net). If you don’t explicitly update the PTR record in your provider console to match your mail hostname (email.your-domain.com), receiving servers will flag your IP as an unverified dynamic node.

The IPv6 Blindspot

This is where 80% of self-hosters stumble: you meticulously configure the reverse DNS for your IPv4 address, but completely ignore IPv6! When Google’s MX servers receive a connection from a dual-stack host, they automatically prefer IPv6. Stalwart establishes an IPv6 socket, Gmail performs a PTR lookup on the IPv6 address, encounters the generic host or an NXDOMAIN, and drops the email into SPAM with SPF: SOFTFAIL.

Golden Rule: Every production mail server must have reciprocal PTR records configured for BOTH its IPv4 and IPv6 addresses pointing to its sending FQDN.


Trap 2: Strict SPF Uniqueness (RFC 7208) and DNS Residuals

SPF (Sender Policy Framework) empowers domain owners to declare which IP addresses are authorized to dispatch emails on their behalf.

However, notice what section 3.2 of the RFC 7208 specification explicitly commands:

“A domain name MUST NOT have multiple records that would cause an authorization check to find more than one SPF record of version 1. If a domain name has multiple records, the result of the authorization check MUST be PermError.”

In short: if your DNS zone exposes more than one TXT record starting with v=spf1, the receiving server is formally mandated to treat the lookup as a Permanent Error (PermError) and flag the mail as untrusted.

During platform migrations or automated setups, DNS zones frequently accumulate toxic legacy entries:

  • An old record: v=spf1 include:mx.ovh.com ~all
  • An automated record generated by Stalwart: v=spf1 a -all
  • Accidental duplicates
  • Obsolete dedicated DNS SPF records (Type 99, officially deprecated in 2014)

The Solution: Surgical DNS Consolidation

Purge all conflicting records and maintain one single unified TXT SPF record:

; Root domain (your-domain.com)
your-domain.com.       300 IN TXT "v=spf1 mx a:email.your-domain.com ip4:198.51.100.42 ip6:2001:db8:a1b2::42 ~all"

; Sending mail host (email.your-domain.com)
email.your-domain.com. 300 IN TXT "v=spf1 a ip4:198.51.100.42 ip6:2001:db8:a1b2::42 -all"

Trap 3: The Ghost EHLO (EHLO localhost)

When an application backend (Node.js, Go, Python) relays an email to your local Stalwart instance or an upstream relay, the very first command uttered is the EHLO greeting:

C: EHLO localhost
S: 250-email.your-domain.com Hello localhost [127.0.0.1], pleased to meet you

Sending EHLO localhost or EHLO [127.0.0.1] is an immediate penalty in SpamAssassin, Rspamd, and Google Postmaster heuristics. Spammers and unmaintained malware bots frequently default to generic or unresolvable hostnames.

Production code must always supply an authentic, resolvable FQDN:

// TypeScript / Node.js best practice
const senderDomain = 'your-domain.com'; // or 'email.your-domain.com'
await client.write(`EHLO ${senderDomain}\r\n`);

Trap 4: Cryptographic DKIM and DMARC Alignment

Having a valid DKIM signature is only half the battle. DMARC requires that the signing domain cryptographically matches the visible address in the user’s From: header:

Visible 'From:' Header:   contact@your-domain.com           (Display Identity)
DKIM-Signature Header:    d=your-domain.com; s=stalwart;... (Cryptographic Identity)
SPF Return-Path Envelope: bounce@email.your-domain.com      (Envelope Identity)

Under relaxed alignment (aspf=r, adkim=r), DMARC permits subdomains (email.your-domain.com) to authenticate the root organization (your-domain.com). But if your application sends with From: contact@aivo.fr from an infrastructure that only signs for d=your-domain.com, DMARC alignment fails completely, triggering quarantine or spam filtering.

Stalwart provides best-in-class multi-tenant key management, supporting modern Ed25519 and RSA-2048 keys with automated per-domain selectors.


Trap 5: MIME Anatomy and RFC 5322 Conformance

Even with a perfect 10/10 DNS reputation, syntactical bugs in your email body will doom deliverability.

  1. Mandatory multipart/alternative structure: Broadcasting pure HTML (Content-Type: text/html) without an accompanying plain-text version (text/plain) is a major red flag for anti-spam engines. Standard clients always render multipart payloads containing both formats.
  2. Canonical Message-ID formatting: The Message-ID header must adhere strictly to RFC 5322 (<unique-uuid@sender-domain.com>). A missing or naked ID (or one generated with localhost) degrades deliverability.
  3. Automated processing headers: For transactional emails (calendar invites, password resets), injecting Auto-Submitted: auto-generated informs filters that the communication is expected and programmatic, lowering false-positive rates.

3. Why Stalwart Mail Server Is a Game Changer

For over two decades, self-hosting email meant duct-taping together a fragile web of disparate legacy daemons: Postfix for MTA, Dovecot for IMAP, OpenDKIM for signing, SpamAssassin or Rspamd for filtering, and MySQL or OpenLDAP for user stores.

One minor syntax error across dozens of configuration files would silently break delivery or leave ports exposed.

Stalwart Mail Server transforms this paradigm:

  • Engineered in 100% Safe Rust: Memory-safe by design, with ultra-low CPU and memory footprints.
  • Unified Single Binary: Native support for SMTP, JMAP (the modern JSON-based successor to IMAP), IMAP4, POP3, SPF, DKIM, DMARC, DANE, and ACME (automatic Let’s Encrypt certificates).
  • Zero-Configuration Cryptography: Built-in support for Ed25519 keys, automatic DMARC reporting (RUF/RUA), and automated key rotation.
  • Modern Administration: An intuitive web management console for domains, identities, and cryptographic keys.

4. Engineering Checklist: The 60-Second Terminal Audit

Audit your domain’s health directly from your terminal:

# 1. Verify you have EXACTLY ONE SPF record
dig TXT your-domain.com +short | grep -i "v=spf1"

# 2. Check bidirectional IPv4 consistency (A and PTR)
dig A email.your-domain.com +short
dig -x 198.51.100.42 +short

# 3. Check bidirectional IPv6 consistency (AAAA and PTR)
dig AAAA email.your-domain.com +short
dig -x 2001:db8:a1b2::42 +short

# 4. Verify DKIM public key
dig TXT stalwart._domainkey.your-domain.com +short

# 5. Verify DMARC policy
dig TXT _dmarc.your-domain.com +short

When your reverse DNS (PTR) exactly matches your server’s sending FQDN, your SPF is consolidated, and your DMARC alignment passes, your emails will reliably reach the inbox.


Conclusion: Digital Sovereignty Meets Technical Rigor

Self-hosting critical communication infrastructure is no longer the exclusive privilege of tech behemoths. Armed with modern tools like Stalwart and a deep grasp of networking standards, businesses can achieve complete data sovereignty without sacrificing deliverability.

True digital sovereignty is not built on slogans: it is forged in the precision of DNS records and the elegance of resilient software architectures.

#Stalwart #Deliverability #SMTP #DNS #Cybersecurity #DevOps #Sovereignty
Nicolas BAUD

Nicolas BAUD

Fractional CTO & AI/IS Architect • AMOA Consulting
Founder & Lead Architect at AIVO

Solutions Architect and Fractional CTO with over 15 years of experience, Nicolas BAUD assists organizations in securing their IT infrastructure, deploying sovereign AI architectures, and implementing software eco-design.

Table of Contents