Why Email Relay Services Matter for Server-Based Email
When you send email directly from your server, it originates from an IP address that has no established sender reputation. Email providers such as Google, Microsoft, and Apple maintain blocklists and reputation scores for sending IP addresses. A fresh IP address starts with no reputation, and messages from it are often scrutinised heavily or blocked entirely.
This is where a mail relay service becomes valuable. Instead of your server sending directly to the recipient's mail server, it hands the email to the relay service over an authenticated SMTP connection. The relay service then delivers the email using its own infrastructure, which already has established IP addresses and domain reputations built up over time. The result is that your emails are far more likely to reach the inbox rather than the spam folder.
Popular relay services include Mailgun, SendGrid, Postmark, Amazon SES, and Mailjet. Each offers SMTP access and detailed delivery logging, though pricing models and features vary. For this guide, the focus is on Mailgun, though the Postfix configuration principles apply to most SMTP-based relay providers.
How Postfix Fits Into the Email Delivery Picture
Postfix is the default Mail Transfer Agent on Ubuntu and many other Linux distributions. It handles outgoing mail queuing, routing, and delivery. By default, Postfix attempts to deliver email directly to the recipient's mail server via DNS MX lookups. When you configure it to use a relay host, Postfix forwards all eligible mail to that relay instead, which then handles the actual delivery.
This separation of responsibilities matters. Your server handles local mail generation and queuing. The relay service handles reputation management, retry logic, and inbox placement. Configuring Postfix correctly is the key step that ties these two parts together.
Installing Required Packages
Before configuring Postfix, make sure the necessary packages are installed. The postfix package is typically already present on Ubuntu servers. You also need libsasl2-modules, which provides the SASL authentication libraries that Postfix uses to authenticate with the relay service.
sudo apt install postfix libsasl2-modules
If Postfix is not yet installed, the package manager will pull it in. During installation, you may be prompted to choose a mail server configuration type. Select Internet Site and accept the default system mail name unless you have specific requirements.
Configuring Postfix to Use Mailgun as a Relay Host
Open the Postfix configuration file and add the relay settings. The key parameters control which relay host to use, how to authenticate, and which security level to enforce for the SMTP connection.
sudo nano /etc/postfix/main.cf
Add or update the following lines in the configuration file:
relayhost = [smtp.mailgun.org]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_security_level = encrypt
smtp_sasl_tls_security_options = noanonymous
Each parameter serves a specific purpose. The relayhost directive tells Postfix to forward mail to Mailgun's SMTP endpoint on port 587. The smtp_sasl_auth_enable option activates SASL authentication, which is required by Mailgun. The smtp_tls_security_level = encrypt setting enforces TLS encryption for the connection, ensuring credentials and email content are not transmitted in plain text.
Storing Relay Credentials Securely
Create a file to store the SASL username and password that Postfix uses to authenticate with Mailgun. This file maps the relay host to the credentials.
sudo nano /etc/postfix/sasl_passwd
Add a single line in the format relay_host username:password. For Mailgun, use the SMTP login credentials from your Mailgun dashboard:
[smtp.mailgun.org]:587 [email protected]:your_smtp_password
Hash the password file to create a lookup table that Postfix can use efficiently. Then secure the file so that only the root user can read it.
sudo postmap /etc/postfix/sasl_passwd
sudo chown root:root /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
sudo chmod 600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
The hashed database file sasl_passwd.db is what Postfix actually reads at runtime. Never leave the plain-text password file readable by other users on the system.
Applying the Configuration
Once the configuration file and credentials are in place, reload Postfix to apply the changes without interrupting existing mail delivery.
sudo postfix reload
Verify the configuration loaded correctly by checking the Postfix logs for any errors related to SASL authentication or TLS handshake.
sudo tail -20 /var/log/mail.log
If you see entries indicating that Postfix connected to the relay and authenticated successfully, the basic setup is working.
Testing the Relay Configuration
Send a test email to confirm that mail flows through the relay and reaches the destination. Use a real email address that you can check, and consider using a throwaway address first in case of issues.
echo "Test email body" | mail -s "Postfix Relay Test" [email protected]
After sending, check your Mailgun dashboard for delivery status. If the email appears in the logs but was not delivered, the dashboard usually provides a reason such as a bounced recipient or a spam score issue.
For deeper testing, examine the Postfix queue and logs directly.
mailq
tail -50 /var/log/mail.log
The mailq command shows any messages that are still queued. If a message has been delivered, it disappears from the queue. The log file shows the handshake, authentication, and delivery attempts in chronological order.
Setting Up SPF, DKIM, and DMARC for Your Sending Domain
Using a relay service does not remove the need for proper email authentication. Without SPF, DKIM, and DMARC records configured for your domain, recipient servers may still treat your emails as suspicious or reject them entirely.
In your Mailgun dashboard, add your sending domain and follow the instructions to add the required DNS records. Mailgun generates custom records for your domain, including an SPF record that authorises Mailgun's servers to send mail on your behalf and a DKIM record with a cryptographic key that verifies message integrity.
v=spf1 include:mgmtechbook.com ~all
k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA...
If you already have an SPF record because you send email from other sources, merge the records rather than replacing them. An SPF record should contain only one v=spf1 directive, so combine the include statements from all sending sources into a single record.
DMARC adds another layer by telling receiving servers what to do when emails fail authentication. Set up a DMARC record for your domain to complement the SPF and DKIM setup. A basic DMARC record instructs receiving servers to quarantine failing emails and send aggregate reports to an email address you control.
v=DMARC1; p=quarantine; rua=mailto:[email protected]; pct=100
Consider starting with a less strict policy such as p=none initially to monitor your authentication results before moving to quarantine or reject policies. Understanding your baseline delivery performance helps you adjust settings safely without risking legitimate emails being blocked during the transition.
For a more detailed walkthrough of SPF, DKIM, and DMARC setup alongside practical deliverability tips, the guide on email deliverability covers this process step by step.
Routing Different Email Types Through Separate Services
Some setups benefit from sending transactional emails through one provider and marketing emails through another. Postfix supports this through sender-dependent relay maps, which route mail based on the sender address rather than applying a single relay to all outgoing mail.
For example, you might want transactional emails from your main domain to go through Mailgun while marketing emails from a subdomain use a different service. This separation can improve deliverability for each email type and gives you better control over sender reputation for each category.
Configure sender-dependent routing in /etc/postfix/main.cf:
sender_dependent_relayhost_maps = hash:/etc/postfix/sender_relay
Create the relay map file with the routing rules:
sudo nano /etc/postfix/sender_relay
@marketing.yourdomain.com [smtp.sendgrid.net]:587
@yourdomain.com [smtp.mailgun.org]:587
Generate the hash database and reload Postfix:
sudo postmap /etc/postfix/sender_relay
sudo postfix reload
You also need to create separate SASL credential files for each relay host, since each service has its own authentication credentials. For instance, sasl_passwd_sendgrid and sasl_passwd_mailgun, then reference the correct credential file in the smtp_sasl_password_maps directive.
Monitoring Delivery and Troubleshooting Common Issues
Both Postfix and your relay service provide logging that helps identify delivery problems. Mailgun's dashboard shows delivery status for each message, including bounces, complaints, and open rates where supported by the receiving mail server.
Several common issues arise during relay configuration:
- Authentication failure: The username or password in
sasl_passwddoes not match what Mailgun expects. Double-check the SMTP credentials in your Mailgun dashboard. - Connection timeout: Outbound port 587 is blocked by your hosting provider. Many providers also allow port 2525 as an alternative.
- DNS resolution failure: The relay hostname cannot be resolved. Check that your server's DNS configuration is working correctly.
- TLS handshake failure: The relay server does not support the TLS version your Postfix is configured to use. Try downgrading the security level to
mayfor testing, thoughencryptis recommended for production.
Test SMTP connectivity to the relay server manually to isolate network issues:
nc -zv smtp.mailgun.org 587
If the connection succeeds, the issue is likely with authentication or DNS. If it fails, check firewall rules and confirm that your hosting provider allows outbound connections on that port.
Switching to a Different Relay Provider
One advantage of the Postfix relay configuration is that it is provider-agnostic. The same configuration pattern works for SendGrid, Postmark, Amazon SES, and most other SMTP-based relay services. To switch providers, update the relay host address and the SASL credentials.
For example, to switch from Mailgun to SendGrid:
relayhost = [smtp.sendgrid.net]:587
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
Update the credentials file with the SendGrid SMTP settings:
sudo nano /etc/postfix/sasl_passwd
[smtp.sendgrid.net]:587 apikey:your_sendgrid_api_key
sudo postmap /etc/postfix/sasl_passwd
sudo postfix reload
The only things that change between providers are the relay host address, the username format, and the password. The rest of the Postfix configuration remains the same. This makes it straightforward to migrate or run parallel setups while evaluating different services.
Maintaining Your Email Relay Setup
A relay configuration requires periodic attention to remain reliable. Monitor delivery logs regularly to catch issues before they affect users. Rotate SMTP credentials if there is any reason to believe they have been compromised. Review your DNS authentication records when making changes to your sending infrastructure.
Backup your Postfix configuration files before making changes. Keep copies of main.cf, sasl_passwd, and any custom map files you have created. This makes it straightforward to restore a working configuration if a change causes unexpected problems.
If you manage multiple domains or high email volumes, consider automating credential rotation and configuration deployment through a configuration management tool. However, for smaller setups, manual maintenance with proper backups is usually sufficient.