Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk11 min

How to Set Up a Postfix Mail Relay with Mailgun on Ubuntu

Set up Postfix on Ubuntu as a secure Mailgun smarthost using port 587, per-domain SMTP credentials, protected SASL maps, TLS, relay restrictions, and verifiable delivery tests.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The reliable default is to configure Ubuntu’s Postfix as a smarthost that sends remote mail to [smtp.mailgun.org]:587 over authenticated SMTP with STARTTLS. Use the SMTP credentials created for the specific Mailgun sending domain, store them in a root-readable password map, reject unauthorized relay attempts, then verify delivery in both the Postfix queue and logs.

What this configuration does

Postfix normally can attempt direct delivery by looking up each recipient domain’s MX records. In a Mailgun relay setup, the Ubuntu server remains the local mail-transfer agent, but its remote mail is handed to Mailgun instead. The relayhost setting forces Postfix to submit remote messages to the specified SMTP service rather than contacting recipient MX servers itself.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The resulting path is:

  1. A local application submits a message to Postfix on the Ubuntu host.
  2. Postfix accepts the message only from permitted local clients or networks.
  3. Postfix authenticates to Mailgun with the credentials for the sending domain.
  4. The connection uses the selected Mailgun SMTP port and TLS policy.
  5. Mailgun accepts the message and performs onward delivery.

This design centralizes outbound mail, avoids exposing every application to Internet SMTP details, and lets you inspect one queue and one set of delivery logs. It does not make the Ubuntu host a general-purpose relay: relay restrictions must continue to reject destinations that are not authorized.

Prerequisites and decisions

Ubuntu access and hostname

You need an Ubuntu server with sudo access, a functioning Postfix package repository, and a hostname that resolves correctly. Check the name Postfix will use before installation:

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
hostname -f

Correct forward and reverse DNS are useful for mail reputation and diagnostics, but the minimum prerequisite for this procedure is a resolvable server hostname. Make sure the host can make outbound TCP connections to the Mailgun submission port you select.

A Mailgun sending domain and SMTP credentials

Mailgun SMTP credentials are managed per sending domain. The control-panel login password is not the password that belongs in Postfix. Obtain the SMTP username and SMTP password displayed for the domain that will send the messages. If you use credentials from a different domain, authentication can fail even though the account itself is valid.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Select a submission port

Port 587 is the practical default for this guide. It begins as ordinary SMTP and upgrades with STARTTLS, and it is generally more reachable than port 25 on hosted servers. Mailgun documents ports 25, 465, 587, and 2525:

Port Connection encryption When to choose it Important qualification
587 STARTTLS upgrade Default for Postfix submission Use the [smtp.mailgun.org]:587 password-map key and STARTTLS-capable settings.
25 STARTTLS upgrade Only when your network permits it and policy requires it Frequently blocked or throttled by hosting providers; Mailgun recommends 587 when that occurs.
2525 STARTTLS upgrade Fallback when standard SMTP ports are filtered Confirm that outbound TCP 2525 is allowed by your firewall and provider.
465 Implicit TLS from connection start When your environment specifically requires implicit TLS It is not interchangeable with the STARTTLS configuration shown below; wrapper-mode settings are required.

Install Postfix as a smarthost

Refresh package metadata and install Postfix from Ubuntu’s packages:

sudo apt update
sudo apt install postfix

During the package configuration dialog, select the smarthost-oriented design (normally labelled Internet with smarthost in Ubuntu’s Postfix dialog) rather than a configuration that delivers directly to recipient servers. If the dialog asks for a system mail name, use the server’s intended fully qualified hostname or the domain identity appropriate for your deployment.

If Postfix is already installed, do not blindly overwrite a working configuration. Save the current files first:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
sudo cp -a /etc/postfix/main.cf /etc/postfix/main.cf.backup
sudo cp -a /etc/postfix/master.cf /etc/postfix/master.cf.backup

Ubuntu packages commonly run selected Postfix services in a chroot. Keep the package’s existing service layout unless you have a specific reason to change it; changing chroot paths while troubleshooting SMTP can create misleading file-not-found errors.

Configure Postfix to use Mailgun

Set the relay and SMTP authentication parameters

Edit /etc/postfix/main.cf and add or update the following settings for port 587:

relayhost = [smtp.mailgun.org]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = may
smtp_tls_note_starttls_offer = yes

The square brackets around the hostname prevent Postfix from performing an MX lookup for the relay host. The port is part of the relay identity, so the same bracketed host-and-port string must appear in the password map. smtp_sasl_auth_enable turns on SMTP AUTH for the outbound connection, while noanonymous prevents Postfix from selecting an anonymous SASL mechanism.

Prevent an open relay

