Postfix + Dovecot: Complete Configuration Guide

Introduction

Building a complete, production-ready email server requires the seamless integration of multiple components. While Postfix handles mail transfer (SMTP) and Dovecot manages mail retrieval (IMAP/POP3), bringing these two powerful systems together creates a robust, secure, and fully functional email infrastructure.

This comprehensive guide walks you through the complete process of setting up and integrating Postfix and Dovecot on a Linux server. You'll learn how to configure both systems to work together harmoniously, implement SMTP authentication through Dovecot SASL, set up virtual domains and users, establish secure connections with SSL/TLS, and optimize the entire stack for reliability and performance.

Unlike individual component guides, this tutorial focuses specifically on the integration points and configuration decisions that make Postfix and Dovecot work together as a unified email solution. Whether you're setting up email for a single domain or hosting multiple domains with hundreds of users, this guide provides the foundation for a professional mail server.

By the end of this tutorial, you'll have a fully operational email server capable of:

  • Sending and receiving email via SMTP (Postfix)
  • Providing secure IMAP/POP3 access (Dovecot)
  • Authenticating SMTP users through Dovecot
  • Supporting virtual domains and mailboxes
  • Encrypting all connections with SSL/TLS
  • Preventing spam and unauthorized relay

Prerequisites

Before beginning this complete configuration, ensure you have:

System Requirements

  • Fresh Linux server (Ubuntu 20.04/22.04, Debian 10/11, CentOS 8/Rocky Linux 8)
  • Root or sudo access
  • Minimum 2GB RAM (4GB recommended for production)
  • At least 40GB disk space
  • Clean system without previous mail server installations

Domain and Network Requirements

  • Registered domain name (e.g., example.com)
  • Static IP address assigned to your server
  • Access to DNS management for your domain
  • Reverse DNS (PTR) record configured
  • No ISP blocks on mail ports (especially port 25)
  • Ports 25, 143, 587, 993 open and accessible

DNS Records Required

Before starting, configure these DNS records:

# A Record for mail server
mail.example.com.        A       203.0.113.10

# MX Record for domain
example.com.            MX      10 mail.example.com.

# SPF Record (initial)
example.com.            TXT     "v=spf1 mx a ip4:203.0.113.10 ~all"

# PTR Record (via hosting provider)
10.113.0.203.in-addr.arpa.  PTR     mail.example.com.

SSL/TLS Certificates

While you can start with self-signed certificates, production systems should use Let's Encrypt:

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

Knowledge Prerequisites

  • Linux command-line proficiency
  • Basic understanding of email protocols (SMTP, IMAP, POP3)
  • Familiarity with DNS configuration
  • Text editor skills (nano, vim)

Architecture Overview

Understanding how Postfix and Dovecot work together:

Component Roles

Postfix (MTA - Mail Transfer Agent)

  • Receives incoming email from other mail servers (port 25)
  • Sends outgoing email to other mail servers (port 25)
  • Receives email submissions from authenticated clients (port 587)
  • Routes messages to local delivery or relay destinations
  • Performs spam filtering and access controls

Dovecot (MDA - Mail Delivery Agent + IMAP/POP3)

  • Delivers mail to local mailboxes (LMTP)
  • Provides IMAP access for clients (ports 143/993)
  • Provides POP3 access for clients (ports 110/995)
  • Authenticates SMTP users for Postfix (SASL)
  • Manages mailbox storage and indexing

Communication Flow

  1. Incoming Mail: External server → Postfix (port 25) → Dovecot LMTP → Mailbox
  2. Outgoing Mail: Email client → Postfix (port 587) → Dovecot SASL auth → Postfix send
  3. Reading Mail: Email client → Dovecot (IMAP/POP3) → Mailbox
  4. Authentication: All SMTP submissions authenticated via Dovecot SASL

Step 1: Initial System Setup

Update your system and set up the hostname:

# Update system packages
sudo apt update && sudo apt upgrade -y

# Set hostname
sudo hostnamectl set-hostname mail.example.com

# Configure /etc/hosts
sudo nano /etc/hosts

Add this line (replace with your IP):

203.0.113.10    mail.example.com mail

Verify hostname:

hostname -f
# Should output: mail.example.com

Step 2: Install Postfix and Dovecot

