email

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 configurations
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_use_tls = yes
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_tls_security_level = may
header_size_limit = 4096000
virtual_alias_maps = hash:/etc/postfix/virtual
smtp_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_passwd
sudo systemctl restart postfix
sudo chown root:root /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
sudo 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/aliases
newaliases

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.