Setting up an SMTP relay on a Linux server can help manage outgoing emails more effectively and can prevent your mail server from being flagged for spam. Below is a step-by-step guide for configuring an SMTP relay with Postfix
, a commonly used mail transfer agent on Linux.
Prerequisites #
- A Linux server with root access.
Postfix
installed (you can install it usingapt install postfix
on Debian/Ubuntu oryum install postfix
on RHEL/CentOS).- An SMTP relay service provider such as SendGrid, Mailgun, Amazon SES, or an existing external SMTP server.
Step 1: Install Postfix #
- Install postfix using these steps if you are on Ubuntu and with these steps if you are on Almalinux.
Step 2: Configure Postfix for SMTP Relay #
- Edit the Postfix configuration file located at
/etc/postfix/main.cf
:
sudo vi /etc/postfix/main.cf
- Look for the relayhost, settings usually looking as below or add them if they are missing.
relayhost =
- You will then modify the setting and add your SMTP relay hostname and port number. E.g, If I want to relay my emails through a server with hostname as relayhost = [smtp.relayhost.com]:587 on port 587, I will set my relay host as below
relayhost = smtp.truehost.com:587

- If you use a firewall, you may need to allow the port that you used in your relayhost line through the firewall.
- If you use firewalld, you can use the command below, replacing 1234 with the port that you want to allow
sudo firewall-cmd --permanent --add-port=1234/tcp

Step 5: Restart Postfix
- After making these changes, restart the Postfix service for the changes to take effect:
sudo systemctl restart postfix
Step 6: Test the Configuration #
- To verify that the relay is working, you can send a test email. Use the
mail
command or any other mail client. - Replace
recipient@example.com
with an actual email address to test.
echo "This is a test email" | mail -s "Test Email" recipient@example.com
- To view the logs and troubleshoot if the email was not sent, check the Postfix log file:
Additional Configuration Tips #
- Setting a Default Sender Domain: You can specify the default sender domain by setting
myorigin
in/etc/postfix/main.cf
. - Rate Limiting: To avoid getting flagged by your relay provider, you can limit the number of outgoing emails in Postfix with additional configuration settings (useful for high-volume email applications).
- Firewall Rules: Ensure that your server’s firewall allows outgoing connections to the relay’s SMTP port (e.g., port 587 or 465).
You should now have a working SMTP relay configured on your Linux server using Postfix! This setup will relay all outgoing emails through the specified SMTP server, providing more reliable delivery and reducing the chances of your emails being marked as spam.