Install both packages:

# Ubuntu/Debian
sudo apt install postfix dovecot-core dovecot-imapd dovecot-pop3d dovecot-lmtpd -y

# CentOS/Rocky Linux
sudo dnf install postfix dovecot -y

During Postfix installation, select:

  • Configuration type: Internet Site
  • System mail name: example.com

Step 3: Configure Mailbox Storage Structure

Create a dedicated mail user and directory structure:

# Create virtual mail user
sudo groupadd -g 5000 vmail
sudo useradd -g vmail -u 5000 vmail -d /var/mail/vmail -m -s /usr/sbin/nologin

# Create mail storage directory
sudo mkdir -p /var/mail/vmail
sudo chown -R vmail:vmail /var/mail/vmail
sudo chmod -R 770 /var/mail/vmail

This creates:

  • A system user vmail (UID 5000) that owns all mailboxes
  • A dedicated directory /var/mail/vmail for storing all mail
  • Proper permissions for security

Step 4: Configure Postfix Main Settings

Backup and edit the main Postfix configuration:

sudo cp /etc/postfix/main.cf /etc/postfix/main.cf.backup
sudo nano /etc/postfix/main.cf

Replace or add these configurations:

# Basic settings
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
mydestination = localhost

# Network configuration
inet_interfaces = all
inet_protocols = ipv4

# Trust and relay
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
relayhost =

# Mail delivery
home_mailbox = Maildir/
message_size_limit = 52428800
mailbox_size_limit = 0

# Virtual mailbox configuration
virtual_mailbox_domains = /etc/postfix/virtual_domains
virtual_mailbox_maps = hash:/etc/postfix/virtual_mailboxes
virtual_mailbox_base = /var/mail/vmail
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
virtual_alias_maps = hash:/etc/postfix/virtual_aliases

# Dovecot LMTP for local delivery
virtual_transport = lmtp:unix:private/dovecot-lmtp

# SMTP restrictions
smtpd_helo_required = yes
smtpd_helo_restrictions =
    permit_mynetworks,
    permit_sasl_authenticated,
    reject_invalid_helo_hostname,
    reject_non_fqdn_helo_hostname,
    reject_unknown_helo_hostname

smtpd_sender_restrictions =
    permit_mynetworks,
    permit_sasl_authenticated,
    reject_non_fqdn_sender,
    reject_unknown_sender_domain

smtpd_recipient_restrictions =
    permit_mynetworks,
    permit_sasl_authenticated,
    reject_non_fqdn_recipient,
    reject_unknown_recipient_domain,
    reject_unauth_destination,
    reject_unauth_pipelining,
    reject_rbl_client zen.spamhaus.org,
    reject_rbl_client bl.spamcop.net,
    permit

# Anti-spam
disable_vrfy_command = yes
smtpd_data_restrictions = reject_unauth_pipelining

# TLS configuration
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pem
smtpd_use_tls = yes
smtpd_tls_security_level = may
smtpd_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtpd_tls_ciphers = high
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtpd_tls_mandatory_ciphers = high
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtp_tls_security_level = may
smtpd_tls_loglevel = 1

# SASL authentication via Dovecot
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $myhostname
broken_sasl_auth_clients = yes

# Milter configuration (for future spam filtering)
milter_default_action = accept
milter_protocol = 6

# Miscellaneous
biff = no
append_dot_mydomain = no
readme_directory = no
compatibility_level = 2

Step 5: Configure Postfix Master Settings

Edit master.cf for submission and encryption:

sudo nano /etc/postfix/master.cf

Find and modify these sections:

# SMTP service (receiving mail from other servers)
smtp      inet  n       -       y       -       -       smtpd

# Submission service (port 587 for authenticated clients)
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_reject_unlisted_recipient=no
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o smtpd_helo_restrictions=
  -o smtpd_sender_restrictions=
  -o smtpd_recipient_restrictions=
  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING

# SMTPS (port 465, optional but recommended)
smtps     inet  n       -       y       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o smtpd_recipient_restrictions=
  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING

Step 6: Create Virtual Domain and Mailbox Files

Virtual Domains

sudo nano /etc/postfix/virtual_domains

Add your domains (one per line):

example.com
example.net

Virtual Mailboxes

