How to Run a Mail Server on a Dedicated Server (and Keep IP Reputation Clean)

Running your own mail server on a dedicated server gives you full control over your email: your own dedicated IP address, your own sending limits, your own data and no per-mailbox fees. It also makes you responsible for deliverability. If your messages land in spam, the cause is almost always a missing DNS record, a mismatched reverse DNS entry or a damaged IP reputation, not the mail software itself.

This tutorial shows you how to set up a secure mail server on Ubuntu 24.04 with Postfix (sending and receiving), Dovecot (mailbox access) and OpenDKIM (message signing), then how to configure SPF, DKIM, DMARC and reverse DNS, and how to keep your IP reputation clean over time.

What you will build: A mail server that sends and receives email for your own domain, encrypted connections (TLS) for SMTP and IMAP, SPF, DKIM and DMARC authentication, a dedicated IP with matching reverse DNS (PTR), and a routine for warming up, monitoring and protecting your sending reputation.

Time needed: about 60 to 90 minutes, plus DNS propagation. Difficulty: intermediate. You should be comfortable with SSH and editing config files on Linux.

1. Should You Self-Host Email on a Dedicated Server?

Self-hosting email is worthwhile in some situations and a poor idea in others.

It makes sense when you:

  • Want full ownership of your email data and metadata

  • Send transactional email (receipts, alerts, password resets) from your own applications

  • Need many mailboxes without per-user pricing

  • Have compliance or data-location requirements

  • Want a dedicated IP whose reputation depends only on you

It may not be the right choice when you:

  • Send large volumes of bulk marketing email with no deliverability experience (a specialist email delivery service is usually easier)

  • Cannot spend time on monitoring and updates

  • Need a guaranteed inbox-placement SLA

A dedicated server helps because you get a dedicated IPv4 address, control over reverse DNS, full control over open ports, and no other tenant sharing your IP and its reputation. A VPS can work too, but shared or recycled IP ranges more often come with blocklist history.

2. Prerequisites

Check these before you start. Most failed mail server setups fail on one of them.

Requirement Why it matters
A dedicated server running Ubuntu 24.04 LTS The commands in this guide target Ubuntu 24.04 (Postfix 3.8, Dovecot 2.3). Paths can differ on other distributions.
A clean dedicated IPv4 address Your IP's history affects deliverability from day one.
Outbound port 25 open Many hosts restrict port 25 by default. Confirm your provider allows it before you begin.
Ability to set reverse DNS (PTR) Receiving servers check that your IP resolves to your mail hostname.
A domain with access to its DNS records You will add MX, SPF, DKIM and DMARC records.
Root or sudo access Required for installation and configuration.

A small server is enough for a typical mailbox workload. Memory needs grow with spam filtering and mailbox count. See our guide to how much RAM a dedicated server needs if you plan to add filtering or webmail later.

Test outbound port 25 first:

nc -vz gmail-smtp-in.l.google.com 25

If this connects, outbound SMTP is open. If it times out, ask your provider to allow port 25 before you continue.

Acceptable use: Follow your provider's acceptable use policy and applicable anti-spam laws. Send only to recipients who expect your mail, and include a working unsubscribe method for marketing email.

Step 1: Set the Hostname and Prepare the Server

Choose a fully qualified domain name (FQDN) for your mail server, such as mail.example.com. Use your own domain throughout this guide.

sudo hostnamectl set-hostname mail.example.com
sudo apt update && sudo apt upgrade -y

Confirm the hostname resolves locally by adding it to /etc/hosts:

203.0.113.10   mail.example.com   mail

Replace 203.0.113.10 with your server's public IPv4 address.

Open the firewall ports you need. If you use UFW:

sudo ufw allow 22/tcp     # SSH
sudo ufw allow 25/tcp     # SMTP (server-to-server)
sudo ufw allow 587/tcp    # Submission (mail clients)
sudo ufw allow 993/tcp    # IMAPS (mail clients)
sudo ufw allow 80/tcp     # Certificate issuance
sudo ufw enable

