My new employer, Mail.Ru, allows its SMTP servers to relay mails from senders that use their corporate email addresses only. Erm, to be more accurate, the authenticated user must match "From" field of the mail. Since I also have a personal mail at @mail.ru, and an account at gmail.com, my mail sent from these accounts was (until today!) bounced.

This would be a simple problem to solve if I used a "modern mail client", but since I use a somewhat archaic, but very powerful chain of mutt + postfix + procmail  + sendmail, I had to find a tweak for the default (and simple) Postfix configuration and make it support multiple relay hosts.

It turns out that Postfix option that allows you to choose a relay host based on the "From" address is called sender_dependent_relayhost_maps. The docs for the option are rather scarce, and there aren’t many examples online either, but my setting is pretty simple so I managed to make it work. Here’s what I had to do:

  • Remove the default 'relayhost' map from /etc/postfix/main.cf:
relayhost = 
  • Add sender_dependent_relayhost_maps to main.cf:
sender_dependent_relayhost_maps = hash:/etc/postfix/relayhost_maps
  • Populate relayhost_maps and create a .db file:
kostja@shmita:~$ cat /etc/postfix/relayhost_maps
username@mail.ru             smtp.mail.ru
username@xxxx.xxxx.ru        smtp.xxxx.xxxx.ru
username@gmail.com           [smtp.gmail.com]:587
kostja@shmita:~$ sudo postmap /etc/postfix/relayhost_maps
  • Provide sasl_passwd (user/password) file entries for all hosts:
kostja@shmita:~$ sudo cat /etc/postfix/sasl_passwd
smtp.xxxx.xxxx.xx      username@xxxx.xxxx.ru:password
smtp.mail.ru           username@mail.ru:password
[smtp.gmail.com]:587   username@gmail.com:password
kostja@shmita:~$ sudo postmap /etc/postfix/sasl_passwd

Voila, this was sufficient for Postfix to start routing the mail correctly. GMail requires TLS and certificate files to accept mail on its smtp hosts, but this topic is very well covered in blogs, e.g. here.