sudo nano /etc/postfix/virtual_mailboxes

Add mailboxes (format: email@domain directory):

[email protected]       example.com/admin/
[email protected]        example.com/user/
[email protected]        example.com/info/
[email protected]     example.net/contact/

Virtual Aliases

sudo nano /etc/postfix/virtual_aliases

Add aliases (format: alias@domain real@address):

[email protected]      [email protected]
[email protected]           [email protected]
[email protected]       [email protected]
[email protected]           [email protected]
[email protected]         [email protected]

Compile and Apply Maps

# Generate hash databases
sudo postmap /etc/postfix/virtual_mailboxes
sudo postmap /etc/postfix/virtual_aliases

# Reload Postfix
sudo systemctl reload postfix

Step 7: Configure Dovecot Core Settings

Backup Dovecot configuration:

sudo cp -r /etc/dovecot /etc/dovecot.backup

Edit main configuration:

sudo nano /etc/dovecot/dovecot.conf

Set these parameters:

# Protocols to enable
protocols = imap pop3 lmtp

# Listen on all interfaces
listen = *, ::

# Base directory
base_dir = /var/run/dovecot/

# Disable SSL by default (we'll enable per-service)
ssl = required

Step 8: Configure Dovecot Mail Location

sudo nano /etc/dovecot/conf.d/10-mail.conf

Configure mail storage:

# Mail location for virtual users
mail_location = maildir:/var/mail/vmail/%d/%n/Maildir

# Mail user
mail_privileged_group = vmail
mail_uid = vmail
mail_gid = vmail

# Maildir-specific optimizations
maildir_very_dirty_syncs = yes
maildir_copy_with_hardlinks = yes

# First valid UID/GID
first_valid_uid = 5000
last_valid_uid = 5000
first_valid_gid = 5000
last_valid_gid = 5000

# Namespace configuration
namespace inbox {
  inbox = yes

  mailbox Drafts {
    auto = subscribe
    special_use = \Drafts
  }

  mailbox Junk {
    auto = subscribe
    special_use = \Junk
  }

  mailbox Spam {
    auto = no
    special_use = \Junk
  }

  mailbox Trash {
    auto = subscribe
    special_use = \Trash
  }

  mailbox Sent {
    auto = subscribe
    special_use = \Sent
  }

  mailbox "Sent Messages" {
    auto = no
    special_use = \Sent
  }
}

Explanation of mail_location:

  • %d = domain part of email address (example.com)
  • %n = username part of email address (user)
  • Full path: /var/mail/vmail/example.com/user/Maildir

Step 9: Configure Dovecot Authentication

sudo nano /etc/dovecot/conf.d/10-auth.conf

Configure authentication:

# Require encryption for authentication
disable_plaintext_auth = yes

# Authentication mechanisms
auth_mechanisms = plain login

# Verbose logging during setup (disable in production)
auth_verbose = yes
auth_verbose_passwords = no
auth_debug = no

# Include passwd-file authentication
!include auth-passwdfile.conf.ext

Create Password File Authentication

sudo nano /etc/dovecot/conf.d/auth-passwdfile.conf.ext

Add:

passdb {
  driver = passwd-file
  args = scheme=SHA512-CRYPT username_format=%u /etc/dovecot/users
}

userdb {
  driver = static
  args = uid=vmail gid=vmail home=/var/mail/vmail/%d/%n
}

Create Users File

sudo nano /etc/dovecot/users

Add users with encrypted passwords:

[email protected]:{SHA512-CRYPT}$6$rounds=100000$...encrypted_password
[email protected]:{SHA512-CRYPT}$6$rounds=100000$...encrypted_password

To generate encrypted passwords:

# Generate password hash
doveadm pw -s SHA512-CRYPT -p 'YourPassword'

# Output will be something like:
# {SHA512-CRYPT}$6$rounds=100000$abc123...

Add the complete output to /etc/dovecot/users:

# Example with real password hash
echo "[email protected]:$(doveadm pw -s SHA512-CRYPT -p 'SecurePassword123')" | sudo tee -a /etc/dovecot/users

# Set proper permissions
sudo chmod 640 /etc/dovecot/users
sudo chown root:dovecot /etc/dovecot/users

Step 10: Configure Dovecot SSL/TLS