Securing the server itself is just as important as configuring mail. Follow our dedicated server hardening checklist before you put the server on the public internet.

Step 2: Create the DNS Records

Mail depends on DNS more than any other service. Create these records at your DNS provider. If you are new to DNS, our DNS zone guide for beginners explains how zones and records work.

Type Name Value Purpose
A mail.example.com 203.0.113.10 Points your mail hostname to the server
MX example.com 10 mail.example.com. Tells other servers where to deliver your mail
TXT (SPF) example.com v=spf1 mx ~all Declares which servers may send for your domain
TXT (DMARC) _dmarc.example.com v=DMARC1; p=none; rua=mailto:[email protected] Sets your policy and reporting
PTR 10.113.0.203.in-addr.arpa mail.example.com. Reverse DNS, set by your hosting provider

The DKIM record is added in Step 6, after you generate the key.

About the reverse DNS (PTR) record: You cannot set it in your domain's DNS. It belongs to the IP address owner, so set it in your provider's control panel or ask support. The PTR hostname should match your server's hostname (mail.example.com), and that hostname's A record should point back to the same IP. This forward-confirmed reverse DNS match is one of the first things receiving servers check.

About SPF: Start with ~all (soft fail) while you test, then change to -all (hard fail) once you confirm that legitimate mail passes.

IPv6 note: If you do not have complete IPv6 setup (AAAA, PTR and SPF coverage), send over IPv4 only. Our guide to IPv4 vs IPv6 on dedicated servers explains the trade-offs.

Verify records after they propagate:

dig +short MX example.com
dig +short TXT example.com
dig +short -x 203.0.113.10

Step 3: Get a TLS Certificate

Mail clients and other servers expect encrypted connections. Use a free Let's Encrypt certificate.

sudo apt install certbot -y
sudo certbot certonly --standalone -d mail.example.com

Port 80 must be free during issuance. Certificates renew automatically, but Postfix and Dovecot need to reload after each renewal. Create a deploy hook:

sudo tee /etc/letsencrypt/renewal-hooks/deploy/reload-mail.sh > /dev/null <<'EOF'
#!/bin/bash
systemctl reload postfix dovecot
EOF

sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-mail.sh

Step 4: Install and Configure Postfix

Postfix is the mail transfer agent (MTA). It accepts mail from other servers, sends your outgoing mail and hands authenticated submissions from your mail clients to the queue.

sudo apt install postfix -y

When prompted, choose Internet Site and enter example.com as the system mail name.

Apply the core settings:

sudo postconf -e "myhostname = mail.example.com"
sudo postconf -e "mydomain = example.com"
sudo postconf -e "myorigin = \$mydomain"
sudo postconf -e "mydestination = \$myhostname, localhost.\$mydomain, localhost, \$mydomain"
sudo postconf -e "inet_interfaces = all"
sudo postconf -e "inet_protocols = ipv4"
sudo postconf -e "home_mailbox = Maildir/"

Add TLS settings:

sudo postconf -e "smtpd_tls_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pem"
sudo postconf -e "smtpd_tls_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pem"
sudo postconf -e "smtpd_tls_security_level = may"
sudo postconf -e "smtp_tls_security_level = may"
sudo postconf -e "smtpd_tls_protocols = >=TLSv1.2"
sudo postconf -e "smtp_tls_protocols = >=TLSv1.2"

may means opportunistic encryption: Postfix uses TLS when the other server supports it, which is the right default for server-to-server mail.

Prevent open relay. An open relay lets anyone send spam through your server and is the fastest way to get blocklisted:

sudo postconf -e "smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, defer_unauth_destination"
sudo postconf -e "smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, reject_non_fqdn_recipient, reject_unknown_recipient_domain"

Connect Postfix to Dovecot for authentication:

sudo postconf -e "smtpd_sasl_type = dovecot"
sudo postconf -e "smtpd_sasl_path = private/auth"

Enable the submission service (port 587) for authenticated mail clients. Edit /etc/postfix/master.cf, find the submission lines (commented out by default) and make them look like this:

