How to Route Mail through a WireGuard Tunnel for Self-Hosted Domains

Abstract: Resolve Postfix mail delivery loops by routing outbound SMTP through a WireGuard tunnel to a remote pfSense gateway instead of localhost.

Created: 2026-10-03 by

Route self-hosted email through a WireGuard tunnel by configuring Postfix to relay outbound SMTP traffic via the remote endpoint’s IP address assigned within the tunnel network. This setup ensures that your mail server sends messages through an encrypted, private path managed by pfSense, rather than attempting to loop back to localhost or failing to reach the external relay. Proper routing tables and static routes are essential for this architecture to function correctly.

Network Architecture Overview

Before diving into configuration files, it is crucial to understand the data flow. In this scenario, you have a local Ubuntu server running Postfix that needs to send email. Instead of sending directly to the public internet (which exposes your server's IP), you route traffic through a WireGuard interface. The WireGuard peer is likely a gateway device, such as a pfSense router or another VPS, which then forwards the email to the final destination (e.g., Gmail, Outlook, or your domain's MX record). The key challenge addressed here is avoiding the common mistake of configuring Postfix to relay to 127.0.0.1 or the local machine itself. Doing so creates a loop where Postfix attempts to deliver mail to itself, resulting in delivery failures. Instead, Postfix must be configured to use the specific IP address assigned to the WireGuard peer on the remote end. This requires coordination between your Ubuntu client, the WireGuard configuration, and the routing logic on your pfSense gateway.

Configuring WireGuard on Ubuntu

First, ensure WireGuard is installed on your Ubuntu server. You can install it using the standard package manager:
sudo apt update
sudo apt install wireguard resolvconf
Create a configuration file for your tunnel, typically located at /etc/wireguard/wg0.conf. This file defines the local private key and the remote public key. Crucially, you must define the AllowedIPs field carefully. To route all traffic through the tunnel, you might set this to 0.0.0.0/0, but for mail-specific routing, it is often safer to specify only the subnet of the remote gateway or the specific IP of the relay server. Here is a minimal example structure:
[Interface]
PrivateKey = YOUR_LOCAL_PRIVATE_KEY
Address = 10.8.0.2/32

[Peer]
PublicKey = REMOTE_PUBLIC_KEY
Endpoint = pfense_or_remote_vps_ip:51820
AllowedIPs = 10.8.0.1/32
PersistentKeepalive = 25
In this example, 10.8.0.2 is the IP assigned to your Ubuntu machine inside the tunnel, and 10.8.0.1 is the IP of the pfSense gateway or remote peer. Ensure that the AllowedIPs includes the IP address of the host you intend to relay mail to. If you are relaying to a specific smart host over the tunnel, that IP must be reachable via this route. Start and enable the service:
sudo wg-quick up wg0
sudo systemctl enable wg-quick@wg0
Verify the connection is established by checking the status:
wg show
You should see active handshakes and bytes sent/received. If the connection fails, check firewall rules on both ends. For more details on troubleshooting interface issues, refer to our guide on IPSect Tunnel Established, but nmap and ping Unable: Troubleshooting Ubuntu VM Network Traffic.

Setting Up Routing on pfSense

Since the tags include pfsense, we assume your WireGuard endpoint is a pfSense router. pfSense acts as the gateway for the tunnel. You need to ensure that traffic coming from the WireGuard subnet (10.8.0.0/24) is routed correctly to the internet or to your specific mail relay. 1. Navigate to VPN > WireGuard in the pfSense web interface. 2. Ensure the peer corresponding to your Ubuntu server has the correct "Allowed IPs" defined. This tells pfSense how to route responses back to the Ubuntu client. 3. Go to System > Route Domains if you are using policy-based routing, though usually, standard routing suffices if the WireGuard interface is added to the default gateway group or if you have a dedicated WAN interface. 4. Verify that there are no firewall rules blocking UDP port 51820 inbound on the pfSense WAN interface. If you are using pfSense to terminate the tunnel and forward mail, you may need to configure a proxy or relay service on pfSense itself, or simply allow the traffic to pass through to another upstream server. The critical step is ensuring that when Ubuntu sends packets to 10.8.0.1, pfSense knows to encapsulate them in WireGuard packets and send them out its WAN interface. For advanced tunnel configurations involving multiple interfaces or VPS setups, see Combining DNA, TSN, and Forward Port in Wireguard Tunnel for VPS.