sudo nano /etc/dovecot/conf.d/10-ssl.conf

Configure SSL:

# Require SSL
ssl = required

# Certificate files
ssl_cert = </etc/letsencrypt/live/mail.example.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/mail.example.com/privkey.pem

# SSL protocols
ssl_min_protocol = TLSv1.2
ssl_protocols = !SSLv2 !SSLv3 !TLSv1 !TLSv1.1

# SSL cipher suite
ssl_cipher_list = ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK

ssl_prefer_server_ciphers = yes

# DH parameters
ssl_dh = </etc/dovecot/dh.pem

Generate DH parameters:

sudo openssl dhparam -out /etc/dovecot/dh.pem 2048
sudo chmod 600 /etc/dovecot/dh.pem

Step 11: Configure Dovecot Master Services

sudo nano /etc/dovecot/conf.d/10-master.conf

Configure service settings for Postfix integration:

service imap-login {
  inet_listener imap {
    port = 143
  }
  inet_listener imaps {
    port = 993
    ssl = yes
  }

  service_count = 1
  process_min_avail = 4
  process_limit = 500
}

service pop3-login {
  inet_listener pop3 {
    port = 110
  }
  inet_listener pop3s {
    port = 995
    ssl = yes
  }

  service_count = 1
  process_min_avail = 2
  process_limit = 200
}

service lmtp {
  # Postfix will use this socket for local delivery
  unix_listener /var/spool/postfix/private/dovecot-lmtp {
    mode = 0600
    user = postfix
    group = postfix
  }
}

service auth {
  # Postfix SMTP authentication socket
  unix_listener /var/spool/postfix/private/auth {
    mode = 0660
    user = postfix
    group = postfix
  }

  # Auth process settings
  unix_listener auth-userdb {
    mode = 0600
    user = vmail
    group = vmail
  }

  user = dovecot
}

service auth-worker {
  user = vmail
}

This configuration creates:

  • UNIX socket at /var/spool/postfix/private/auth for SMTP authentication
  • UNIX socket at /var/spool/postfix/private/dovecot-lmtp for mail delivery
  • Proper permissions for Postfix to access these sockets

Step 12: Configure Dovecot LMTP

sudo nano /etc/dovecot/conf.d/20-lmtp.conf

Add:

protocol lmtp {
  # Mail plugins
  mail_plugins = $mail_plugins

  # Postmaster address
  postmaster_address = [email protected]

  # Enable address extensions (user+tag@domain)
  lmtp_save_to_detail_mailbox = yes
  recipient_delimiter = +
}

Step 13: Configure Firewall

Allow all necessary mail ports:

UFW (Ubuntu/Debian)

sudo ufw allow 25/tcp comment 'SMTP'
sudo ufw allow 587/tcp comment 'Submission'
sudo ufw allow 465/tcp comment 'SMTPS'
sudo ufw allow 143/tcp comment 'IMAP'
sudo ufw allow 993/tcp comment 'IMAPS'
sudo ufw allow 110/tcp comment 'POP3'
sudo ufw allow 995/tcp comment 'POP3S'
sudo ufw reload

Firewalld (CentOS/Rocky)

sudo firewall-cmd --permanent --add-service=smtp
sudo firewall-cmd --permanent --add-service=smtp-submission
sudo firewall-cmd --permanent --add-service=smtps
sudo firewall-cmd --permanent --add-service=imap
sudo firewall-cmd --permanent --add-service=imaps
sudo firewall-cmd --permanent --add-service=pop3
sudo firewall-cmd --permanent --add-service=pop3s
sudo firewall-cmd --reload

Step 14: Start and Enable Services

# Enable services to start on boot
sudo systemctl enable postfix
sudo systemctl enable dovecot

# Start services
sudo systemctl start postfix
sudo systemctl start dovecot

# Check status
sudo systemctl status postfix
sudo systemctl status dovecot

Step 15: Testing the Complete Setup

Test 1: Check Configuration Syntax

# Check Postfix configuration
sudo postfix check

# Check Dovecot configuration
sudo doveconf -n

No output from postfix check means no errors.

Test 2: Verify Services Are Listening

# Check all mail ports
sudo netstat -tlnp | grep -E ':(25|587|465|143|993|110|995)'

You should see services listening on all configured ports.

