Relaying email from your Ubuntu VPS using Postfix
published on
In this tutorial I will describe how to set up Postfix on your VPS so that emails can be relayed to another server which will send your email for you. This can be used with your GMail or Outlook email account.
Install Postfix
Run the following command to install Postfix and some other required packages: sudo apt install postfix libsasl2-modules mailutils.
When you are asked to configure Postfix choose Internet Site and set the system name to be your domain name (e.g. if your server hostname is host1.example.com your system name should be example.com).
Now let us set up Postfix
Edit the/etc/postfix/main.cf file and edit it so that the matching lines look like the ones below:
myhostname = <your-domain>relay_domains =masquerade_domains = <your-domain>relayhost = <email-server>:<port>inet_interfaces = loopback-only# outbound relay configurationssmtp_sasl_auth_enable = yessmtp_sasl_password_maps = hash:/etc/postfix/sasl_passwdsmtp_sasl_security_options = noanonymoussmtp_use_tls = yessmtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crtsmtp_tls_security_level = mayheader_size_limit = 4096000virtual_alias_maps = hash:/etc/postfix/virtualsmtp_generic_maps = hash:/etc/postfix/generic
Make sure <your-domain>, <email-server> and <port> are set to the correct values for your email provider.
Now edit the /etc/postfix/master.cf file and alter the necessary parts to look like the two lines below:
-o smtpd_sender_restrictions=reject_unknown_sender_domain-o smtpd_recipient_restrictions=permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
Next, create a password file by editing /etc/postfix/sasl_passwd and adding the following line (making sure to replace with your own settings):
<email-server-address>:<port> <email-username>:<email-password>
Now run the following four commands to allow Postfix to use the settings you have just entered:
sudo postmap /etc/postfix/sasl_passwdsudo systemctl restart postfixsudo chown root:root /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.dbsudo chmod 0600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
Finally, create a virtual aliases file by running the following two commands (again, make sure to use your own email address here):
sudo echo "root: <your-email-address>" >> /etc/aliasesnewaliases
Test your work
You probably now want to test that you have a working system. This can be done by running the following command and checking you received the email:
echo "This is a test email" | mailx -r <mail-from-address> -s Hello <mail-to-address>
If this works then you are finished. If not go back over the above again to configure Postfix properly.
