Postfix: Routing outgoing email based on sender domain

I was in a situation where I needed to implement a mail routing policy: Outgoing email from a specific domain gets routed through a relay (eg. Amazon SES) and all other goes directly.

Situation

  • We have a Postfix server which acts both as a receiver and a sender.
  • We want to route all mails with MAIL FROM header containing @example.com via Amazon SES (Simple Email Service) relay.
  • Email with other MAIL FROM headers will be sent directly, without using SES.

 

 

Configuration

/etc/postfix/main.cf

# Domain-based outgoing email relay policy
sender_dependent_relayhost_maps = hash:/etc/postfix/relay_maps
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

This is the main part of the configuration. We tell Postfix to look for so-called “sender dependent relayhost maps” in a hashed file with the specified path.
We also enable authentication and tell Postfix in which file the access credentials are stored. Enabling TLS encryption is also a very good idea.

 

/etc/postfix/relay_maps

@example.com      [email-smtp.eu-west-1.amazonaws.com]:587

Here we set what goes where. With this configuration every email originating from example.com will go through mail relay at email-smtp.eu-west-1.amazonaws.com using port 587

 

/etc/postfix/sasl_passwd

[email-smtp.eu-west-1.amazonaws.com]:587 USER:PASSW0RD

The relay service will provide you with authentication details, which you need to enter here.

 

Remember to run postmap on both files after any change to them.

 

Notes

Don’t forget to properly modify your SPF setup – you need to tell the world that SES (or other relay service for that matter) is permitted to send emails on behalf of your domain. There is a probability that your emails would end up marked as spam otherwise.

4 Comments

Add yours

  1. Hi Tanks for that but how can we do for the sender_dependent_relayhost_maps dont be overruled by transport_maps ?

  2. Hi, As far as I’m aware, sender_dependent_relayhost_maps has a fairly low priority, meanwhile transport_maps has a pretty high priority. I don’t think you can overwrite the latter with the former.

  3. Alex Gerulaitis

    June 12, 2020 — 6:53 pm

    Thanks Filip – this is great! One question: if I need to route not just @domain email but any subdomains as well (e.g. @.domain) – what is the correct way to do this? Tried “.domain”, “.domain” – doesn’t seem to work.

    • “but any subdomains as well ”
      Either use the transport_table_map, or another format, not a hash table but a pcre-table with patterns.

Leave a Reply...