Skip to content

Relay via Mailgun / SendGrid — the smarthost pattern for outbound deliverability

Configure Postfix to relay outbound mail through Mailgun, SendGrid, or AWS SES with SASL auth, vendor-specific DKIM via CNAME, and per-domain transport routing.

Some clients should not deliver mail from their own IP. A new domain has no sender reputation; a low-volume box can’t keep its IP warm; a marketing list pegs deliverability into the floor for transactional mail on the same IP. The fix is to relay outbound through an Email Service Provider — Mailgun, SendGrid, AWS SES, Postmark, SparkPost — that has the reputation, the warming, and the receivers’ allow-list. This article is the Postfix smarthost pattern we apply, with the wrinkles per vendor.

How to verify

Audit current outbound posture.

sudo postconf | grep -E 'relayhost|smtp_sasl|smtp_tls'
ls -l /etc/postfix/sasl_passwd*
dig +short MX example.com
dig +short TXT example.com
dig +short TXT mg.example.com  # for Mailgun CNAME setup

A box with relayhost = empty delivers direct (look up MX, connect). The transformation moves this to relayhost = [smtp.vendor.com]:587 with SASL.

What’s happening

The relay pattern is conceptually simple: instead of Postfix looking up MX records and delivering directly, it hands every outbound message to the ESP’s submission endpoint with SMTP AUTH. The ESP queues, signs with its own DKIM, applies its IP warming pool, and delivers.

The non-obvious operational details:

  1. DKIM alignment for the customer domain. The ESP signs with its d= by default (e.g. d=mg.mailgun.org). For DMARC aspf=r to pass, the ESP must either sign with d=example.com directly (some support this with a “domain authentication” or “verified domain” feature, usually via a CNAME chain) or you sign locally with OpenDKIM before relaying.
  2. Return-Path / bounces. The ESP rewrites Return-Path to its own bounce-handling subdomain. Bounces land at the ESP, not at your Postfix. The ESP exposes a webhook or an API for bounce data; pipe that into your suppression list — see bouncehammer-postfix-bounces.
  3. Cost per message. ESPs charge per message after a free tier. The transactional traffic of a busy SaaS can hit costs surprisingly fast; budget before committing.
  4. SRS rewriting. If your Postfix forwards mail (e.g. role accounts, group aliases), it should rewrite the envelope sender so the ESP sees its own domain as the sender — see postsrsd-srs-forwarding-rewrite.

The procedure (Mailgun example)

  1. Provision a sending domain in the Mailgun panel. This generates DNS records you must publish:

    ; SPF — add Mailgun to your existing record
    example.com.            IN TXT  "v=spf1 include:mailgun.org ~all"
    
    ; DKIM — Mailgun publishes the key under their TXT record
    smtp._domainkey.example.com.  IN TXT  "k=rsa; p=MIIBIjANBgkq..."
    
    ; MX for Mailgun's bounce subdomain (optional, recommended)
    mg.example.com.         IN MX    10 mxa.mailgun.org.
    mg.example.com.         IN MX    10 mxb.mailgun.org.

    In the Mailgun UI, click “Verify” — they probe DNS until all records are present.

  2. Generate or retrieve the SMTP credentials. Mailgun → Sending → Domain settings → SMTP credentials. The format is postmaster@mg.example.com and a strong random password.

  3. Configure Postfix relayhost:

    relayhost = [smtp.mailgun.org]:587
    smtp_sasl_auth_enable = yes
    smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
    smtp_sasl_security_options = noanonymous
    smtp_tls_security_level = encrypt
    smtp_tls_note_starttls_offer = yes
    header_size_limit = 4096000
  4. Write the SASL password file:

    sudo tee /etc/postfix/sasl_passwd <<EOF
    [smtp.mailgun.org]:587  postmaster@mg.example.com:strong-mailgun-pw
    EOF
    sudo postmap hash:/etc/postfix/sasl_passwd
    sudo chown root:root /etc/postfix/sasl_passwd*
    sudo chmod 600 /etc/postfix/sasl_passwd*
  5. Reload and probe:

    sudo postfix check
    sudo systemctl reload postfix
    echo "test" | mail -s "mailgun relay probe" you@external.com
    sudo journalctl -u postfix -f

    Log should show relay=smtp.mailgun.org[...]:587, ... status=sent.