Relay authentication to Mailgun is separate from deciding which clients may submit mail to your Ubuntu host. Keep the inbound relay policy restricted. On a current Ubuntu Postfix installation, the following is the relevant pattern:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
smtpd_relay_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination

Some existing Ubuntu configurations place the same restrictions in smtpd_recipient_restrictions. Preserve the restriction framework already used by your installation, but ensure that reject_unauth_destination is present after the permitted-client rules. That final check rejects messages for destinations your server is not authorized to relay to.

Do not add broad public networks to mynetworks. Limit it to loopback and the private application networks that genuinely need to submit mail. If an application can submit locally, it can normally use the local Postfix submission path without exposing SMTP AUTH to the Internet.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Ensure certificate trust is available

STARTTLS is useful only if Postfix can validate the Mailgun certificate. Ensure Ubuntu’s CA-certificates package and system trust store are installed and readable by the Postfix SMTP client. If your deployment overrides the default trust store, set the Postfix SMTP CA-file or CA-directory option to the Ubuntu system bundle used by your host. A wrong CA path, an invalid certificate chain, an incorrect hostname, or a badly skewed system clock can all appear as TLS failures.

Store the Mailgun credentials safely

Create /etc/postfix/sasl_passwd with one entry whose key exactly matches the relay host and port:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
[smtp.mailgun.org]:587 SMTP_USERNAME:SMTP_PASSWORD

Replace SMTP_USERNAME and SMTP_PASSWORD with the SMTP credential for the sending domain. Do not use the Mailgun control-panel password. Avoid putting the real password in a command that will be retained in shell history.

Convert the text map into the database Postfix reads and lock down both files:

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

The plaintext file contains a live secret, so it should be readable only by root. Protect backups, configuration-management artifacts, snapshots, and support bundles in the same way. Remove accidental copies and avoid pasting the password into tickets or public shell transcripts. If you rotate the Mailgun credential, update the map, run postmap again, and reload or restart Postfix.

Choose the TLS policy deliberately

The example uses smtp_tls_security_level = may. With an optional policy, Postfix attempts TLS when the server offers STARTTLS but can fall back if TLS negotiation is unavailable. That is compatible with a wide range of SMTP endpoints, but it means authentication and message transfer are not guaranteed to be encrypted in every failure mode.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

After you have confirmed the endpoint, certificate validation, firewall rules, and clock are correct, consider requiring encryption:

smtp_tls_security_level = encrypt

With encrypt, Postfix will not deliver when it cannot establish TLS. Mailgun’s TLS policy documentation describes this distinction: optional TLS may permit a plaintext fallback, whereas required TLS makes the delivery fail rather than continue unencrypted. Choose the stricter policy when your operational testing proves that it works reliably, and monitor the queue for deferred messages after changing it.

Using port 465 instead

Port 465 starts TLS immediately; it does not wait for a STARTTLS command. If your network or application requires that mode, use a relay key that includes port 465 and configure Postfix’s SMTP wrapper mode and an encrypted TLS level, for example:

relayhost = [smtp.mailgun.org]:465
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_wrappermode = yes
smtp_tls_security_level = encrypt

The password map must then contain:

[smtp.mailgun.org]:465 SMTP_USERNAME:SMTP_PASSWORD

Do not combine the 465 wrapper-mode settings with a 587 password-map key. A port/key mismatch commonly produces authentication or connection errors even when the credentials are correct.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Validate and restart Postfix

Run a configuration check before restarting the service:

sudo postfix check
sudo systemctl restart postfix
sudo systemctl --no-pager --full status postfix

postfix check catches many syntax and permission problems, but it does not prove that Mailgun authentication or outbound connectivity works. Inspect the effective non-default settings when diagnosing an unexpected value:

sudo postconf -n

Confirm that the output contains the intended relay host, SASL map, TLS policy, and relay restrictions. Do not paste the contents of sasl_passwd into a public diagnostic report.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Send a real test message

Test through the local Postfix submission path

A local application can submit a message through the server’s normal sendmail-compatible interface:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
printf 'From: [email protected]
To: [email protected]
Subject: Postfix Mailgun relay test

This message tests local submission through Postfix.
' | /usr/sbin/sendmail -v [email protected]

Use a recipient mailbox that you control rather than sending repeated tests to unrelated addresses. The verbose output shows whether the message was accepted locally; it does not by itself prove that Mailgun accepted it, so continue with queue and log checks.

Test Mailgun credentials directly with Swaks

Swaks is useful for separating a Mailgun credential or network problem from a local Postfix configuration problem. Mailgun documents an authenticated SMTP pattern that specifies the server, username, password, recipient, subject, and body. A representative port-587 test is:

read -r SMTP_USER
read -sr SMTP_PASS; printf 'n'
swaks --server smtp.mailgun.org --port 587 --tls --auth LOGIN --auth-user "$SMTP_USER" --auth-password "$SMTP_PASS" --from "$SMTP_USER" --to [email protected] --header 'Subject: Direct Mailgun SMTP test' --body 'Testing authenticated STARTTLS submission.'

