How to set up Postfix on Debian 11 to use a mailhoster with SMTP

Latest update: Aug 2022

Important notes

  • Make sure you use your own hostname below. I used mx2f95.netcup.net only for testing purposes. This will not work for you. The hostname entry has to be identical to the entry in the password file sasl_passwd.
  • “said: 451 4.3.0 pymilter: untrapped exception in pythonfilter (in reply to end of DATA command)”
    In case you run across an error like this and your mails are not going to be sent out, then I strongly encourage you to try the -r switch followed by your source address, which overrides any ‘from’ variable specified in environment. There are some mailhosters like Netcup for instance, which are quite picky about the ‘from’ variable. I’ve spend hours and hours to find that out by testing every configuration you can imagine. For some completely unlogical reason the same error occured when the ‘mail content’ had too few characters. For instance just ‘content’ didn’t work.

Installation of packages

sudo apt install postfix mailutils libsasl2-2 ca-certificates libsas2-modules

Configuration of Postfix

sudo nano /etc/postfix/main.cf
relayhost = [mx2f95.netcup.net]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_use_tls = yes

Configuration of password file

sudo nano /etc/postfix/sasl_passwd
[mx2f95.netcup.net]:587 sourceaddress@domain.com:yourpassword
sudo chmod 400 /etc/postfix/sasl_passwd
sudo postmap /etc/postficx/sasl_passwd

Testing

echo "mail content" | sudo mail -s "Test" -a "From: Notification System<sourceaddress@domain.com>" destinationaddress@domain.com -r sourceaddress@domain.com

Troubleshooting

# you can check the mail logs
sudo tail -f /var/log/mail.log

# or even the system log if you need to dive deeper
sudo tail -f /var/log/syslog

# if the output is barely readable you can pass it to an optical highlighter
# make sure you install the lnav package first
sudo tail -f /var/log/mail.log | lnav

# if there is too much crap in terms of old mail entries you can flush the whole mail queue
sudo postsuper -d ALL

# if you just need to check the current queue list
sudo mailq