Rewrite “from” for specific “to” addresses

amazon-sesamazon-web-servicesemail-serverpostfix

We have a setup where postfix sends mails via Amazon SES relay. All is working fine except email forwards.

While this topic has already been discuessed at least here and here, there are still some points which I can't wrap my head around.

The problem is that Amazon SES won't send emails, where From: is not verified. So when an internal address wants to forward to an external and the sender is external as well, the mail will not get sent.

To solve this, we currently use the following config in main.cf

header_checks = regexp:/etc/postfix/first_header_checks
smtp_header_checks = regexp:/etc/postfix/second_header_checks
sender_canonical_maps = regexp:/etc/postfix/sender_canonical
sender_canonical_classes = envelope_sender
smtpd_data_restrictions = check_sender_access pcre:/etc/postfix/sender_access

With first_header_checks

/^From:(\s)?(.*)/i PREPEND X-Original-From: $2
/^To:(\s)?(.*)$/i PREPEND X-Original-To: $2

second_header_checks

/^From:(.*)/i REPLACE From: <no-reply@verified-domain.com>

sender_canonical

/.*/    user@verified-domain.com

sender_access

/(.*)/  prepend Reply-To: <$1>

This works great for incoming mail. user@external.com sends the mail to me@verified-domain.com and it gets forwarded to new@another-external.com

Reply-To: <user@external.com>
X-Original-To: <me@verified-domain.com>
To: new@another-external.com
From: <no-reply@verified-domain.com>
X-Original-From: <user@external.com>

The problem, this also happens for outgoing mail from the server. Say me@verified-domain.com sends a mail, the from gets rewritten to no-reply and a Reply-To will be set. This I want to fix. The mail headers should only be rewritten for incoming mail that will be forwarded.

I have tried using regular expressions like !/^From:(\s)?(.*@verified-domain\.com)/ but so far with no luck.

Best Answer

Postfix 2.1 and above supports conditional operators within regex and pcre tables. In your case second_header_checks using these conditionals should look like this:

if !/^From:(.*)@verified-domain.com/i
/^From:(.*)/i REPLACE From: <no-reply@verified-domain.com>
endif

You can test your lookup tables without actually sending anything like this:

peter@mail:~peter $ cat msgheaders
From: <peter@external.com>
To: new@another-external.com

peter@mail:~peter $ postmap -hmq - regexp:/etc/postfix/second_header_checks < msgheaders
From: <peter@external.com>     REPLACE From: <no-reply@verified-domain.com>

peter@mail:~peter $ cat msgheaders-1
From: <peter@verified-domain.com>
To: new@another-external.com

peter@mail:~peter $ postmap -hmq - regexp:/etc/postfix/second_header_checks < msgheaders-1
peter@mail:~peter $