Configure Postfix as a relay
Configure postfix as relay for macOS Monterey using gmail SMTP as a gateway
1. Configure Postfix
Edit main.cf file
sudo vi /etc/postfix/main.cf
Ensure the following values are set as shown below
mail_owner = _postfix
setgid_group = _postdrop
And add the following lines at the end of the file
relayhost=smtp.gmail.com:587
smtp_sasl_auth_enable=yes
smtp_sasl_password_maps=hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options=noanonymous
smtp_sasl_mechanism_filter=plain
smtp_use_tls=yes
smtp_tls_security_level=encrypt
tls_random_source=dev:/dev/urandom
transport_maps = pcre:/etc/postfix/transport_maps
2. Generating the app password
Goto your gmail account. Click on your profile picture, from the dropdown select Manage your Google Account. Select Security tab from the right hand menu. In the Signing in to Google section, enable 2-Step Verification & then from the App Password generate a password
3. Create a credentials file
This file would be a combination of the SMTP endpoint as well as your email and password to authenticate the SMTP calls.
sudo sh -c 'echo "\nsmtp.gmail.com:587 [email protected]:your_password" >> /etc/postfix/sasl_passwd'
Replace both the email to your actual email and the password to your app password generated earlier in step 2.
Add the credential file to Postfix lookup table
sudo postmap /etc/postfix/sasl_passwd
4. Reloading Postfix
Reload the postfix
sudo postfix reload
5. Testing
Now that we have configured Postfix, created credential file, added it to the Postfix lookup, reloaded the Postfix service. We can now test it by sending an email from our system. It can be tested several way one of which would be to send a test email via command-line as below
echo "This is a test email body." | mail -s "Test Subject" [email protected]
6. Debugging
To check the mail queue list
postqueue -p # OR
mailq
To delete email from the queue
sudo postsuper -d QUEUE_ID # OR to delete all
sudo postsuper -d ALL
To flush the mail queue
postqueue -f # OR
sudo postfix flush
7. What's Next
Sending test emails from local machine is great however it is a good idea to stop any emails from the local machine going out to the actual clients. To block such emails. Follow the following steps
Since we have the following line added already
transport_maps = pcre:/etc/postfix/transport_maps
Let's create that file with
sudo vi /etc/postfix/transport_maps
and add the following lines to stop emails to all emails expect the one allowed
/^(?!USERNAME).*\@.*\.com$/ discard:
/.*/ :
In the above regex, change the USERNAME to your own username. It will match all emails and discard those except the one with the username added with any hostname at the end. for example
[email protected] # will not match
[email protected] # will match and be discarded
Reload the postfix
sudo postfix reload