Enable Relay and Rewrite Sender for Postfix in FreePBX for Microsoft 365 or Google Workspace

See the following tutorial for enabling relay and sender rewriting for FreePBX and Postfix. Rewrites are important when relaying via 365 as you must use the mailbox sender address, for Google it accepts and sends regardless of the sender. The tutorial below is for Google Workspace, but can be used with Microsoft 365 by simply changing the SMTP server to "smtp.office365.com".

cd /etc/postfix

Create an SMTP server password file and hash it.

echo "smtp.gmail.com:587 user@domain.com:password" > /etc/postfix/sasl_passwd
postmap /etc/postfix/sasl_passwd
rm /etc/postfix/sasl_passwd

Create an smtp_header_checks file.

echo "/^From:.*/ REPLACE From: PBX Display Name <pbx@mypbx.com>" > /etc/postfix/smtp_header_checks

Add the following code to the end of main.cf:

# header checks to rewrite
smtp_header_checks = pcre:/etc/postfix/smtp_header_checks

# smart host forwarding
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sasl_type = cyrus
smtp_use_tls = yes
smtp_tls_CAfile = /etc/pki/tls/certs/ca-bundle.crt
relayhost = smtp.gmail.com:587

Note this tutorial can be adapted to almost any Postfix linux system, providing you install this dependency:

yum install postfix mailx cyrus-sasl-plain