Secure Email Relay with Mailgun and Postfix

14 min read 2,686 words
Setting Up a Secure Email Relay with Postfix and Mailgun featured image

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. If you are new to Postfix setup on Ubuntu, our guide to configuring Postfix for reliable email delivery covers the basics before you move to relay configuration.

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.

Note: Port 587 is the standard submission port for authenticated SMTP. Some hosting providers also allow port 2525 as an alternative if 587 is blocked by their firewall rules. Check with your provider if you encounter connection issues.

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 postmaster@yourdomain.com: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" recipient@example.com

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.

Before testing: Back up your current Postfix configuration files if you are modifying an existing mail setup. Changes to relay settings can affect how existing mail flow is handled, particularly if your server already sends email directly.

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:dmarc-reports@yourdomain.com; 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, our guide to 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.

Tip: If you are automating transactional emails such as order confirmations or password resets, ensure that each email type has a clear sender address. This helps with deliverability metrics and makes it easier to track performance separately for different categories of outgoing mail.

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_passwd does 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 may for testing, though encrypt is 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.

What to Do if Delivery Problems Persist

If you have followed the configuration steps and your emails still land in spam folders, the issue often lies in your DNS authentication setup, your sending domain's reputation, or content-related factors that email providers use to assess message quality.

Start by verifying that your SPF, DKIM, and DMARC records are correctly published and that they pass validation when tested. Tools such as MXToolbox and DMARC Analyzer can help you check your records without needing direct server access. Look for discrepancies between what your DNS shows and what your relay service dashboard reports.

Check whether your sending domain has been flagged on any blocklists. Services such as Spamhaus and SORBS maintain lists that many email providers reference. If your domain appears on a blocklist, follow the delisting process for that specific service before continuing to send.

Consider the content of your emails as well. High volumes of links, certain keywords, and poor HTML structure can contribute to lower spam scores. Test with simple plain-text emails first to isolate whether the issue is technical or content-related.

If you have reviewed your configuration, checked DNS records, and addressed content factors but delivery problems remain, reaching out to your relay provider's support team can help. They have visibility into how recipient servers are handling your messages and can often identify issues that are not visible from your server logs alone.

If you need help reviewing your current Postfix configuration or setting up a relay service for the first time, you can get in touch with details of your setup, the email volume you handle, and any delivery issues you are currently experiencing.

Frequently Asked Questions

Do I need a relay service if my server already has a static IP address?
A static IP address helps with reputation building over time, but it does not guarantee good deliverability. Most email providers still check SPF, DKIM, and DMARC records regardless of whether you use a relay. A relay service accelerates reputation building and handles the operational overhead of maintaining sender scores across multiple IP ranges.
Can I use TLS with the relay connection?
Yes. The smtp_tls_security_level = encrypt setting enforces TLS for the connection to the relay server. Most reputable relay providers require TLS. If you encounter compatibility issues, try smtp_tls_security_level = may as a fallback, though this should be temporary since it allows plain-text connections.
What happens if my relay service goes offline?
Postfix queues undelivered mail locally until the relay becomes available again. The queue lifetime is controlled by the maximal_queue_lifetime parameter in main.cf, which defaults to five days. As long as your server stays online, mail is not lost during relay outages.
Is it safe to store SMTP credentials in a plain-text file?
The sasl_passwd file contains sensitive authentication details, so it should have restrictive permissions (mode 600) and be owned by root. The hashed version sasl_passwd.db is what Postfix reads, and it cannot be reversed to recover the plain-text password. For additional security, consider using secrets management tools if your setup supports them.
How do I know if my emails are reaching the inbox?
Check your relay service dashboard for delivery statistics. Most providers show delivery rates, bounce rates, and complaint rates. You can also send test emails to accounts on Gmail, Outlook, and other major providers and inspect the headers to see which folder they landed in. If emails consistently go to spam, review your SPF, DKIM, and DMARC configuration and check whether your sending domain has been flagged on any blocklists.
How often should I check my email logs?
For production systems handling transactional or customer-facing email, reviewing delivery logs weekly helps catch patterns early. If you are sending lower volumes, monthly reviews are usually sufficient unless you notice specific delivery issues. Paying attention to bounce rates and complaint indicators gives you a clearer picture of overall email health than reviewing every log entry individually.
Can I send both transactional and marketing emails through the same relay setup?
You can, but separating them often leads to better deliverability outcomes. Transactional emails such as order confirmations and password resets tend to have high open rates and low complaint rates. Marketing emails typically see lower engagement and occasionally trigger spam complaints. Mixing both through the same sending infrastructure can affect your sender reputation for all email types.