Configuring Postfix for Relay

Now, configure Postfix to send mail through the WireGuard tunnel. Open the main configuration file:
sudo nano /etc/postfix/main.cf
Add or modify the following lines. Replace 10.8.0.1 with the actual IP address of your WireGuard peer that will handle the SMTP relay.
# Define the relayhost
relayhost = [10.8.0.1]:587

# Use SASL authentication if required
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sasl_mechanism_filter = plain

# Disable DNS lookups for the relay host to prevent leakage
smtp_use_tls = yes
smtp_tls_security_level = encrypt
Note the square brackets around the IP address [10.8.0.1]. This tells Postfix not to perform an MX lookup for the hostname, treating it as a literal IP address. This is vital because you are connecting to a specific internal IP via the tunnel, not a public domain name. Next, create the password map if you need to authenticate with the relay server:
echo "[10.8.0.1]:587 username:password" | sudo tee /etc/postfix/sasl_passwd
sudo postmap /etc/postfix/sasl_passwd
sudo chmod 600 /etc/postfix/sasl_passwd*
Restart Postfix to apply changes:
sudo systemctl restart postfix
To test the configuration, send a test email:
echo "Test body" | mail -s "Test Subject" [email protected]
Check the mail log for any errors:
sudo tail -f /var/log/mail.log
If you encounter authentication issues, ensure your SASL credentials are correct. For stricter security measures regarding SASL accounts, consider reading Restricting SASL Accounts by IP Addresses in Postfix on Ubuntu 22.04.

Verifying the Route

To confirm that mail is indeed flowing through the WireGuard tunnel, you can monitor the traffic. On the Ubuntu server, you can use tcpdump to capture packets on the WireGuard interface:
sudo tcpdump -i wg0 port 587
You should see SMTP traffic being encapsulated and sent out. Simultaneously, on the pfSense side, you can verify that the WireGuard peer is receiving these packets. If the traffic does not appear on the WireGuard interface, check your routing table on Ubuntu with ip route to ensure that traffic destined for the relay IP is directed to the wg0 interface. By following these steps, you avoid the localhost loop error and establish a secure, encrypted channel for your self-hosted email communications. This method leverages the strength of WireGuard for encryption and pfSense for robust network management, providing a reliable infrastructure for your mail server.

Frequently Asked Questions

Why is my Postfix trying to connect to localhost instead of the WireGuard IP?

This usually happens if the relayhost parameter is left empty or incorrectly formatted. Ensure you explicitly set relayhost = [YOUR_WIREGUARD_PEER_IP]:PORT in main.cf. The square brackets are mandatory to prevent DNS resolution attempts on the local machine.

Can I route all internet traffic through the WireGuard tunnel for mail?

Yes, by setting AllowedIPs = 0.0.0.0/0 in the WireGuard peer configuration, all traffic from your Ubuntu server will go through the tunnel. However, this increases latency for non-mail traffic. It is often better to use policy-based routing to only send mail-related traffic through the tunnel.

What if the WireGuard connection drops while sending mail?

Postfix will queue the message in the mail queue if the connection fails. You can manually flush the queue with sudo postsuper -r ALL once the tunnel is restored. Setting PersistentKeepalive in the WireGuard config helps maintain the connection state.

Do I need to open ports on my pfSense firewall for this to work?

You need to allow inbound UDP traffic on port 51820 for the WireGuard handshake to succeed. Once the tunnel is established, standard SMTP ports (like 587) are handled within the encrypted tunnel, so no additional open ports are needed for the mail traffic itself.

How do I debug why Postfix cannot reach the WireGuard peer?

Use telnet 10.8.0.1 587 from the Ubuntu server to test basic connectivity. If it fails, check the WireGuard status with wg show and verify that the peer's IP is correctly assigned. Also, ensure that the pfSense firewall allows traffic from the WireGuard subnet to exit towards the internet.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More