submission inet n       -       y       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_tls_auth_only=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject

This forces TLS and requires a login on port 587, so only your users can send through it.

Step 5: Install and Configure Dovecot (IMAP)

Dovecot stores mailboxes and lets mail clients read mail over IMAP.

sudo apt install dovecot-imapd -y

Mailbox location. In /etc/dovecot/conf.d/10-mail.conf:

mail_location = maildir:~/Maildir

Authentication. In /etc/dovecot/conf.d/10-auth.conf:

disable_plaintext_auth = yes
auth_mechanisms = plain login

TLS. In /etc/dovecot/conf.d/10-ssl.conf:

ssl = required
ssl_cert = </etc/letsencrypt/live/mail.example.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/mail.example.com/privkey.pem
ssl_min_protocol = TLSv1.2

Let Postfix use Dovecot for logins. In /etc/dovecot/conf.d/10-master.conf, find the service auth block and add the Postfix socket:

service auth {
  unix_listener /var/spool/postfix/private/auth {
    mode = 0660
    user = postfix
    group = postfix
  }
}

Restart both services and create a first mailbox user:

sudo systemctl restart postfix dovecot
sudo adduser --shell /usr/sbin/nologin alice

This guide uses system accounts, which is the simplest way to start. For many domains or hundreds of mailboxes, plan a virtual mailbox setup (a database or file-based user map) instead.

Step 6: Set Up DKIM Signing

DKIM adds a cryptographic signature to every outgoing message so receivers can verify it really came from your domain and was not altered.

sudo apt install opendkim opendkim-tools -y
sudo mkdir -p /etc/opendkim/keys/example.com
sudo opendkim-genkey -b 2048 -d example.com -s mail -D /etc/opendkim/keys/example.com
sudo chown -R opendkim:opendkim /etc/opendkim
sudo chmod 600 /etc/opendkim/keys/example.com/mail.private

Edit /etc/opendkim.conf. Comment out any existing Socket line, then set:

Syslog                  yes
UMask                   007
Mode                    sv
Canonicalization        relaxed/simple
SigningTable            refile:/etc/opendkim/signing.table
KeyTable                /etc/opendkim/key.table
ExternalIgnoreList      refile:/etc/opendkim/trusted.hosts
InternalHosts           refile:/etc/opendkim/trusted.hosts
Socket                  inet:12301@localhost
UserID                  opendkim

Create the three supporting files:

echo '*@example.com mail._domainkey.example.com' | sudo tee /etc/opendkim/signing.table
echo 'mail._domainkey.example.com example.com:mail:/etc/opendkim/keys/example.com/mail.private' | sudo tee /etc/opendkim/key.table
printf '127.0.0.1\nlocalhost\n' | sudo tee /etc/opendkim/trusted.hosts

Connect Postfix to OpenDKIM:

sudo postconf -e "milter_default_action = accept"
sudo postconf -e "milter_protocol = 6"
sudo postconf -e "smtpd_milters = inet:localhost:12301"
sudo postconf -e "non_smtpd_milters = inet:localhost:12301"
sudo systemctl restart opendkim postfix

Now publish the public key. Print it:

sudo cat /etc/opendkim/keys/example.com/mail.txt

Create a TXT record named mail._domainkey.example.com with the value shown inside the quotes (join the pieces into one string if it is split). When DNS propagates, test the key:

sudo opendkim-testkey -d example.com -s mail -vvv

A result of key OK means DKIM is working.

Step 7: Test Sending, Receiving and Authentication

1. Send a test message

Send a test message from the server (install mailutils if the mail command is missing):

echo "Test message body" | mail -s "Test from my dedicated server" [email protected]

2. Read the headers

In Gmail, open the message and choose Show original. You want to see SPF: PASS, DKIM: PASS and DMARC: PASS.

3. Check for open relay

From a different machine, try to send mail through your server to an outside address without logging in. It must be rejected.

4. Score your setup