Test 3: Test Dovecot Authentication

# Test user authentication
doveadm auth test [email protected] SecurePassword123

Expected output:

passdb: [email protected] auth succeeded
userdb: [email protected]

Test 4: Send Test Email via Command Line

# Install mail client if needed
sudo apt install mailutils -y

# Send test email
echo "Test email body" | mail -s "Test Subject" -r [email protected] [email protected]

Check logs:

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

Look for successful delivery through LMTP to Dovecot.

Test 5: Test SMTP Submission with Authentication

# Test authenticated submission
telnet localhost 587

After connection, enter:

EHLO test.local
AUTH LOGIN

You'll be prompted for username and password (base64 encoded).

Encode credentials:

echo -n '[email protected]' | base64
echo -n 'SecurePassword123' | base64

Use the base64 output for authentication.

Test 6: Test IMAP Access

# Test IMAP connection
telnet localhost 143

Commands:

a1 LOGIN [email protected] SecurePassword123
a2 LIST "" "*"
a3 SELECT INBOX
a4 LOGOUT

Test 7: Test Complete Email Flow

Using an email client (Thunderbird, Outlook, etc.):

Incoming Server (IMAP):

  • Server: mail.example.com
  • Port: 993
  • Security: SSL/TLS
  • Authentication: Normal password
  • Username: [email protected]
  • Password: SecurePassword123

Outgoing Server (SMTP):

  • Server: mail.example.com
  • Port: 587
  • Security: STARTTLS
  • Authentication: Normal password
  • Username: [email protected]
  • Password: SecurePassword123

Send a test email to yourself and verify:

  1. Email appears in Sent folder
  2. Email is received in Inbox
  3. No errors in logs

Test 8: Test External Delivery

Send email from your server to Gmail/Outlook:

echo "Test from mail server" | mail -s "External test" -r [email protected] [email protected]

Check:

  1. Email arrives (may take a minute)
  2. Check spam folder if not in inbox
  3. View full headers to see authentication results

Troubleshooting Common Integration Issues

Issue 1: Postfix Can't Connect to Dovecot LMTP

Symptoms: Mail stuck in queue, errors about LMTP connection

Diagnosis:

# Check if socket exists
ls -la /var/spool/postfix/private/dovecot-lmtp

# Check Dovecot logs
sudo tail -f /var/log/dovecot.log

# Check Postfix logs
sudo tail -f /var/log/mail.log

Solutions:

  • Verify socket path in both configs matches
  • Check socket permissions (should be owned by postfix:postfix)
  • Restart both services: sudo systemctl restart postfix dovecot

Issue 2: SMTP Authentication Failing

Symptoms: Can't send email, "Authentication failed" errors

Diagnosis:

# Test authentication manually
doveadm auth test [email protected] password

# Check auth socket
ls -la /var/spool/postfix/private/auth

# Check Dovecot auth logs
sudo grep "auth" /var/log/dovecot.log

Solutions:

  • Verify user exists in /etc/dovecot/users
  • Check password hash is correct
  • Ensure socket permissions allow Postfix access
  • Verify SASL configuration in Postfix main.cf

Issue 3: Permission Denied Errors

Symptoms: "Permission denied" in logs when delivering mail

Diagnosis:

# Check vmail user and group
id vmail

# Check directory permissions
ls -la /var/mail/vmail/

# Check file ownership
ls -la /var/mail/vmail/example.com/

Solutions:

# Fix ownership recursively
sudo chown -R vmail:vmail /var/mail/vmail/

# Fix permissions
sudo chmod -R 770 /var/mail/vmail/

# Ensure Dovecot runs as vmail for userdb
# Check conf.d/10-master.conf auth-worker section

Issue 4: Mail Not Appearing in IMAP

Symptoms: Email delivered but not visible in email client

Diagnosis:

# Check if mail files exist
sudo find /var/mail/vmail/ -name "cur" -type d -exec ls -la {} \;

# Check Dovecot mail_location
doveconf -n | grep mail_location

# Test IMAP manually
telnet localhost 143

Solutions:

  • Verify mail_location format matches actual directory structure
  • Check %d and %n variables expand correctly
  • Rebuild indexes: doveadm force-resync -u [email protected] INBOX

Issue 5: TLS/SSL Certificate Errors

