I have several PHP (and WordPress) projects on a Ubuntu server and the mails sent from the server are always been an issue.
Even with a good DNS configuration some receiver will mark the mail from your server as spam.
I use Mxroute as mail server and relay, and you should too, but this configuration work with almost all majors relay server
Introduction mail functions and daemons
In PHP the mails are sent trough the function mail() and, by default, using the daemon sendmail
Postfix has better options, like relay; when installed it should takeover on what sendmail does.
Before going into Postfix and Relay configuration, if you are a WordPress user, there is a way to use a relay trough the function wp_mail() and a plugin called wp-smtp
That plugin use PhpMailer/WPSMTP that is included in the WordPress core
But external scripts or plugin that keep using the function mail() will not use the relay, so the next steps are to configure the server in a way to use the relay even when a script call the mail() function.
Purge Sendmail, install Postfix (mailutils)
sudo apt update sudo service sendmail stop sudo apt-get purge sendmail* sudo apt install mailutils
Postfix configuration (base)
Follow this guide (Ubunt 20.4) for postfix basic configuration
Send mail without relay may result in a spam tag
Using a trusted relay often result in a better mail deliverability, I personally use Mxroute, but there are many out there
Edit Postfix configuration
First i have create a recipient called firstname.lastname@example.org
Second i add those lines to my main.cf
relayhost = [22.214.171.124]:587 smtp_sasl_auth_enable = yes smtp_sasl_security_options = noanonymous smtp_tls_security_level = encrypt header_size_limit = 4096000 smtp_use_tls = yes smtp_tls_loglevel = 1 smtp_sasl_mechanism_filter = login smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd smtp_generic_maps = hash:/etc/postfix/gener
126.96.36.199 (use your relay ip)
smtp_sasl_password_maps contain relay address user and password of noreply@
smtp_generic_maps <– in this file I override the sender, the file generin contain the this string [email@example.com firstname.lastname@example.org], in this way the receive mail got the pass instead the neutral (as the account is validated)
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination <– this line is very important to avoid spam
Error: SASL authentication failed; cannot authenticate to server 188.8.131.52[184.108.40.206]: no mechanism available
Many system may have a connection refused due the fact the postfix need libsals2 or you will get that error.
sudo apt-get update sudo apt-get -y install libsasl2-modules
And this is all, restart the services (Apache and postfix) and you should be able to send mail using mail() through a relay
Questions? Suggestions? Please leave a comment below.