Send a message to a deliverability testing service such as mail-tester.com and review the report for missing or failing checks.

5. Check the connection

openssl s_client -starttls smtp -connect mail.example.com:25

A valid certificate for mail.example.com should appear.

6. Watch the logs

sudo tail -f /var/log/mail.log

How to Keep Your IP Reputation Clean

A working mail server is only half of the job. Mailbox providers such as Gmail, Outlook and Yahoo decide whether to trust you based on your IP address, your domain, your authentication and how recipients react. These practices protect that trust.

1. Start with a clean IP

Before you send anything, check whether your IP appears on a blocklist using a lookup tool such as MXToolbox or Spamhaus. If your IP is already listed, ask your provider for a different one. A previous tenant's history becomes yours.

2. Get authentication and DNS exactly right

  • PTR and hostname match: the IP resolves to mail.example.com, and that name resolves back to the IP.

  • SPF, DKIM and DMARC all pass, and the domains align with your visible From address.

  • Consistent HELO name: Postfix announces your myhostname, which should match the PTR.

Large providers now require authentication, and bulk senders face stricter rules, including easy unsubscribe and low spam-complaint rates. Check Google's and Microsoft's current sender requirements before you send at volume, because thresholds change.

3. Warm up the IP gradually

A new IP has no history, and a sudden burst of mail looks suspicious. Increase volume slowly and send first to engaged recipients. A typical approach:

Period Suggested daily volume
Days 1 to 3 Tens of messages to active contacts
Week 1 Low hundreds
Week 2 Gradually double if bounces and complaints stay low
Weeks 3 to 6 Keep increasing steadily toward your target

These are guidelines, not provider rules. If you see deferrals or spam-folder placement, slow down.

4. Send only wanted mail

  • Use confirmed opt-in lists

  • Remove hard bounces immediately

  • Remove recipients who never engage

  • Include an unsubscribe link in bulk mail

  • Never buy or scrape lists

Spam complaints damage reputation faster than any technical mistake.

5. Separate different kinds of mail

Keep transactional mail (receipts, password resets) apart from marketing or bulk mail, ideally on separate IPs or at least separate subdomains. A complaint wave on a newsletter should never block your password-reset emails.

6. Limit your sending rate

Throttling prevents burst sending and reduces the damage if an account is compromised:

sudo postconf -e "default_destination_rate_delay = 1s"
sudo postconf -e "default_destination_concurrency_limit = 5"
sudo systemctl reload postfix

Tune these to match your actual volume.

7. Protect the server and the accounts

Compromised mailboxes are a leading cause of blocklisting.

  • Use strong passwords and consider app-specific passwords or key-based access

  • Install Fail2ban with Postfix and Dovecot jails to block password-guessing attacks

  • Keep Postfix, Dovecot and the OS patched

  • Never leave the server as an open relay

8. Monitor reputation signals

  • Google Postmaster Tools: domain and IP reputation, spam rate, authentication results

  • Microsoft SNDS and JMRP: IP data and complaint feedback for Outlook.com recipients

  • DMARC reports: the rua address in your DMARC record receives aggregate reports showing who sends mail as your domain

  • Blocklist checks: run regular lookups on your IP and domain

  • Queue and bounce review: postqueue -p shows stuck mail, and bounce messages tell you which providers reject you and why

9. Tighten DMARC gradually

Start with p=none to collect reports and find legitimate senders you forgot about. When reports show only authorized mail passing, move to p=quarantine, then to p=reject. This protects your domain from spoofing and strengthens your reputation.

Maintenance Checklist

Task Frequency
Review /var/log/mail.log for errors and rejections Weekly
Check IP and domain on blocklists Weekly, and after any deliverability complaint
Review DMARC reports and Postmaster Tools Weekly to monthly
Apply OS and mail software updates Monthly, or immediately for security fixes
Confirm certificate renewal works Quarterly
Back up mailboxes and configuration Daily or weekly, with tested restores
Review accounts and remove unused ones Quarterly