Symptoms: Certificate warnings in email clients

Diagnosis:

# Test SMTP TLS
openssl s_client -connect mail.example.com:587 -starttls smtp

# Test IMAPS
openssl s_client -connect mail.example.com:993

# Check certificate validity
sudo openssl x509 -in /etc/letsencrypt/live/mail.example.com/fullchain.pem -noout -dates

Solutions:

  • Ensure certificate paths are correct in both Postfix and Dovecot configs
  • Verify certificate matches mail.example.com hostname
  • Renew expired certificates
  • Use fullchain.pem (not cert.pem) for proper certificate chain

Performance Optimization

Postfix Optimization

sudo nano /etc/postfix/main.cf

Add:

# Connection caching
smtp_connection_cache_destinations = example.com
smtp_connection_cache_time_limit = 2s

# Queue management
maximal_queue_lifetime = 5d
bounce_queue_lifetime = 5d
maximal_backoff_time = 4000s
minimal_backoff_time = 300s

# Concurrency
default_process_limit = 100
smtpd_client_connection_count_limit = 50

Dovecot Optimization

sudo nano /etc/dovecot/conf.d/10-master.conf

Adjust process limits:

service imap-login {
  process_limit = 1000
  client_limit = 1000
}

default_process_limit = 1000
default_client_limit = 1000

Enable mail caching:

sudo nano /etc/dovecot/conf.d/10-mail.conf

Add:

mail_cache_min_mail_count = 0

Security Hardening

1. Implement Fail2ban

sudo apt install fail2ban -y

Configure for Postfix and Dovecot:

sudo nano /etc/fail2ban/jail.local

Add:

[postfix]
enabled = true
port = smtp,465,submission
filter = postfix
logpath = /var/log/mail.log
maxretry = 5
bantime = 3600

[dovecot]
enabled = true
port = imap,imaps,pop3,pop3s
filter = dovecot
logpath = /var/log/dovecot.log
maxretry = 5
bantime = 3600

Restart:

sudo systemctl restart fail2ban

2. Rate Limiting

In Postfix main.cf:

anvil_rate_time_unit = 60s
smtpd_client_connection_rate_limit = 30
smtpd_client_message_rate_limit = 100

3. Disable Unnecessary Services

If not using POP3, disable it:

sudo nano /etc/dovecot/dovecot.conf

Change:

protocols = imap lmtp

Reload:

sudo systemctl reload dovecot

Monitoring and Maintenance

Daily Monitoring

# Check mail queue
sudo mailq

# Check Dovecot connections
sudo doveadm who

# Monitor logs in real-time
sudo tail -f /var/log/mail.log
sudo tail -f /var/log/dovecot.log

Weekly Tasks

# Check for errors
sudo grep -i error /var/log/mail.log | tail -50
sudo grep -i error /var/log/dovecot.log | tail -50

# Check authentication failures
sudo grep "authentication failed" /var/log/dovecot.log | wc -l

# Review rejected mail
sudo grep "reject:" /var/log/mail.log | tail -20