SendGrid

Same pattern, different endpoint. The credential is an API key prefixed with apikey: as the SASL user, the API key itself as the password:

# /etc/postfix/sasl_passwd
[smtp.sendgrid.net]:587  apikey:SG.<the-api-key-value>
relayhost = [smtp.sendgrid.net]:587

SendGrid’s DKIM is a CNAME chain — they publish keys at their domain, you CNAME s1._domainkey.example.com → s1.domainkey.uXXXX.wlYYY.sendgrid.net. Their domain authentication UI walks you through the records.

AWS SES

SES uses a per-region SMTP endpoint:

relayhost = [email-smtp.us-east-1.amazonaws.com]:587

The SMTP credentials are NOT your AWS access keys directly — they are derived from your IAM access keys via SES’s smtp-credentials conversion. The SES console offers a one-click “Generate SMTP credentials” that does this for you.

SES has a sandbox mode that limits sending to verified recipients; new accounts must request production access before relaying real traffic.

Per-domain routing — send some via ESP, some direct

Use postfix-transport-maps-routing to route only specific traffic through the ESP:

# /etc/postfix/transport
example.com         smtp:[smtp.mailgun.org]:587
example.com.fr      smtp:[smtp.mailgun.org]:587
# everything else uses the default smtp transport (direct delivery)

Combine with a custom smtp-mailgun service in master.cf that has its own SASL config — useful when you want different ESP credentials per domain.

Operational notes

  • The SASL password file is high-value; lock it to 600 root:root. The compiled .db has the same.
  • Mailgun’s free tier covers ~5000 msg/month; busy SaaS exceeds this in a day. Set up billing alerts at 50% / 80% / 100%.
  • SendGrid’s reputation is dynamic; a shared IP pool can change. Pay for a dedicated IP if your DMARC RUA reports show sender-IP variance.
  • All ESPs throttle on signup. Mailgun’s first 24 hours have a low ceiling; SES’s sandbox; SendGrid’s verification. Plan launches accordingly.
  • DMARC aspf=s (strict alignment) breaks ESP relay because the envelope MAIL FROM is the ESP’s bounce domain. Use aspf=r (relaxed) and let DKIM carry alignment.

Common pitfalls

  • The DKIM CNAME chain for SendGrid points to the wrong shard; messages send but DKIM doesn’t verify — the SendGrid UI reports red until both s1._domainkey and s2._domainkey CNAMEs land correctly.
  • The sasl_passwd file has trailing whitespace on the password line; postmap accepts it, smtp fails auth with “Username and Password not accepted” — verify with postmap -q "[smtp.mailgun.org]:587" hash:/etc/postfix/sasl_passwd.
  • Mailgun’s mg.example.com subdomain has its own MX pointing at Mailgun; the parent example.com is unchanged. Some tutorials mix the two — keep the parent domain’s MX pointed at your own MX if you still receive mail there.
  • SES sandbox mode silently rejects unverified recipients with 554 Message rejected: Email address is not verified — new accounts must explicitly request production access through the SES console.
  • The ESP’s TLS root CA is missing from the Postfix CA bundle (rare on Ubuntu, common in stripped containers); smtp_tls_security_level = encrypt fails on cert verification. Install ca-certificates and confirm.

Stack Harbor stands up ESP relays as the deliverability layer for clients without warm IPs in the engagements we run — DNS records published from version-controlled zone data, SASL credentials rotated quarterly, bounces piped into the suppression list, DMARC RUA reports monitored for alignment. If you have a Postfix that ships mail directly and lands in junk, the ESP-pivot decision is part of our Managed Operations practice.