Should You Self-Host Email?
Self-hosting a mail server is one of the most rewarding — and most demanding — things you can run on a VPS. Before you commit, here is an honest assessment.
Reasons to self-host email:
- Complete data sovereignty — Your emails live on your server, not on Google’s or Microsoft’s infrastructure. Nobody scans your messages for advertising.
- Unlimited mailboxes — Create as many addresses as you want at no additional per-user cost
- Custom domain email — Professional addresses like
you@yourdomain.comwithout paying $6–$12 per user per month for Google Workspace or Microsoft 365 - Learning — Understanding email infrastructure (SMTP, IMAP, DNS, authentication) is valuable knowledge
- Privacy — No third party has access to your communications
Reasons not to self-host email:
- Deliverability challenges — Getting your emails past spam filters at Gmail, Outlook, and Yahoo requires perfect DNS configuration, a clean IP reputation, and ongoing maintenance
- 24/7 responsibility — Email outages are not acceptable. If your server goes down at 3 AM, nobody receives your mail until you fix it
- IP reputation management — If your server’s IP lands on a blacklist (which can happen even if you did nothing wrong), deliverability tanks
- Spam fighting — You need to configure and maintain spam filtering, and it requires ongoing tuning
- Time investment — Initial setup takes 2–4 hours. Ongoing maintenance is 1–2 hours per month.
If you value data sovereignty and are willing to invest the time, read on. If email is mission-critical for your business and you cannot afford any deliverability issues, consider a managed dedicated server where MassiveGRID’s team can help maintain the infrastructure.
Prerequisites
You need:
- An Ubuntu 24.04 VPS with at least 2 GB RAM (4 GB recommended if running spam filtering)
- A fully qualified domain name (FQDN) for your mail server, e.g.,
mail.yourdomain.com - The ability to set rDNS (reverse DNS / PTR record) for your server’s IP address — MassiveGRID allows you to set this from the control panel
- Root or sudo access to the server
- Port 25 open (some providers block it by default — MassiveGRID does not block port 25 on VPS instances)
Mail servers are RAM-hungry but CPU-light. Postfix and Dovecot together use relatively little CPU even under moderate load, but each active IMAP connection consumes memory, and spam filtering (Rspamd) benefits from RAM for its classification models. This makes email an excellent use case for MassiveGRID’s Dedicated VPS, where you can independently scale RAM high while keeping CPU allocation modest — you do not need 8 cores to run a mail server, but you might need 8 GB of RAM for comfortable operation with spam filtering.
Set the hostname before you begin:
sudo hostnamectl set-hostname mail.yourdomain.com
echo "127.0.1.1 mail.yourdomain.com mail" | sudo tee -a /etc/hosts
DNS Records Setup
Email deliverability lives and dies by DNS. Every record must be correct. Configure these at your domain registrar or DNS provider:
A Record
mail.yourdomain.com. IN A YOUR_SERVER_IP
MX Record
yourdomain.com. IN MX 10 mail.yourdomain.com.
PTR Record (Reverse DNS)
This is set at your hosting provider, not your DNS provider. In MassiveGRID’s control panel, set the rDNS for your server’s IP to mail.yourdomain.com. This must match your mail server’s HELO/EHLO hostname exactly. Many receiving mail servers reject messages from IPs without matching PTR records.
SPF Record
yourdomain.com. IN TXT "v=spf1 mx a:mail.yourdomain.com ~all"
This tells receiving servers that your mail server is authorized to send email for your domain. The ~all (softfail) is recommended during testing. Change to -all (hardfail) once you confirm everything works.
DKIM Record
We will generate this after configuring OpenDKIM. For now, know that it will be a TXT record containing your DKIM public key.
DMARC Record
_dmarc.yourdomain.com. IN TXT "v=DMARC1; p=quarantine; rua=mailto:postmaster@yourdomain.com; pct=100"
DMARC tells receiving servers what to do with emails that fail SPF and DKIM checks. Start with p=none during testing (no action, just report), then move to p=quarantine (send to spam) or p=reject (block entirely) once you are confident your configuration is correct.
Installing and Configuring Postfix
Postfix handles sending and receiving email (SMTP). Install it:
sudo apt update
sudo apt install postfix -y
During installation, select “Internet Site” and enter your domain (yourdomain.com).
Edit the main configuration:
sudo nano /etc/postfix/main.cf
Replace the contents with a production-ready configuration:
# Basic settings
myhostname = mail.yourdomain.com
mydomain = yourdomain.com
myorigin = $mydomain
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mynetworks = 127.0.0.0/8 [::1]/128
# Mailbox
home_mailbox = Maildir/
mailbox_size_limit = 0
message_size_limit = 52428800
# SMTP authentication (via Dovecot SASL)
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $myhostname
# TLS settings
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.yourdomain.com/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.yourdomain.com/privkey.pem
smtpd_tls_security_level = may
smtpd_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
smtp_tls_security_level = may
smtp_tls_protocols = !SSLv2, !SSLv3, !TLSv1, !TLSv1.1
# Recipient restrictions
smtpd_recipient_restrictions =
permit_sasl_authenticated,
permit_mynetworks,
reject_unauth_destination,
reject_invalid_hostname,
reject_non_fqdn_hostname,
reject_non_fqdn_sender,
reject_non_fqdn_recipient,
reject_unknown_sender_domain,
reject_unknown_recipient_domain,
reject_rbl_client zen.spamhaus.org
# DKIM integration (added after OpenDKIM setup)
milter_protocol = 6
milter_default_action = accept
smtpd_milters = unix:opendkim/opendkim.sock
non_smtpd_milters = unix:opendkim/opendkim.sock
# Connection limits
smtpd_client_connection_rate_limit = 50
smtpd_error_sleep_time = 5s
smtpd_soft_error_limit = 3
smtpd_hard_error_limit = 10
Configure the submission port (587) for authenticated email sending. Edit /etc/postfix/master.cf and uncomment/add:
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_recipient_restrictions=permit_sasl_authenticated,reject
-o milter_macro_daemon_name=ORIGINATING
Installing and Configuring Dovecot
Dovecot handles IMAP (reading email) and provides SASL authentication for Postfix:
sudo apt install dovecot-core dovecot-imapd dovecot-lmtpd -y
Configure Dovecot’s mail location and authentication. Edit /etc/dovecot/conf.d/10-mail.conf:
mail_location = maildir:~/Maildir
Configure authentication in /etc/dovecot/conf.d/10-auth.conf:
disable_plaintext_auth = yes
auth_mechanisms = plain login
Set up the authentication socket for Postfix in /etc/dovecot/conf.d/10-master.conf:
service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}
}
Configure SSL in /etc/dovecot/conf.d/10-ssl.conf:
ssl = required
ssl_cert = </etc/letsencrypt/live/mail.yourdomain.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/mail.yourdomain.com/privkey.pem
ssl_min_protocol = TLSv1.2
ssl_prefer_server_ciphers = yes
SSL/TLS with Let’s Encrypt
Get certificates before starting the services:
sudo apt install certbot -y
sudo certbot certonly --standalone -d mail.yourdomain.com
Set up auto-renewal with a post-renewal hook that restarts mail services:
sudo nano /etc/letsencrypt/renewal-hooks/deploy/mail-restart.sh
#!/bin/bash
systemctl restart postfix
systemctl restart dovecot
sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/mail-restart.sh
OpenDKIM Setup
DKIM (DomainKeys Identified Mail) cryptographically signs your outgoing emails, proving they came from your server and were not modified in transit. This is critical for deliverability.
sudo apt install opendkim opendkim-tools -y
Configure OpenDKIM:
sudo nano /etc/opendkim.conf
AutoRestart Yes
AutoRestartRate 10/1h
Syslog yes
SyslogSuccess Yes
LogWhy Yes
Canonicalization relaxed/simple
ExternalIgnoreList refile:/etc/opendkim/TrustedHosts
InternalHosts refile:/etc/opendkim/TrustedHosts
KeyTable refile:/etc/opendkim/KeyTable
SigningTable refile:/etc/opendkim/SigningTable
Mode sv
PidFile /run/opendkim/opendkim.pid
SignatureAlgorithm rsa-sha256
UserID opendkim:opendkim
Socket local:/var/spool/postfix/opendkim/opendkim.sock
Create the required directories and files:
sudo mkdir -p /etc/opendkim/keys/yourdomain.com
sudo mkdir -p /var/spool/postfix/opendkim
sudo chown opendkim:postfix /var/spool/postfix/opendkim
Create /etc/opendkim/TrustedHosts:
127.0.0.1
localhost
*.yourdomain.com
Create /etc/opendkim/KeyTable:
mail._domainkey.yourdomain.com yourdomain.com:mail:/etc/opendkim/keys/yourdomain.com/mail.private
Create /etc/opendkim/SigningTable:
*@yourdomain.com mail._domainkey.yourdomain.com
Generate the DKIM keys:
sudo opendkim-genkey -b 2048 -s mail -d yourdomain.com -D /etc/opendkim/keys/yourdomain.com/
sudo chown opendkim:opendkim /etc/opendkim/keys/yourdomain.com/mail.private
View the public key for your DNS record:
sudo cat /etc/opendkim/keys/yourdomain.com/mail.txt
This outputs a TXT record. Add it to your DNS as mail._domainkey.yourdomain.com. The value is the long string inside the parentheses. Note that many DNS providers require you to remove the quotes and join the multi-line value into a single string.
Add the opendkim user to the postfix group and restart services:
sudo adduser postfix opendkim
sudo systemctl restart opendkim
sudo systemctl restart postfix
sudo systemctl restart dovecot
Testing Deliverability
Before you start using your mail server for real communication, test everything thoroughly.
Basic Send/Receive Test
Create a system user for your mailbox:
sudo adduser mailuser
# Set a strong password
Send a test email from the command line:
echo "Test email body" | mail -s "Test from self-hosted mail" your-external@gmail.com
Check the headers of the received email. You should see:
DKIM-Signatureheader presentReceived-SPF: passDMARC: pass
Mail-Tester.com
Send an email to the address shown at mail-tester.com. It checks your SPF, DKIM, DMARC, rDNS, blacklists, and message content. Aim for a score of 9/10 or higher. Common deductions:
- Missing rDNS (-1 point) — Set PTR record in MassiveGRID control panel
- DKIM not configured (-2 points) — Follow the OpenDKIM steps above
- IP on a blacklist (-3 points) — Request delisting or contact MassiveGRID support for a clean IP
Authentication Verification
# Verify DKIM
sudo opendkim-testkey -d yourdomain.com -s mail -vvv
# Verify SPF
dig TXT yourdomain.com | grep spf
# Verify DMARC
dig TXT _dmarc.yourdomain.com
Spam Filtering with Rspamd
Without spam filtering, your inbox will be overrun within hours. Rspamd is a modern, high-performance spam filter that integrates well with Postfix.
sudo apt install rspamd redis-server -y
sudo systemctl enable rspamd redis-server
sudo systemctl start rspamd redis-server
Rspamd works as a milter (mail filter) that Postfix passes messages through. Add to /etc/postfix/main.cf:
# If you already have OpenDKIM milter, add Rspamd alongside it:
smtpd_milters = unix:opendkim/opendkim.sock, inet:localhost:11332
non_smtpd_milters = unix:opendkim/opendkim.sock, inet:localhost:11332
Rspamd uses Redis for its statistical classifier, rate limiting, and greylisting. This is where RAM matters — Rspamd with Redis and its classification models comfortably uses 500 MB–1 GB of RAM. Combined with Postfix, Dovecot, and the OS, a production mail server with spam filtering needs at minimum 2 GB, and 4 GB is recommended for comfortable operation.
This is the strongest case for MassiveGRID’s Dedicated VPS (VDS). Mail servers have an unusual resource profile: they are RAM-hungry but CPU-light. With independent resource scaling on a VDS, you can allocate 8 GB of RAM while keeping CPU at 2–4 cores, which perfectly matches the mail server workload. On providers that only offer fixed plans, you would need to buy a plan with 8 cores just to get 8 GB of RAM — wasting money on CPU you will never use.
Access the Rspamd web interface for monitoring and configuration:
# Set a password for the web interface
sudo rspamadm pw
# Copy the output hash and add to /etc/rspamd/local.d/worker-controller.inc:
# password = "HASH_HERE"
sudo systemctl restart rspamd
The web interface is available at http://your-server-ip:11334. For security, proxy it through Nginx with authentication or only access it through a WireGuard VPN tunnel (see our WireGuard guide).
Webmail with Roundcube
For a complete self-hosted email solution, add webmail access with Roundcube:
sudo apt install roundcube roundcube-plugins -y
During installation, select “Yes” to configure the database with dbconfig-common and choose SQLite or MySQL. Configure the IMAP and SMTP settings in /etc/roundcube/config.inc.php:
$config['default_host'] = 'ssl://mail.yourdomain.com';
$config['default_port'] = 993;
$config['smtp_server'] = 'tls://mail.yourdomain.com';
$config['smtp_port'] = 587;
$config['smtp_user'] = '%u';
$config['smtp_pass'] = '%p';
Set up an Nginx server block to serve Roundcube and issue an SSL certificate with Certbot. After that, you will have a fully functional webmail interface at https://webmail.yourdomain.com.
Maintenance and Monitoring
A mail server requires ongoing attention. Set up these maintenance tasks:
Log Monitoring
# Watch mail logs in real-time
sudo tail -f /var/log/mail.log
# Check for delivery errors
sudo grep "status=bounced\|status=deferred" /var/log/mail.log | tail -20
# Count messages processed today
sudo grep "$(date +%b\ %e)" /var/log/mail.log | grep "status=sent" | wc -l
Queue Management
# View the mail queue
sudo postqueue -p
# Flush deferred messages (retry delivery)
sudo postqueue -f
# Delete all stuck messages (nuclear option)
# sudo postsuper -d ALL
Blacklist Monitoring
Check your IP against major blacklists regularly. Use MXToolbox or set up automated checks:
#!/bin/bash
# /usr/local/bin/check-blacklist.sh
IP="YOUR_SERVER_IP"
# Reverse the IP
REVERSED=$(echo $IP | awk -F. '{print $4"."$3"."$2"."$1}')
BLACKLISTS="zen.spamhaus.org bl.spamcop.net b.barracudacentral.org"
for BL in $BLACKLISTS; do
RESULT=$(dig +short "$REVERSED.$BL" 2>/dev/null)
if [ -n "$RESULT" ]; then
echo "LISTED on $BL: $RESULT"
fi
done
Backup
Back up mail data regularly. The critical items are:
- User mailboxes:
/home/*/Maildir/ - Postfix configuration:
/etc/postfix/ - Dovecot configuration:
/etc/dovecot/ - DKIM keys:
/etc/opendkim/ - SSL certificates:
/etc/letsencrypt/
# Daily mail backup script
tar czf /var/backups/mail_$(date +%Y%m%d).tar.gz \
/home/*/Maildir/ \
/etc/postfix/ \
/etc/dovecot/ \
/etc/opendkim/ \
--exclude='*.log'
# Rotate: keep 14 days
find /var/backups/ -name "mail_*.tar.gz" -mtime +14 -delete
When Managed Hosting Is the Better Choice
We have walked through a complete mail server setup, and you can see the complexity involved. Let us be honest about when self-hosting email is not the right call:
- Business-critical email — If your livelihood depends on email deliverability (sales, client communication, invoicing), the risk of misconfiguration or blacklisting is significant
- No time for maintenance — Mail servers need regular attention: monitoring logs, managing blacklists, updating software, tuning spam filters
- Large teams — Managing dozens of mailboxes, shared calendars, and contacts is significantly easier with a managed solution
- Compliance requirements — HIPAA, SOC 2, and similar standards require documented processes and audit trails that are complex to implement on a self-managed server
For these scenarios, consider a MassiveGRID Managed Dedicated Server where the infrastructure team handles security patches, monitoring, and incident response. You still get full data sovereignty on your own dedicated hardware, but without the operational burden.
For personal email, small businesses with technical staff, or anyone who values privacy above convenience, a self-hosted mail server on a MassiveGRID VDS is a solid choice. The independent RAM scaling means you can allocate exactly the resources your mail server needs, and the Ceph 3x replicated storage ensures your email data survives hardware failures.
MassiveGRID Ubuntu VPS includes: Ubuntu 24.04 LTS pre-installed · Proxmox HA cluster with automatic failover · Ceph 3x replicated NVMe storage · Independent CPU/RAM/storage scaling · 12 Tbps DDoS protection · 4 global datacenter locations · 100% uptime SLA · 24/7 human support rated 9.5/10
→ Deploy a self-managed VPS — from $1.99/mo
→ Need dedicated resources? — from $8.30/mo
→ Want fully managed hosting? — we handle everything
Advanced Postfix Configuration: Virtual Domains and Aliases
The basic setup above uses system users for mailboxes. For production use with multiple domains or many users, virtual domains and virtual mailboxes are more flexible.
Virtual Alias Maps
Virtual aliases let you create email redirects without creating system users. Create the alias map:
sudo nano /etc/postfix/virtual
# Aliases for yourdomain.com
info@yourdomain.com mailuser@yourdomain.com
sales@yourdomain.com mailuser@yourdomain.com
support@yourdomain.com mailuser@yourdomain.com
abuse@yourdomain.com mailuser@yourdomain.com
postmaster@yourdomain.com mailuser@yourdomain.com
# Catch-all (use cautiously — attracts spam)
# @yourdomain.com mailuser@yourdomain.com
Apply the alias map:
sudo postmap /etc/postfix/virtual
Add to /etc/postfix/main.cf:
virtual_alias_maps = hash:/etc/postfix/virtual
This lets you receive email at info@, sales@, support@ and have it all delivered to a single mailbox. This is sufficient for most personal and small-business use cases.
Hosting Multiple Domains
To handle email for multiple domains on the same server, add them to the virtual domains configuration:
# In /etc/postfix/main.cf
virtual_mailbox_domains = yourdomain.com, seconddomain.com, thirddomain.com
virtual_mailbox_maps = hash:/etc/postfix/vmailbox
virtual_mailbox_base = /var/mail/vhosts
Create the virtual mailbox map:
sudo nano /etc/postfix/vmailbox
user@yourdomain.com yourdomain.com/user/
admin@seconddomain.com seconddomain.com/admin/
info@thirddomain.com thirddomain.com/info/
sudo postmap /etc/postfix/vmailbox
sudo mkdir -p /var/mail/vhosts
sudo chown -R vmail:vmail /var/mail/vhosts
You will also need to create a dedicated vmail user for virtual mailbox ownership:
sudo groupadd -g 5000 vmail
sudo useradd -g vmail -u 5000 -d /var/mail/vhosts -s /usr/sbin/nologin vmail
Remember that each domain needs its own SPF, DKIM, and DMARC DNS records. Generate separate DKIM keys per domain:
sudo opendkim-genkey -b 2048 -s mail -d seconddomain.com -D /etc/opendkim/keys/seconddomain.com/
Update the OpenDKIM KeyTable and SigningTable files accordingly.
Securing Your Mail Server
A mail server is a high-value target for attackers. It accepts connections from the entire internet on ports 25, 587, and 993. Harden it beyond the defaults:
Fail2ban for Mail Services
sudo apt install fail2ban -y
Create a jail configuration for Postfix and Dovecot:
sudo nano /etc/fail2ban/jail.local
[postfix]
enabled = true
port = smtp,465,submission
filter = postfix
logpath = /var/log/mail.log
maxretry = 5
bantime = 3600
findtime = 600
[postfix-sasl]
enabled = true
port = smtp,465,submission
filter = postfix[mode=auth]
logpath = /var/log/mail.log
maxretry = 3
bantime = 7200
findtime = 600
[dovecot]
enabled = true
port = pop3,pop3s,imap,imaps
filter = dovecot
logpath = /var/log/mail.log
maxretry = 5
bantime = 3600
findtime = 600
sudo systemctl enable fail2ban
sudo systemctl restart fail2ban
# Check ban status
sudo fail2ban-client status postfix-sasl
Firewall Rules
sudo ufw allow 25/tcp # SMTP (receiving)
sudo ufw allow 587/tcp # Submission (sending, authenticated)
sudo ufw allow 993/tcp # IMAPS (reading, encrypted)
sudo ufw allow 22/tcp # SSH
sudo ufw allow 80/tcp # HTTP (for Let's Encrypt renewal)
sudo ufw allow 443/tcp # HTTPS (for webmail)
sudo ufw enable
Do not open port 110 (POP3) or 143 (IMAP) unencrypted. Force all client connections through encrypted ports (993 for IMAPS, 587 for submission with STARTTLS).
Disable Open Relay
An open relay allows anyone on the internet to send email through your server. This is the fastest way to get your IP blacklisted. Verify your server is not an open relay:
# Test from an external machine
telnet mail.yourdomain.com 25
EHLO test.com
MAIL FROM:<test@test.com>
RCPT TO:<test@gmail.com>
If Postfix is configured correctly, the RCPT TO command should return 554 Relay access denied for unauthenticated connections to external domains. If it accepts the command, your relay restrictions are misconfigured. Double-check smtpd_recipient_restrictions in main.cf.
Troubleshooting Deliverability Issues
If your emails land in spam at major providers, work through this checklist:
- Check rDNS —
dig -x YOUR_SERVER_IPshould returnmail.yourdomain.com - Verify SPF —
dig TXT yourdomain.comshould show your SPF record - Verify DKIM signing — Send an email to a Gmail address and click “Show original.” Look for
DKIM: PASS - Check DMARC —
dig TXT _dmarc.yourdomain.comshould show your DMARC policy - Blacklist check — Run your IP through MXToolbox Blacklist Check
- Send volume — New mail servers should start with low volume. Send to known contacts first and build reputation gradually
- Content quality — Avoid spam trigger words, include an unsubscribe link in bulk emails, and keep the text-to-HTML ratio balanced
- HELO hostname — Verify Postfix sends
EHLO mail.yourdomain.com, which must match the rDNS record
Gmail and Outlook are the strictest receivers. If your email passes their filters, it will pass everywhere. Google’s Postmaster Tools (free, requires domain verification) provides insight into your domain’s reputation and deliverability trends.
Performance Considerations and Server Sizing
Here is how different components use server resources:
| Component | CPU Impact | RAM Impact | Storage Impact |
|---|---|---|---|
| Postfix (SMTP) | Low | Low (50–100 MB) | Queue storage |
| Dovecot (IMAP) | Low | Medium (per-connection) | Mailbox indexing |
| Rspamd + Redis | Medium (during scanning) | High (500 MB–1 GB) | Classification database |
| OpenDKIM | Minimal | Minimal | Minimal |
| Roundcube (PHP) | Low | Low (per-session) | Minimal |
| Unbound DNS | Minimal | Low (cache) | Minimal |
Sizing recommendations:
| Scenario | Recommended Plan | Specs |
|---|---|---|
| Personal (1–5 users, light volume) | Cloud VPS | 2 vCPU, 2 GB RAM, 40 GB NVMe |
| Small business (5–20 users) | Dedicated VPS | 2 vCPU, 4 GB RAM, 80 GB NVMe |
| Medium business (20–100 users, Rspamd) | Dedicated VPS | 4 vCPU, 8 GB RAM, 200 GB NVMe |
| Large org or MSP | Managed Dedicated | Custom sizing, HA cluster |
The sweet spot for most self-hosted mail deployments is a MassiveGRID Dedicated VPS with 4 GB RAM and 2–4 dedicated CPU cores. The independent scaling means you only pay for the resources you actually use, and you can scale RAM up instantly when you add Rspamd or your user count grows — without overpaying for excess CPU.
Automating Mail Server Health Checks
A mail server that silently fails is worse than no mail server at all. Set up automated health checks to catch issues before your users notice.
Service Monitoring Script
#!/bin/bash
# /usr/local/bin/mail-health-check.sh
# Run via cron every 5 minutes
ALERT_EMAIL="admin@external-provider.com" # Use an EXTERNAL email for alerts
HOSTNAME=$(hostname -f)
ERRORS=""
# Check Postfix
if ! systemctl is-active --quiet postfix; then
ERRORS="$ERRORS\n- Postfix is DOWN"
systemctl restart postfix
fi
# Check Dovecot
if ! systemctl is-active --quiet dovecot; then
ERRORS="$ERRORS\n- Dovecot is DOWN"
systemctl restart dovecot
fi
# Check Rspamd
if ! systemctl is-active --quiet rspamd; then
ERRORS="$ERRORS\n- Rspamd is DOWN"
systemctl restart rspamd
fi
# Check disk space (alert at 85%)
DISK_USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
if [ "$DISK_USAGE" -gt 85 ]; then
ERRORS="$ERRORS\n- Disk usage is at ${DISK_USAGE}%"
fi
# Check mail queue size (alert if > 100 messages)
QUEUE_SIZE=$(postqueue -p | tail -1 | grep -oP '^\d+' || echo 0)
if [ "$QUEUE_SIZE" -gt 100 ]; then
ERRORS="$ERRORS\n- Mail queue has $QUEUE_SIZE messages"
fi
# Check SSL certificate expiry (alert if < 14 days)
CERT_EXPIRY=$(openssl x509 -enddate -noout -in /etc/letsencrypt/live/mail.yourdomain.com/cert.pem | cut -d= -f2)
EXPIRY_EPOCH=$(date -d "$CERT_EXPIRY" +%s)
NOW_EPOCH=$(date +%s)
DAYS_LEFT=$(( (EXPIRY_EPOCH - NOW_EPOCH) / 86400 ))
if [ "$DAYS_LEFT" -lt 14 ]; then
ERRORS="$ERRORS\n- SSL certificate expires in $DAYS_LEFT days"
fi
# Send alert if any errors found
if [ -n "$ERRORS" ]; then
echo -e "Mail server health check failed on $HOSTNAME:\n$ERRORS" | \
mail -s "ALERT: Mail Server Issues on $HOSTNAME" "$ALERT_EMAIL"
fi
Schedule it with cron:
sudo crontab -e
# Add: */5 * * * * /usr/local/bin/mail-health-check.sh >> /var/log/mail-health.log 2>&1
Important: Send alert emails through an external provider (not through the mail server you are monitoring). If your mail server is down, it cannot send you an alert about being down. Use a separate SMTP relay for monitoring alerts, or use a webhook-based notification system like a Slack or Discord integration.
Log Rotation
Mail logs grow fast on an active server. Ensure logrotate is configured properly:
sudo nano /etc/logrotate.d/mail
/var/log/mail.log
/var/log/mail.err
/var/log/mail.warn
{
daily
rotate 30
compress
delaycompress
missingok
notifempty
create 640 syslog adm
postrotate
/usr/lib/rsyslog/rsyslog-rotate
endscript
}
Keep 30 days of logs for troubleshooting. For compliance requirements, archive older logs to external storage.
Summary
Setting up a self-hosted mail server is a substantial project, but the result is complete ownership of your email infrastructure. The key components are Postfix for SMTP, Dovecot for IMAP, OpenDKIM for message signing, and Rspamd for spam filtering. The DNS configuration — SPF, DKIM, DMARC, and rDNS — is what determines whether your emails reach inboxes or spam folders.
Start with a MassiveGRID Cloud VPS for personal email. Graduate to a Dedicated VPS when you add spam filtering or serve more than a handful of users — the independent RAM scaling is a perfect match for mail server workloads. And if the operational overhead of running a mail server is more than you want to take on, Managed Dedicated hosting gives you the same data sovereignty with none of the maintenance burden.