Configure Postfix SMTP Relay: Step-by-Step Guide for Sending Webserver Email

This guide explains how to set up Postfix to relay email through a third-party SMTP service like SendGrid. Whether you’re using SendGrid, Mailgun, Brevo, or another provider, the configuration process is nearly identical.

Once set up, your server can send email securely and reliably. Common use cases include:

  • Contact form submissions from your website
  • System alerts or cron job outputs
  • Application-generated notifications

What is SMTP Relay?

SMTP relay is the process of passing email from your mail server (Postfix) to an external SMTP service (SendGrid), which then delivers it to the recipient. This method improves deliverability, ensures proper authentication, and avoids issues with ISPs blocking direct outbound email.

In this setup:

  • Your webserver sends email to Postfix (locally)
  • Postfix connects securely to smtp.sendgrid.net
  • Postfix authenticates using your SendGrid API key
  • SendGrid accepts the message and delivers it to the recipient’s mail server

Using SendGrid as an SMTP relay gives you a trusted, authenticated, and secure outbound mail path, reducing the chances of your emails being blocked or flagged as spam.

Benefits of Using an SMTP Relay

SMTP relay services offer several advantages for sending email from your server:

  • Improved Deliverability
    SMTP relays have trusted infrastructure and established relationships with email providers, reducing the chance your emails end up in spam or get blocked.
  • Simplified Configuration
    Instead of managing your own mail server’s reputation, security, and compliance, the relay handles these complex tasks for you.
  • Scalability
    SMTP relays can handle large volumes of email without extra effort on your part, making them ideal for growing websites or applications.
  • Security and Authentication
    Most SMTP relay providers support modern authentication methods (like TLS, SPF, DKIM, and DMARC), protecting your emails from interception or spoofing.
  • Reliability and Monitoring
    SMTP relays often provide uptime guarantees, detailed delivery reports, and alerts, so you can track email status and troubleshoot issues easily.
  • Reduced Server Load
    Offloading email sending to a relay reduces resource consumption on your own server, keeping it focused on your core applications.

By using an SMTP relay, you ensure your emails reach inboxes efficiently and securely, while simplifying management and improving scalability.

Prerequisites #

  • A Linode running the latest Ubuntu LTS version.
  • Domain name with access to DNS management.
  • Basic familiarity with the command line.

Step 1: Create a SendGrid Account #

  1. Visit https://sendgrid.com/ and sign up.
  2. Navigate to Settings > API Keys.
    • Click Create API Key.
    • Name: Webserver SMTP
    • API Key Permissions: Restricted Access
      • Enable Mail Send: Full Access
    • Save the API key securely.
  3. Go to Settings > Sender Authentication
    • Complete all verification steps.
    • Use Single Sender Verification):

Step 2: Update SPF Record #

Purpose

SPF (Sender Policy Framework) helps prevent spoofing by authorising SendGrid to send emails on behalf of your domain.

Instructions

  1. Access your domain's DNS settings via your DNS provider (e.g. Cloudflare).
  2. Locate or create a TXT record for the root domain (@) or the specific subdomain used for sending emails.

Recommended SPF Record:

txt
"v=spf1 include:sendgrid.net -all"

Notes:

  • Allow DNS changes to propagate (can take up to 48 hours).
  • If an SPF record already exists, do not add a second one. Instead, update the existing record to include SendGrid. Example:
txt
"v=spf1 include:<other_service> include:sendgrid.net -all"

Step 3: Update Firewall Rules #

Linode Cloud Firewall #

Verify SMTP Port Restrictions: Linode blocks outbound SMTP ports (including 587) by default on new accounts. If blocked, submit a support request to remove the restriction.

Recommended firewall rules:

Label Protocol Port(s) Destination
accept-outbound-SMTP TCP 587 All IPv4, All IPv6
accept-outbound-DNS-TCP TCP 53 All IPv4, All IPv6
accept-outbound-DNS-UDP UDP 53 All IPv4, All IPv6

UFW (Uncomplicated Firewall) #

Check current status:

bash
sudo ufw status

Allow outbound SMTP on port 587:

bash
sudo ufw allow out 587/tcp

Allow DNS resolution (both TCP and UDP on port 53):

bash
sudo ufw allow out 53/tcp
sudo ufw allow out 53/udp

Reload UFW to apply changes:

bash
sudo ufw reload

Verify detailed firewall status:

bash
sudo ufw status verbose

Step 4: Set Up Postfix #

Install Postfix and Mailutils:

bash
sudo apt install postfix mailutils
  • Select Internet Site for mail configuration.
  • Set System mail name to your domain (e.g., example.com).

Backup configuration file:

bash
sudo cp /etc/postfix/main.cf /etc/postfix/main.cf.bak

Edit configuration:

bash
sudo vim /etc/postfix/main.cf

Modify:

/etc/postfix/main.cf
# Basic identity
myhostname = mail.<example.com>
myorigin = <example.com>
mydomain = <example.com>
mydestination = localhost

# Network interfaces and protocols
inet_interfaces = loopback-only
inet_protocols = all

# Trusted networks - localhost only
mynetworks = 127.0.0.0/8 [::1]/128

# Relay via SendGrid SMTP
relayhost = [smtp.sendgrid.net]:587

# SASL authentication for relayhost
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sasl_tls_security_options = noanonymous

# TLS configuration for outbound SMTP
smtp_tls_security_level = verify
smtp_tls_CApath = /etc/ssl/certs
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtp_tls_note_starttls_offer = yes

# Banner and headers
smtpd_banner = $myhostname ESMTP (restricted)
biff = no
append_dot_mydomain = no

# Disable local delivery (optional, if not needed)
home_mailbox =
mailbox_command =

# Performance tuning
default_process_limit = 10

# Rate limiting to reduce abuse
smtpd_client_message_rate_limit = 10

Create SMTP authentication file:

bash
sudo vim /etc/postfix/sasl_passwd

Add:

/etc/postfix/sasl_passwd
[smtp.sendgrid.net]:587 apikey:<sendgrid_api>

Set permissions:

bash
sudo chmod 600 /etc/postfix/sasl_passwd*
sudo chown root:root /etc/postfix/sasl_passwd*

Hash the password file:

This creates /etc/postfix/sasl_passwd.db which Postfix uses securely.

bash
sudo postmap /etc/postfix/sasl_passwd

Restart Postfix service to apply changes:

bash
sudo systemctl restart postfix

Step 5: Verify Email Sending #

Send a test email (should arrive within seconds):

From address must be verified by SMTP provider (SendGrid) to prevent rejection.

bash
echo "Test Email Body" | mail -s "Test Email Subject" -r "[email protected]" [email protected]
  • echo "Test Email Body"
    Defines the body content of the email.
  • |
    Pipes the output of echo to the next command (mail).
  • mail -s "Test Email Subject"
    Sends the email with the specified subject line.
  • -r "[email protected]"
    Sets the From address. Must be a verified sender to avoid SMTP rejection.
  • [email protected]
    The recipient’s email address.

By the end, your server will be able to send email securely and reliably. Common use cases include: