Postfix: selecting relay host based on From: mail header rather than envelope sender

Solution 1:

Based on this thread on postfix mailing-list: different transport for all mail introduced via sendmail(1), looks like your case was possible. Unfortunately you can't only rely on two tables sender_dependent_relayhost_maps and smtp_sasl_password_maps. You need modify master.cf. The idea is using header_checks to route email to different transport. Then in each transport, we define smtp client that use independent credential and relayhost.

First define header_checks in main.cf and its pcre table

#main.cf
header_checks = pcre:/etc/postfix/header_dependent_relay

#/etc/postfix/header_dependent_relay

/^From:.*specialsender1\@example\.com/       smtp1:[host1.example.com]
/^From:.*specialsender2\@example\.com/       smtp2:[host2.example.com]
/^From:.*specialsender3\@example\.com/       smtp3:[host3.example.com]

Good, now we setup smtp1,smtp2,smtp3 transport in master.cf

#master.cf
smtp1    unix  -       -       -       -       10       smtp
    -o smtp_sasl_password_maps=hash:/etc/postfix/smtp1.relay
smtp2    unix  -       -       -       -       10       smtp
    -o smtp_sasl_password_maps=hash:/etc/postfix/smtp2.relay
smtp3    unix  -       -       -       -       10       smtp
    -o smtp_sasl_password_maps=hash:/etc/postfix/smtp3.relay

File smtpX.relay has similar content e.g.

[hostX.example.com]   userX:passwordX

Disclaimer:

  • The hash table of smtp_sasl_password_maps is only for example. You can replace it with mysql table.
  • You can also replace pcre table of header_checks with combination of SELECT and REGEXP in MySQL . But it may kill your database as postfix will hit MySQL for every header line

Solution 2:

This worked for me with one change: the action "FILTER" needs to be added in the header_dependent_relay file:

#/etc/postfix/header_dependent_relay

/^From:.*specialsender1\@example\.com/       FILTER smtp1:[host1.example.com]
/^From:.*specialsender2\@example\.com/       FILTER smtp2:[host2.example.com]
/^From:.*specialsender3\@example\.com/       FILTER smtp3:[host3.example.com]

See http://www.postfix.org/header_checks.5.html