Run the command from the Ubuntu host whose firewall and DNS you are diagnosing. Treat the password as temporary shell data, clear variables when finished, and avoid recording it in shell history. A successful Swaks transaction confirms that the host can reach Mailgun, negotiate TLS, authenticate, and submit a message; it does not test Postfix’s queue policy.

Verify delivery in the queue and logs

Immediately inspect the queue:

mailq

An empty queue after a successful test is a good sign, but the authoritative evidence is a log entry showing SMTP authentication and an accepted remote delivery. Review recent service and mail logs:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo journalctl -u postfix -n 100 --no-pager
sudo tail -n 100 /var/log/mail.log

Look for a successful SASL authentication followed by a remote SMTP acceptance. The exact queue ID lets you follow one message from local submission to final handoff. A message that remains queued with repeated deferrals has not completed relay delivery, even if the local sendmail command exited without an error.

Troubleshoot by symptom

Authentication failed

  • Verify that the username and password belong to the Mailgun sending domain, not the account control panel.
  • Check that relayhost and the password-map key match character for character, including brackets and port number.
  • Rebuild the map after every edit with sudo postmap /etc/postfix/sasl_passwd.
  • Confirm that Postfix is reading the intended map with sudo postconf smtp_sasl_password_maps.
  • Inspect logs for the queue ID, but never disclose the password while collecting diagnostics.

TLS or certificate errors

  • Confirm that the server clock is accurate; certificate validity checks depend on correct time.
  • Make sure Ubuntu’s CA trust store is installed and that any explicitly configured CA path points to the real system bundle.
  • Check that the relay hostname is exactly smtp.mailgun.org and that the selected port matches the TLS mode.
  • If you changed the policy to encrypt, temporarily compare behavior under the tested configuration rather than leaving production mail in an unintended plaintext-fallback state.

Connection timeout or refused connection

  • Verify outbound TCP access to port 587, or to the alternate port selected for your deployment.
  • Review cloud-provider egress rules, host firewalls, and network appliances that block SMTP.
  • If port 25 is blocked or throttled, use 587 as Mailgun recommends, or test 2525 when your network permits it.
  • Check DNS resolution for smtp.mailgun.org and inspect the exact Postfix error in the mail log.

Messages stay deferred in the queue

Read the SMTP response attached to the queue entry. Repeated deferrals can result from DNS problems, outbound firewall rules, Mailgun limits, TLS negotiation failures, or a transient provider response. Fix the stated cause first; do not repeatedly flush the queue without understanding why delivery is being deferred. After correction, Postfix will retry according to its normal queue schedule, or you can use the standard queue-management command appropriate to your operational policy.

The server appears to relay for unauthorized destinations

Review the effective restrictions with:

sudo postconf smtpd_relay_restrictions
sudo postconf mynetworks

Ensure that reject_unauth_destination is present and that mynetworks contains only trusted local addresses or private application networks. Remove any broad public range that was added for convenience, reload Postfix, and test submission from an authorized application path only.

Operational hardening after the first successful delivery

  • Keep the credential map private. Maintain root ownership and mode 600 on the plaintext password file, and protect its generated database and every backup.
  • Use the least-permissive client policy. Permit local authenticated clients and explicitly trusted networks; reject unauthenticated destinations.
  • Prefer encrypted submission. Keep STARTTLS enabled and move to smtp_tls_security_level = encrypt once certificate validation and connectivity are proven in your environment.
  • Monitor the queue. A growing queue is an early warning of authentication, TLS, DNS, firewall, or provider-limit problems.
  • Rotate credentials safely. Replace the map, rebuild it with postmap, restart or reload Postfix, and verify one controlled test message.
  • Limit diagnostic disclosure. Logs can contain recipient addresses, server names, and message identifiers. Share only the lines needed to resolve an incident, and never share the password map.

Final configuration checklist

  • Postfix is installed from Ubuntu packages and starts without errors.
  • The host has a resolvable hostname and outbound access to the selected Mailgun port.
  • relayhost uses the bracketed Mailgun hostname and the intended port.
  • SASL authentication is enabled, anonymous mechanisms are disabled, and the map is generated with postmap.
  • The map key exactly matches the relay host and port, and the credential is for the sending domain rather than the control panel.
  • Ubuntu’s CA trust store is available to Postfix, and the TLS mode matches the selected port.
  • Relay restrictions include reject_unauth_destination and the trusted-client list is narrow.
  • postfix check succeeds, the service restarts cleanly, and a real test message is accepted by Mailgun.
  • The queue is clear or progressing normally, and logs show authenticated, accepted remote delivery.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.