For monitoring, our Prometheus and Grafana tutorial shows how to graph server health. For backups, see our dedicated server backup guide.

Troubleshooting Common Problems

Symptom Likely cause Fix
Mail never leaves the server Outbound port 25 blocked Test with nc, then ask your provider to open it
Messages go to spam Missing or failing SPF, DKIM or DMARC; no PTR Recheck DNS records and Gmail's "Show original" results
550 5.7.1 rejection IP on a blocklist or failing authentication Check the IP on blocklist tools and read the bounce text
Rejection mentioning reverse DNS PTR missing or does not match hostname Set PTR to mail.example.com and verify the A record
421 or "deferred" messages Rate limiting by the receiver Slow your sending and warm up the IP more gradually
DKIM fails Wrong selector, truncated key or DNS not propagated Run opendkim-testkey and recheck the TXT record
Cannot log in on port 587 TLS or Dovecot socket problem Check /var/log/mail.log and the socket permissions in 10-master.conf
Client shows certificate warning Using IP or wrong hostname Connect using mail.example.com

Frequently Asked Questions

Can I run a mail server on a dedicated server?

Yes. A dedicated server is well suited to self-hosted email because you get a dedicated IP address, control over reverse DNS and open ports, and no shared reputation. You also need to handle DNS, authentication and maintenance yourself.

Is a dedicated IP necessary for email?

It is strongly recommended. With a dedicated IP, your reputation depends only on your own sending behavior. On a shared IP, other users' mistakes can affect your deliverability.

Why do my emails go to spam?

The usual causes are missing SPF, DKIM or DMARC records, a missing or mismatched PTR record, a new IP with no sending history, or recipients marking your mail as spam. Fix authentication first, then warm up your IP and clean your lists.

What is reverse DNS and why does it matter for email?

Reverse DNS (a PTR record) maps your IP address back to a hostname. Receiving servers check that it exists and matches your mail server's name. Without it, many servers reject or spam-filter your mail.

How long does IP warm-up take?

Plan for several weeks of gradual volume increases. The exact time depends on your target volume and how recipients respond.

What ports does a mail server need?

Port 25 for server-to-server SMTP, 587 for authenticated mail submission and 993 for secure IMAP. You also need port 80 or another method to obtain and renew TLS certificates.

Should I use Postfix and Dovecot, or a mail suite?

Postfix and Dovecot give you flexibility and are widely documented. All-in-one mail suites can be easier to deploy and manage, and are worth considering for many domains or non-technical administrators.

Can I send newsletters from my own mail server?

You can, but treat it carefully. Warm up the IP, use consent-based lists, separate bulk and transactional mail and monitor complaints closely. For very large campaigns, a specialist email delivery service may be easier.

Conclusion

Running a mail server on a dedicated server is practical when you take the DNS and reputation side as seriously as the software. Install Postfix and Dovecot, sign your mail with DKIM, publish correct SPF and DMARC records, match your reverse DNS to your hostname, and then protect your IP by sending only wanted mail at a steady, gradually increasing pace.

Ready to set it up? Explore KW Servers dedicated servers with dedicated IPv4 addresses and the control you need for a reliable mail server, or continue with our cPanel server management guide if you prefer a control-panel-based email setup.

This tutorial is reviewed and updated as mail software versions and mailbox provider requirements change. Commands target Ubuntu 24.04 LTS; verify package versions and sender requirements before deploying to production.

Discover KW Servers Dedicated Server Locations

KW Servers servers are available around the world, providing diverse options for hosting websites. Each region offers unique advantages, making it easier to choose a location that best suits your specific hosting needs.

Find Your Perfect Server

AI-powered · Instant results

Ask KW Servers AI
Instantly match you to the perfect dedicated server

How can I help you today?

Try asking for specific hardware, locations, or budgets.

Ryzen 9 in Germany

High-performance compute nodes in EU

128GB RAM Servers

Ideal for heavy virtualization

Budget Gaming

Low-latency servers under $100/mo

10TB Storage Arrays

Secure backup and archiving