# Check disk usage
du -sh /var/mail/vmail/*

Create Monitoring Script

sudo nano /usr/local/bin/mail-check.sh

Add:

#!/bin/bash

echo "=== Mail Server Status Check ==="
echo ""

echo "Postfix Status:"
systemctl status postfix | grep Active

echo ""
echo "Dovecot Status:"
systemctl status dovecot | grep Active

echo ""
echo "Mail Queue:"
mailq | tail -1

echo ""
echo "Active IMAP/POP3 Sessions:"
doveadm who | wc -l

echo ""
echo "Disk Usage:"
df -h /var/mail/vmail | tail -1

echo ""
echo "Recent Errors:"
grep -i error /var/log/mail.log | tail -5

Make executable:

sudo chmod +x /usr/local/bin/mail-check.sh

Run daily via cron:

sudo crontab -e

Add:

0 9 * * * /usr/local/bin/mail-check.sh | mail -s "Daily Mail Server Report" [email protected]

Adding New Users and Domains

Add New User

# Generate password hash
NEW_PASSWORD=$(doveadm pw -s SHA512-CRYPT -p 'UserPassword')

# Add to users file
echo "[email protected]:$NEW_PASSWORD" | sudo tee -a /etc/dovecot/users

# Add to virtual mailboxes
echo "[email protected]    example.com/newuser/" | sudo tee -a /etc/postfix/virtual_mailboxes

# Rebuild maps
sudo postmap /etc/postfix/virtual_mailboxes

# Reload services
sudo systemctl reload postfix dovecot

Add New Domain

# Add domain
echo "newdomain.com" | sudo tee -a /etc/postfix/virtual_domains

# Add first user for domain
NEW_PASSWORD=$(doveadm pw -s SHA512-CRYPT -p 'AdminPassword')
echo "[email protected]:$NEW_PASSWORD" | sudo tee -a /etc/dovecot/users

# Add mailbox
echo "[email protected]    newdomain.com/admin/" | sudo tee -a /etc/postfix/virtual_mailboxes

# Rebuild maps
sudo postmap /etc/postfix/virtual_mailboxes

# Create directory
sudo mkdir -p /var/mail/vmail/newdomain.com
sudo chown -R vmail:vmail /var/mail/vmail/newdomain.com

# Reload services
sudo systemctl reload postfix dovecot

Configure DNS for new domain:

newdomain.com.          MX      10 mail.example.com.
newdomain.com.          TXT     "v=spf1 mx a ip4:203.0.113.10 ~all"

Backup Strategy

Backup Mail Data

# Create backup directory
sudo mkdir -p /backup/mail

# Backup mailboxes
sudo rsync -av /var/mail/vmail/ /backup/mail/vmail-$(date +%Y%m%d)/

# Backup configurations
sudo tar czf /backup/mail/configs-$(date +%Y%m%d).tar.gz \
    /etc/postfix/ \
    /etc/dovecot/ \
    /etc/letsencrypt/

Automated Backup Script

sudo nano /usr/local/bin/backup-mail.sh

Add:

#!/bin/bash
BACKUP_DIR="/backup/mail"
DATE=$(date +%Y%m%d)

# Create backup directory
mkdir -p $BACKUP_DIR

# Backup mail data
rsync -av --delete /var/mail/vmail/ $BACKUP_DIR/vmail-latest/

# Backup configurations
tar czf $BACKUP_DIR/configs-$DATE.tar.gz \
    /etc/postfix/ \
    /etc/dovecot/

# Keep only last 7 days of config backups
find $BACKUP_DIR -name "configs-*.tar.gz" -mtime +7 -delete

# Log
echo "Mail backup completed: $DATE" >> $BACKUP_DIR/backup.log

Make executable and schedule:

sudo chmod +x /usr/local/bin/backup-mail.sh
sudo crontab -e

Add:

0 2 * * * /usr/local/bin/backup-mail.sh

Conclusion

You now have a complete, integrated Postfix and Dovecot email server with:

  • Secure SMTP submission with authentication
  • IMAP and POP3 access with SSL/TLS encryption
  • Virtual domain and user support
  • Local mail delivery via LMTP
  • Comprehensive security measures
  • Performance optimizations

This setup provides a solid foundation for a production email server capable of handling multiple domains and users reliably and securely.

Key Achievements

  1. Complete Integration: Postfix and Dovecot work seamlessly together
  2. Virtual Hosting: Support for multiple domains and users
  3. Security: SSL/TLS encryption, SASL authentication, restricted relay
  4. Performance: Optimized for efficiency and scalability
  5. Maintainability: Organized configuration and monitoring

Next Steps

To further enhance your email server:

  1. Implement DKIM for email authentication and better deliverability
  2. Configure SPF and DMARC for complete email authentication
  3. Add SpamAssassin for spam filtering
  4. Install webmail (Roundcube/Rainloop) for browser access
  5. Set up monitoring (Nagios/Zabbix) for proactive alerting
  6. Configure automated backups to remote storage
  7. Implement quotas to manage disk usage per user
  8. Add Sieve filtering for server-side mail rules

Important Reminders

  • Monitor regularly: Check logs daily for issues
  • Update frequently: Apply security updates promptly
  • Test backups: Verify backup restoration works
  • Review security: Audit configurations quarterly
  • Document changes: Keep track of custom modifications

With this complete Postfix and Dovecot setup, you have full control over your email infrastructure, ensuring privacy, security, and reliability for all your email communications.