Building Your Own Email Server: A Complete Guide to Postfix and Dovecot
Running your own email server gives you complete control over your communications, enhanced privacy, and the ability to use custom domain names for professional correspondence. In this comprehensive guide, we’ll walk through setting up a fully functional email server using Postfix for sending emails (SMTP) and Dovecot for receiving them (IMAP/POP3).
Prerequisites
Before we begin, you’ll need:
- A VPS or dedicated server running Ubuntu 22.04 or Debian 11 (minimum 1GB RAM)
- A registered domain name (e.g., yourdomain.com)
- Root or sudo access to your server
- Basic understanding of Linux command line
- Port 25, 587, 993, and 465 open on your firewall
Understanding the Components
Postfix is a Mail Transfer Agent (MTA) that handles sending and receiving emails via SMTP. It’s robust, secure, and widely used in production environments.
Dovecot is an IMAP and POP3 server that allows email clients to retrieve messages from the server. It handles user authentication and mailbox management.
Step 1: DNS Configuration
Before installing anything, configure your domain’s DNS records. These are crucial for email delivery and authentication.
Required DNS Records
Add these records in your domain registrar’s DNS panel:
# A Record - Points your mail server to your IP
mail.yourdomain.com A YOUR_SERVER_IP# MX Record - Tells other servers where to send emails
yourdomain.com MX 10 mail.yourdomain.com# PTR Record (Reverse DNS) - Set this through your VPS provider
YOUR_SERVER_IP PTR mail.yourdomain.com# SPF Record - Prevents email spoofing
yourdomain.com TXT "v=spf1 mx ~all"# DMARC Record - Email authentication policy
_dmarc.yourdomain.com TXT "v=DMARC1; p=quarantine; rua=mailto:postmaster@yourdomain.com"
Wait 24–48 hours for DNS propagation, though it often happens faster.
Step 2: Update Your System and Set Hostname
# Update package lists
sudo apt update && sudo apt upgrade -y# Set your hostname
sudo hostnamectl set-hostname mail.yourdomain.com# Update /etc/hosts
echo "YOUR_SERVER_IP mail.yourdomain.com mail" | sudo tee -a /etc/hosts
Step 3: Install Postfix
# Install Postfix
sudo apt install postfix -yDuring installation, you’ll be prompted:
- General type: Select “Internet Site”
- System mail name: Enter
yourdomain.com
Step 4: Configure Postfix
Edit the main Postfix configuration file:
sudo nano /etc/postfix/main.cfReplace or add these configurations:
# Basic Settings
myhostname = mail.yourdomain.com
mydomain = yourdomain.com
myorigin = $mydomain
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all# Virtual mailbox settings
home_mailbox = Maildir/
virtual_mailbox_domains = /etc/postfix/virtual_domains
virtual_mailbox_maps = hash:/etc/postfix/vmailbox
virtual_alias_maps = hash:/etc/postfix/virtual# SMTP Authentication
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# TLS Configuration
smtpd_tls_cert_file = /etc/ssl/certs/mailcert.pem
smtpd_tls_key_file = /etc/ssl/private/mailkey.pem
smtpd_tls_security_level = may
smtpd_tls_auth_only = yes
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
smtp_tls_security_level = may# 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_hostnamesmtpd_recipient_restrictions = permit_mynetworks,
permit_sasl_authenticated,
reject_non_fqdn_recipient,
reject_unknown_recipient_domain,
reject_unauth_destination,
reject_rbl_client zen.spamhaus.org,
reject_rbl_client bl.spamcop.net,
permit
Step 5: Configure SSL/TLS Certificates
For production, use Let’s Encrypt for free SSL certificates:
# Install Certbot
sudo apt install certbot -y# Generate certificate
sudo certbot certonly --standalone -d mail.yourdomain.com# Link certificates for Postfix
sudo ln -s /etc/letsencrypt/live/mail.yourdomain.com/fullchain.pem /etc/ssl/certs/mailcert.pem
sudo ln -s /etc/letsencrypt/live/mail.yourdomain.com/privkey.pem /etc/ssl/private/mailkey.pem
For testing, you can generate self-signed certificates:
sudo openssl req -new -x509 -days 365 -nodes \
-out /etc/ssl/certs/mailcert.pem \
-keyout /etc/ssl/private/mailkey.pemStep 6: Configure Virtual Domains and Mailboxes
Create virtual domain file:
echo "yourdomain.com" | sudo tee /etc/postfix/virtual_domainsCreate virtual mailbox file:
sudo nano /etc/postfix/vmailboxAdd your email addresses (format: email address, then directory):
user@yourdomain.com yourdomain.com/user/
admin@yourdomain.com yourdomain.com/admin/Create virtual alias file for forwarding:
sudo nano /etc/postfix/virtualAdd aliases if needed:
postmaster@yourdomain.com admin@yourdomain.com
info@yourdomain.com user@yourdomain.comGenerate hash databases:
sudo postmap /etc/postfix/vmailbox
sudo postmap /etc/postfix/virtualStep 7: Configure Postfix Master Process
Edit the master configuration:
sudo nano /etc/postfix/master.cfEnsure these lines are uncommented and configured:
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=ORIGINATINGsmtps 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=ORIGINATINGStep 8: Install and Configure Dovecot
# Install Dovecot
sudo apt install dovecot-core dovecot-imapd dovecot-pop3d -yConfigure Dovecot Mail Location
sudo nano /etc/dovecot/conf.d/10-mail.confSet the mail location:
mail_location = maildir:~/Maildir
mail_privileged_group = mailConfigure Dovecot Authentication
sudo nano /etc/dovecot/conf.d/10-auth.confModify these settings:
disable_plaintext_auth = yes
auth_mechanisms = plain loginAt the bottom, ensure this line is included:
!include auth-system.conf.extConfigure Dovecot Master Settings
sudo nano /etc/dovecot/conf.d/10-master.confFind the service auth section and modify it:
service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}
}Configure SSL for Dovecot
sudo nano /etc/dovecot/conf.d/10-ssl.confConfigure SSL:
ssl = required
ssl_cert = </etc/ssl/certs/mailcert.pem
ssl_key = </etc/ssl/private/mailkey.pem
ssl_min_protocol = TLSv1.2
ssl_prefer_server_ciphers = yesStep 9: Create System Users
Each email address needs a corresponding Linux user:
# Create users
sudo useradd -m -s /bin/bash user
sudo useradd -m -s /bin/bash admin# Set passwords
sudo passwd user
sudo passwd admin# Create Maildir structure
sudo maildirmake.dovecot /home/user/Maildir
sudo maildirmake.dovecot /home/admin/Maildir# Set proper permissions
sudo chown -R user:user /home/user/Maildir
sudo chown -R admin:admin /home/admin/Maildir
Step 10: Configure DKIM for Email Authentication
DKIM adds a digital signature to outgoing emails, improving deliverability.
# Install OpenDKIM
sudo apt install opendkim opendkim-tools -y# Create directory structure
sudo mkdir -p /etc/opendkim/keys/yourdomain.com
cd /etc/opendkim/keys/yourdomain.com# Generate keys
sudo opendkim-genkey -s mail -d yourdomain.com# Set permissions
sudo chown opendkim:opendkim mail.private
sudo chmod 600 mail.private
Configure OpenDKIM:
sudo nano /etc/opendkim.confAdd these configurations:
Syslog yes
SyslogSuccess yes
LogWhy yesDomain yourdomain.com
KeyFile /etc/opendkim/keys/yourdomain.com/mail.private
Selector mailSocket inet:8891@localhostPidFile /run/opendkim/opendkim.pid
OversignHeaders FromUserID opendkim
UMask 007Mode sv
SubDomains no
AutoRestart yes
Add DKIM to Postfix:
sudo nano /etc/postfix/main.cfAdd at the end:
# DKIM
milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:localhost:8891
non_smtpd_milters = inet:localhost:8891Get your DKIM DNS record:
sudo cat /etc/opendkim/keys/yourdomain.com/mail.txtAdd this as a TXT record in your DNS:
mail._domainkey.yourdomain.com TXT "v=DKIM1; k=rsa; p=YOUR_PUBLIC_KEY_HERE"Step 11: Start and Enable Services
# Restart Postfix
sudo systemctl restart postfix
sudo systemctl enable postfix# Restart Dovecot
sudo systemctl restart dovecot
sudo systemctl enable dovecot# Restart OpenDKIM
sudo systemctl restart opendkim
sudo systemctl enable opendkim# Check service status
sudo systemctl status postfix
sudo systemctl status dovecot
sudo systemctl status opendkim
Step 12: Configure Firewall
# Allow necessary ports
sudo ufw allow 25/tcp # SMTP
sudo ufw allow 587/tcp # Submission
sudo ufw allow 465/tcp # SMTPS
sudo ufw allow 993/tcp # IMAPS
sudo ufw allow 995/tcp # POP3S# Enable firewall
sudo ufw enableStep 13: Testing Your Email Server
Test SMTP (Sending)
# Test from command line
echo "Test email body" | mail -s "Test Subject" recipient@example.com# Check mail logs
sudo tail -f /var/log/mail.logTest with Telnet
# Test SMTP connection
telnet mail.yourdomain.com 25# Test submission port
telnet mail.yourdomain.com 587# Test IMAP
telnet mail.yourdomain.com 993
Configure Email Client
Use these settings in your email client (Thunderbird, Outlook, etc.):
Get Vipin Singh Inkiya’s stories in your inbox
Join Medium for free to get updates from this writer.
Incoming Mail (IMAP):
- Server: mail.yourdomain.com
- Port: 993
- Security: SSL/TLS
- Authentication: Normal password
- Username: user (just the username, not full email)
Outgoing Mail (SMTP):
- Server: mail.yourdomain.com
- Port: 587
- Security: STARTTLS
- Authentication: Normal password
- Username: user
Step 14: Monitor and Maintain
Check Logs Regularly
# Main mail log
sudo tail -f /var/log/mail.log# Authentication issues
sudo tail -f /var/log/auth.logCommon Commands
# View mail queue
mailq# Flush mail queue
sudo postfix flush# Check Postfix configuration
sudo postfix check# Reload Postfix after config changes
sudo postfix reload# Test Dovecot configuration
sudo doveconf -n
Automated Certificate Renewal
# Test renewal
sudo certbot renew --dry-run# Certbot automatically sets up renewal, but verify:
sudo systemctl status certbot.timerTroubleshooting Common Issues
Emails Not Sending
- Check if port 25 is blocked by your ISP or hosting provider
- Verify DNS records are properly configured
- Check mail logs:
sudo tail -100 /var/log/mail.log - Ensure firewall rules allow traffic
- Test SPF, DKIM, and DMARC records using online tools
Authentication Failures
- Verify user exists:
id username - Check password: Try resetting with
sudo passwd username - Review Dovecot auth logs:
sudo grep dovecot /var/log/mail.log - Ensure Postfix can communicate with Dovecot:
ls -la /var/spool/postfix/private/auth
Emails Marked as Spam
- Verify reverse DNS (PTR record) is set correctly
- Check SPF, DKIM, and DMARC using tools like MXToolbox
- Ensure your server IP isn’t on blacklists: Check at mxtoolbox.com/blacklists.aspx
- Warm up your IP by gradually increasing sending volume
Connection Issues
- Verify services are running:
sudo systemctl status postfix dovecot - Check if ports are listening:
sudo netstat -tlnp | grep -E '25|587|993' - Test connectivity from external network
- Review firewall rules:
sudo ufw status
Security Best Practices
- Keep software updated: Regularly run
sudo apt update && sudo apt upgrade - Use strong passwords: Enforce complex passwords for all email accounts
- Enable fail2ban: Protect against brute force attacks
- Regular backups: Backup
/home/*/Maildirand configuration files - Monitor logs: Set up log monitoring and alerts
- Limit access: Only allow necessary ports through firewall
- Use encrypted connections: Always require TLS/SSL
- Implement rate limiting: Prevent abuse of your server
Conclusion
You now have a fully functional email server capable of sending and receiving emails with your custom domain. This setup provides you with complete control over your email infrastructure, enhanced privacy, and professional communication capabilities.
Remember that running an email server requires ongoing maintenance, monitoring, and security updates. Regularly check your logs, keep software updated, and monitor your server’s reputation to ensure reliable email delivery.
For production environments, consider additional components like spam filtering (SpamAssassin), webmail interfaces (Roundcube or Rainloop), and backup solutions to create a robust email infrastructure.
Happy emailing!
Thanks for reading!
If you’re a founder, startup, or business looking to build a web application, mobile app, AI solution, or automate your business processes, Arahita Labs can help turn your ideas into production-ready products.
We specialize in:
- Custom Web & Mobile App Development
- AI Applications & Automations
- MVP Development for Startups
- UI/UX Design
- Backend Systems & APIs
Learn more at https://arahita.com or connect with us to discuss your project.





