๐ง AlmaLinux Email Server with Postfix Complete Setup Guide
Ready to create your own professional email server on AlmaLinux? ๐ Whether youโre setting up email for your business, organization, or personal use, this comprehensive guide will help you build a secure, reliable, and fully-featured email server using Postfix and Dovecot! โจ
Running your own email server gives you complete control over your communications, enhanced privacy, and the satisfaction of managing your own digital infrastructure! ๐ฌ
๐ค Why Set Up Your Own Email Server?
Building your email server on AlmaLinux brings incredible advantages! ๐
Essential Benefits:
- ๐ Complete Privacy Control - Your emails stay on your server
- ๐ฐ Cost Effective - No monthly fees for unlimited mailboxes
- ๐ก๏ธ Enhanced Security - Custom security policies and encryption
- ๐ Unlimited Storage - Only limited by your server capacity
- ๐ฏ Custom Domains - Professional email addresses with your domain
- ๐ง Full Configuration Control - Customize every aspect
- ๐ Detailed Logging - Complete visibility into email operations
- ๐ Multiple Domain Support - Host email for multiple domains
- ๐ซ No Vendor Lock-in - Full ownership of your email infrastructure
๐ฏ What You Need Before Starting
Letโs make sure youโre ready for this email server adventure! โ
System Requirements:
- โ AlmaLinux 8 or 9 (fresh installation recommended)
- โ Minimum 2GB RAM (4GB+ recommended)
- โ 50GB+ storage space for emails
- โ Static public IP address (essential!)
- โ Domain name with DNS control access
- โ Port 25 access from your ISP (check first!)
- โ Basic DNS and networking knowledge
DNS Prerequisites:
- โ A record pointing to your server IP
- โ MX record pointing to your mail server
- โ PTR record (reverse DNS) configured
- โ SPF, DKIM, and DMARC records (weโll set up)
What Weโll Install:
- โ Postfix - SMTP server for sending/receiving emails
- โ Dovecot - IMAP/POP3 server for email retrieval
- โ SpamAssassin - Spam filtering system
- โ ClamAV - Antivirus scanning for emails
- โ OpenDKIM - Domain key signing
- โ Fail2Ban - Brute force protection
- โ SSL/TLS certificates for encryption
๐ Step 1: System Preparation and Initial Configuration
Letโs start by preparing our AlmaLinux system for email server operations!
# Update the system first
sudo dnf update -y
# Set proper hostname (replace with your mail server domain)
sudo hostnamectl set-hostname mail.yourdomain.com
sudo hostnamectl set-hostname --transient mail.yourdomain.com
sudo hostnamectl set-hostname --static mail.yourdomain.com
# Verify hostname
hostnamectl status
Configure System Timezone:
# Set timezone (adjust for your location)
sudo timedatectl set-timezone UTC
sudo timedatectl set-ntp true
# Verify time configuration
timedatectl status
date
Essential Packages Installation:
# Install required packages
sudo dnf install -y \
postfix \
dovecot \
dovecot-mysql \
dovecot-pigeonhole \
mysql-server \
php \
php-mysql \
php-imap \
httpd \
certbot \
python3-certbot-apache \
spamassassin \
clamav \
clamav-update \
opendkim \
opendkim-tools \
bind-utils \
telnet \
nc \
fail2ban \
rsyslog
Firewall Configuration:
# Configure firewall for email services
sudo firewall-cmd --permanent --add-service=smtp # Port 25
sudo firewall-cmd --permanent --add-service=smtps # Port 465
sudo firewall-cmd --permanent --add-service=submission # Port 587
sudo firewall-cmd --permanent --add-service=imap # Port 143
sudo firewall-cmd --permanent --add-service=imaps # Port 993
sudo firewall-cmd --permanent --add-service=pop3 # Port 110
sudo firewall-cmd --permanent --add-service=pop3s # Port 995
sudo firewall-cmd --permanent --add-service=http # Port 80
sudo firewall-cmd --permanent --add-service=https # Port 443
# Reload firewall rules
sudo firewall-cmd --reload
# Verify open ports
sudo firewall-cmd --list-all
๐ง Step 2: MySQL Database Setup for Virtual Users
Weโll use MySQL to store virtual users and domains, making management much easier!
# Start and enable MySQL
sudo systemctl enable mysqld
sudo systemctl start mysqld
# Secure MySQL installation
sudo mysql_secure_installation
Create Mail Database and User:
# Connect to MySQL as root
sudo mysql -u root -p
# In MySQL console, create database and user
```sql
CREATE DATABASE mailserver;
CREATE USER 'mailuser'@'localhost' IDENTIFIED BY 'secure_mail_password_here';
GRANT ALL PRIVILEGES ON mailserver.* TO 'mailuser'@'localhost';
FLUSH PRIVILEGES;
USE mailserver;
-- Create virtual domains table
CREATE TABLE virtual_domains (
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL UNIQUE
);
-- Create virtual users table
CREATE TABLE virtual_users (
id INT(11) PRIMARY KEY AUTO_INCREMENT,
domain_id INT(11) NOT NULL,
email VARCHAR(120) NOT NULL UNIQUE,
password VARCHAR(106) NOT NULL,
FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
);
-- Create virtual aliases table
CREATE TABLE virtual_aliases (
id INT(11) PRIMARY KEY AUTO_INCREMENT,
domain_id INT(11) NOT NULL,
source VARCHAR(100) NOT NULL,
destination VARCHAR(100) NOT NULL,
FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
);
-- Add your domain (replace yourdomain.com)
INSERT INTO virtual_domains (name) VALUES ('yourdomain.com');
-- Create test user account (replace with your info)
INSERT INTO virtual_users (domain_id, email, password)
VALUES (1, '[email protected]', ENCRYPT('your_password_here', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))));
-- Verify data
SELECT * FROM virtual_domains;
SELECT * FROM virtual_users;
EXIT;
Test Database Connection:
# Test MySQL connection for Postfix
mysql -u mailuser -p mailserver -e "SELECT email FROM virtual_users;"
๐ Step 3: Postfix Configuration for SMTP
Now letโs configure Postfix as our SMTP server for sending and receiving emails!
# Backup original Postfix configuration
sudo cp /etc/postfix/main.cf /etc/postfix/main.cf.backup
sudo cp /etc/postfix/master.cf /etc/postfix/master.cf.backup
Configure Main Postfix Settings:
# Create optimized main.cf configuration
sudo tee /etc/postfix/main.cf << 'EOF'
# Basic Configuration
myhostname = mail.yourdomain.com
mydomain = yourdomain.com
myorigin = $mydomain
inet_interfaces = all
inet_protocols = all
mydestination = localhost
# Network and Connection Settings
mynetworks = 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
message_size_limit = 52428800
mailbox_size_limit = 0
# Virtual Domain Configuration
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf
virtual_transport = lmtp:unix:private/dovecot-lmtp
# TLS Configuration
smtp_tls_security_level = may
smtpd_tls_security_level = may
smtpd_tls_cert_file = /etc/ssl/certs/mail.yourdomain.com.pem
smtpd_tls_key_file = /etc/ssl/private/mail.yourdomain.com.key
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_tls_protocols = !SSLv2, !SSLv3
smtp_tls_protocols = !SSLv2, !SSLv3
smtpd_tls_ciphers = high
smtp_tls_ciphers = high
# SASL Authentication
smtpd_sasl_auth_enable = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_authenticated_header = yes
# Client Restrictions
smtpd_client_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_rbl_client zen.spamhaus.org,
reject_rbl_client bl.spamcop.net,
permit
# Helo Restrictions
smtpd_helo_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_invalid_helo_hostname,
reject_non_fqdn_helo_hostname,
permit
# Sender Restrictions
smtpd_sender_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_non_fqdn_sender,
reject_unknown_sender_domain,
permit
# Recipient Restrictions
smtpd_recipient_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_non_fqdn_recipient,
reject_unknown_recipient_domain,
reject_unauth_destination,
permit
# Data Restrictions
smtpd_data_restrictions = reject_unauth_pipelining
# Other Settings
disable_vrfy_command = yes
strict_rfc821_envelopes = yes
smtpd_delay_reject = yes
smtpd_helo_required = yes
EOF
Create MySQL Configuration Files:
# Virtual domains configuration
sudo tee /etc/postfix/mysql-virtual-mailbox-domains.cf << 'EOF'
user = mailuser
password = secure_mail_password_here
hosts = localhost
dbname = mailserver
query = SELECT 1 FROM virtual_domains WHERE name='%s'
EOF
# Virtual mailbox maps configuration
sudo tee /etc/postfix/mysql-virtual-mailbox-maps.cf << 'EOF'
user = mailuser
password = secure_mail_password_here
hosts = localhost
dbname = mailserver
query = SELECT 1 FROM virtual_users WHERE email='%s'
EOF
# Virtual alias maps configuration
sudo tee /etc/postfix/mysql-virtual-alias-maps.cf << 'EOF'
user = mailuser
password = secure_mail_password_here
hosts = localhost
dbname = mailserver
query = SELECT destination FROM virtual_aliases WHERE source='%s'
EOF
# Secure the configuration files
sudo chmod 600 /etc/postfix/mysql-virtual-*.cf
sudo chown root:postfix /etc/postfix/mysql-virtual-*.cf
Configure Master.cf for Submission:
# Add submission and smtps services to master.cf
sudo tee -a /etc/postfix/master.cf << 'EOF'
# Submission port 587
submission inet n - y - - smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_security_level=encrypt
-o smtpd_sasl_auth_enable=yes
-o smtpd_sasl_type=dovecot
-o smtpd_sasl_path=private/auth
-o smtpd_sasl_security_options=noanonymous
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
-o smtpd_sender_restrictions=reject_sender_login_mismatch
-o smtpd_recipient_restrictions=reject_non_fqdn_recipient,reject_unknown_recipient_domain,permit_sasl_authenticated,reject
# SMTPS port 465
smtps inet n - y - - smtpd
-o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
-o smtpd_sasl_type=dovecot
-o smtpd_sasl_path=private/auth
-o smtpd_sasl_security_options=noanonymous
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
-o smtpd_sender_restrictions=reject_sender_login_mismatch
-o smtpd_recipient_restrictions=reject_non_fqdn_recipient,reject_unknown_recipient_domain,permit_sasl_authenticated,reject
EOF
โ Step 4: Dovecot Configuration for IMAP/POP3
Dovecot handles email retrieval and user authentication. Letโs configure it properly!
# Backup Dovecot configuration
sudo cp -r /etc/dovecot /etc/dovecot.backup
Configure Dovecot Main Settings:
# Edit main dovecot configuration
sudo tee /etc/dovecot/dovecot.conf << 'EOF'
# Basic Configuration
protocols = imap pop3 lmtp
listen = *
base_dir = /var/run/dovecot/
instance_name = dovecot
# Logging
log_path = /var/log/dovecot.log
info_log_path = /var/log/dovecot-info.log
debug_log_path = /var/log/dovecot-debug.log
syslog_facility = mail
auth_verbose = yes
auth_verbose_passwords = no
auth_debug = no
mail_debug = no
# SSL Configuration
ssl = required
ssl_cert = </etc/ssl/certs/mail.yourdomain.com.pem
ssl_key = </etc/ssl/private/mail.yourdomain.com.key
ssl_protocols = !SSLv2 !SSLv3
ssl_cipher_list = ECDHE+AESGCM:DH+AESGCM:ECDHE+AES:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
ssl_prefer_server_ciphers = yes
# Mail Location
mail_location = maildir:/var/mail/vhosts/%d/%n/
mail_privileged_group = mail
first_valid_uid = 1000
last_valid_uid = 1000
# Authentication
disable_plaintext_auth = yes
auth_mechanisms = plain login
# Include other configurations
!include conf.d/*.conf
EOF
Configure Dovecot Authentication:
# Configure auth-sql.conf.ext
sudo tee /etc/dovecot/conf.d/auth-sql.conf.ext << 'EOF'
passdb {
driver = sql
args = /etc/dovecot/dovecot-sql.conf.ext
}
userdb {
driver = static
args = uid=vmail gid=vmail home=/var/mail/vhosts/%d/%n
}
EOF
# Create SQL configuration for Dovecot
sudo tee /etc/dovecot/dovecot-sql.conf.ext << 'EOF'
driver = mysql
connect = host=localhost dbname=mailserver user=mailuser password=secure_mail_password_here
default_pass_scheme = SHA512-CRYPT
password_query = SELECT email as user, password FROM virtual_users WHERE email='%u';
EOF
# Secure the SQL configuration
sudo chmod 600 /etc/dovecot/dovecot-sql.conf.ext
sudo chown dovecot:dovecot /etc/dovecot/dovecot-sql.conf.ext
Configure Mail Storage:
# Create vmail user for mail storage
sudo groupadd -g 5000 vmail
sudo useradd -g vmail -u 5000 vmail -d /var/mail/vhosts
# Create mail directories
sudo mkdir -p /var/mail/vhosts/yourdomain.com
sudo chown -R vmail:vmail /var/mail/vhosts
sudo chmod -R 750 /var/mail/vhosts
Configure LMTP Service:
# Configure LMTP in 10-master.conf
sudo tee /etc/dovecot/conf.d/10-master.conf << 'EOF'
service imap-login {
inet_listener imap {
port = 143
}
inet_listener imaps {
port = 993
ssl = yes
}
}
service pop3-login {
inet_listener pop3 {
port = 110
}
inet_listener pop3s {
port = 995
ssl = yes
}
}
service lmtp {
unix_listener /var/spool/postfix/private/dovecot-lmtp {
mode = 0600
user = postfix
group = postfix
}
}
service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0666
user = postfix
group = postfix
}
unix_listener auth-userdb {
mode = 0600
user = vmail
group = vmail
}
}
service auth-worker {
user = vmail
}
EOF
๐ Step 5: SSL/TLS Certificate Setup with Letโs Encrypt
Security is crucial for email servers! Letโs get free SSL certificates.
# Stop any conflicting services
sudo systemctl stop httpd
# Get SSL certificate for your mail server
sudo certbot certonly --standalone -d mail.yourdomain.com
# Copy certificates to appropriate locations
sudo mkdir -p /etc/ssl/certs /etc/ssl/private
sudo cp /etc/letsencrypt/live/mail.yourdomain.com/fullchain.pem /etc/ssl/certs/mail.yourdomain.com.pem
sudo cp /etc/letsencrypt/live/mail.yourdomain.com/privkey.pem /etc/ssl/private/mail.yourdomain.com.key
# Set proper permissions
sudo chmod 644 /etc/ssl/certs/mail.yourdomain.com.pem
sudo chmod 600 /etc/ssl/private/mail.yourdomain.com.key
sudo chown root:root /etc/ssl/certs/mail.yourdomain.com.pem
sudo chown root:root /etc/ssl/private/mail.yourdomain.com.key
Auto-renewal Setup:
# Create certificate renewal script
sudo tee /usr/local/bin/renew-mail-certs.sh << 'EOF'
#!/bin/bash
# Renew Let's Encrypt certificates and restart mail services
certbot renew --quiet
# Copy new certificates
cp /etc/letsencrypt/live/mail.yourdomain.com/fullchain.pem /etc/ssl/certs/mail.yourdomain.com.pem
cp /etc/letsencrypt/live/mail.yourdomain.com/privkey.pem /etc/ssl/private/mail.yourdomain.com.key
# Set permissions
chmod 644 /etc/ssl/certs/mail.yourdomain.com.pem
chmod 600 /etc/ssl/private/mail.yourdomain.com.key
# Restart services
systemctl restart postfix dovecot
echo "SSL certificates renewed and services restarted"
EOF
sudo chmod +x /usr/local/bin/renew-mail-certs.sh
# Add to crontab for automatic renewal
echo "0 3 * * 0 /usr/local/bin/renew-mail-certs.sh" | sudo crontab -
๐ก๏ธ Step 6: Spam Protection with SpamAssassin
Letโs add powerful spam filtering to protect your users!
# Update SpamAssassin rules
sudo sa-update
# Configure SpamAssassin
sudo tee /etc/mail/spamassassin/local.cf << 'EOF'
# Local SpamAssassin Configuration
# Required score for spam classification
required_score 4.0
# Network tests
skip_rbl_checks 0
use_razor2 1
use_pyzor 1
use_dcc 1
# Bayesian filter settings
use_bayes 1
bayes_auto_learn 1
bayes_auto_learn_threshold_nonspam 0.1
bayes_auto_learn_threshold_spam 12.0
# Custom rules
header CUSTOM_SPAM_HEADER X-Spam-Status =~ /^Yes/
score CUSTOM_SPAM_HEADER 2.0
# Whitelist
whitelist_from *@yourdomain.com
# Report settings
report_safe 0
rewrite_header Subject [SPAM]
EOF
# Enable and start SpamAssassin
sudo systemctl enable spamassassin
sudo systemctl start spamassassin
# Configure Postfix to use SpamAssassin
echo "spamassassin unix - n n - - pipe
user=spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f \${sender} \${recipient}" | sudo tee -a /etc/postfix/master.cf
Integrate SpamAssassin with Postfix:
# Add content filter to main.cf
echo "content_filter = spamassassin" | sudo tee -a /etc/postfix/main.cf
๐ฆ Step 7: Antivirus Protection with ClamAV
Add virus scanning to keep your email system safe!
# Update ClamAV database
sudo freshclam
# Configure ClamAV
sudo tee /etc/clamd.d/scan.conf << 'EOF'
# ClamAV Configuration
LocalSocket /var/run/clamd.scan/clamd.sock
User clamscan
PidFile /var/run/clamd.scan/clamd.pid
DatabaseDirectory /var/lib/clamav
LogFile /var/log/clamd.scan
LogVerbose yes
ScanMail yes
ScanArchive yes
ArchiveBlockEncrypted no
MaxScanSize 100M
MaxFileSize 25M
MaxRecursion 16
MaxFiles 10000
MaxPartitions 50
MaxIconsPE 100
EOF
# Enable and start ClamAV services
sudo systemctl enable clamav-freshclam
sudo systemctl enable clamd@scan
sudo systemctl start clamav-freshclam
sudo systemctl start clamd@scan
# Create ClamAV integration script
sudo tee /usr/local/bin/clamscan-postfix.sh << 'EOF'
#!/bin/bash
# ClamAV integration with Postfix
SENDMAIL="/usr/sbin/sendmail -i"
cd /tmp
cat > mail.tmp
clamdscan --stdout --no-summary mail.tmp
if [ $? -eq 0 ]; then
# Clean email - deliver normally
$SENDMAIL "$@" < mail.tmp
else
# Infected email - reject
echo "Message rejected: Virus detected"
exit 1
fi
rm -f mail.tmp
EOF
sudo chmod +x /usr/local/bin/clamscan-postfix.sh
๐ Step 8: DKIM Signing with OpenDKIM
DKIM helps prevent email spoofing and improves deliverability!
# Configure OpenDKIM
sudo tee /etc/opendkim.conf << 'EOF'
# OpenDKIM Configuration
PidFile /var/run/opendkim/opendkim.pid
Mode sv
Syslog yes
SyslogSuccess yes
LogWhy yes
UserID opendkim:opendkim
Socket inet:12301@localhost
Umask 002
SendReports yes
SoftwareHeader yes
Canonicalization relaxed/simple
Selector default
MinimumKeyBits 1024
KeyTable /etc/opendkim/KeyTable
SigningTable /etc/opendkim/SigningTable
ExternalIgnoreList /etc/opendkim/TrustedHosts
InternalHosts /etc/opendkim/TrustedHosts
EOF
# Create OpenDKIM directories
sudo mkdir -p /etc/opendkim/keys/yourdomain.com
# Generate DKIM keys
sudo opendkim-genkey -T -r -s default -d yourdomain.com -D /etc/opendkim/keys/yourdomain.com/
# Create configuration files
sudo tee /etc/opendkim/KeyTable << 'EOF'
default._domainkey.yourdomain.com yourdomain.com:default:/etc/opendkim/keys/yourdomain.com/default.private
EOF
sudo tee /etc/opendkim/SigningTable << 'EOF'
*@yourdomain.com default._domainkey.yourdomain.com
EOF
sudo tee /etc/opendkim/TrustedHosts << 'EOF'
127.0.0.1
localhost
192.168.0.0/16
*.yourdomain.com
EOF
# Set proper permissions
sudo chown -R opendkim:opendkim /etc/opendkim
sudo chmod 600 /etc/opendkim/keys/yourdomain.com/default.private
# Enable and start OpenDKIM
sudo systemctl enable opendkim
sudo systemctl start opendkim
# Configure Postfix to use OpenDKIM
echo "
# OpenDKIM Integration
milter_protocol = 2
milter_default_action = accept
smtpd_milters = inet:localhost:12301
non_smtpd_milters = inet:localhost:12301" | sudo tee -a /etc/postfix/main.cf
Display DKIM Public Key for DNS:
# Show DKIM public key for DNS record
echo "Add this TXT record to your DNS:"
echo "Name: default._domainkey"
echo "Value:"
sudo cat /etc/opendkim/keys/yourdomain.com/default.txt
๐จ Step 9: Security Hardening with Fail2Ban
Protect your mail server from brute force attacks!
# Configure Fail2Ban for mail services
sudo tee /etc/fail2ban/jail.d/mail.conf << 'EOF'
[postfix]
enabled = true
port = smtp,465,submission
filter = postfix
logpath = /var/log/maillog
maxretry = 5
bantime = 3600
[dovecot]
enabled = true
port = pop3,pop3s,imap,imaps,submission,465,sieve
filter = dovecot
logpath = /var/log/dovecot.log
maxretry = 5
bantime = 3600
[postfix-sasl]
enabled = true
port = smtp,465,submission,imap,imaps,pop3,pop3s
filter = postfix-sasl
logpath = /var/log/maillog
maxretry = 3
bantime = 3600
EOF
# Create custom filters
sudo tee /etc/fail2ban/filter.d/postfix-sasl.conf << 'EOF'
[Definition]
failregex = (?i): warning: [-.\w]+\[<HOST>\]: SASL (?:LOGIN|PLAIN|(?:CRAM|DIGEST)-MD5) authentication failed
ignoreregex =
EOF
# Enable and start Fail2Ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
# Check Fail2Ban status
sudo fail2ban-client status
โ Step 10: Start and Test Email Services
Time to bring everything together and test our email server!
# Start all email services
sudo systemctl enable postfix dovecot mysql
sudo systemctl start postfix dovecot mysql
# Check service status
sudo systemctl status postfix
sudo systemctl status dovecot
sudo systemctl status mysql
# Test Postfix configuration
sudo postfix check
# Test Dovecot configuration
sudo doveconf -n
# Check listening ports
sudo netstat -tlnp | grep -E '(25|465|587|110|143|993|995)'
Test SMTP Connection:
# Test SMTP without authentication
telnet localhost 25
# In telnet session:
# EHLO localhost
# MAIL FROM: test@localhost
# RCPT TO: [email protected]
# DATA
# Subject: Test Email
#
# This is a test email.
# .
# QUIT
# Test SMTP with encryption
openssl s_client -connect localhost:465 -quiet
# Then use same SMTP commands as above
Test IMAP Connection:
# Test IMAP without SSL
telnet localhost 143
# In telnet session:
# a1 LOGIN [email protected] your_password_here
# a2 LIST "" "*"
# a3 SELECT INBOX
# a4 LOGOUT
# Test IMAP with SSL
openssl s_client -connect localhost:993 -quiet
# Then use same IMAP commands as above
๐ฎ Quick Examples - Email Management Operations
Letโs create some practical examples for managing your email server! ๐
Example 1: Add New Email User
# Create script to add new email users
cat > ~/add-email-user.sh << 'EOF'
#!/bin/bash
# Script to add new email user
if [ $# -ne 3 ]; then
echo "Usage: $0 <email> <password> <domain>"
echo "Example: $0 [email protected] secretpass yourdomain.com"
exit 1
fi
EMAIL=$1
PASSWORD=$2
DOMAIN=$3
# Check if domain exists
DOMAIN_ID=$(mysql -u mailuser -psecure_mail_password_here mailserver -sN -e "SELECT id FROM virtual_domains WHERE name='$DOMAIN'")
if [ -z "$DOMAIN_ID" ]; then
echo "โ Domain $DOMAIN not found. Adding it first..."
mysql -u mailuser -psecure_mail_password_here mailserver -e "INSERT INTO virtual_domains (name) VALUES ('$DOMAIN')"
DOMAIN_ID=$(mysql -u mailuser -psecure_mail_password_here mailserver -sN -e "SELECT id FROM virtual_domains WHERE name='$DOMAIN'")
fi
# Add user
ENCRYPTED_PASSWORD=$(doveadm pw -s SHA512-CRYPT -p "$PASSWORD")
mysql -u mailuser -psecure_mail_password_here mailserver -e "INSERT INTO virtual_users (domain_id, email, password) VALUES ($DOMAIN_ID, '$EMAIL', '$ENCRYPTED_PASSWORD')"
if [ $? -eq 0 ]; then
echo "โ
User $EMAIL created successfully!"
# Create mailbox directory
sudo mkdir -p /var/mail/vhosts/$DOMAIN/${EMAIL%@*}
sudo chown vmail:vmail /var/mail/vhosts/$DOMAIN/${EMAIL%@*}
echo "๐ง User can now login with:"
echo " Email: $EMAIL"
echo " IMAP Server: mail.$DOMAIN (port 993, SSL)"
echo " SMTP Server: mail.$DOMAIN (port 587, STARTTLS)"
else
echo "โ Failed to create user $EMAIL"
fi
EOF
chmod +x ~/add-email-user.sh
# Example usage:
# ./add-email-user.sh [email protected] mypassword yourdomain.com
Example 2: Email Statistics Dashboard
# Create email statistics script
cat > ~/mail-stats.sh << 'EOF'
#!/bin/bash
# Email Server Statistics Dashboard
echo "๐ Email Server Statistics"
echo "=========================="
echo -e "\n๐ฅ User Statistics:"
TOTAL_USERS=$(mysql -u mailuser -psecure_mail_password_here mailserver -sN -e "SELECT COUNT(*) FROM virtual_users")
TOTAL_DOMAINS=$(mysql -u mailuser -psecure_mail_password_here mailserver -sN -e "SELECT COUNT(*) FROM virtual_domains")
echo "Total Users: $TOTAL_USERS"
echo "Total Domains: $TOTAL_DOMAINS"
echo -e "\n๐ฌ Mail Queue:"
QUEUE_SIZE=$(postqueue -p | tail -n1 | grep -o '[0-9]*' | head -1)
echo "Messages in queue: ${QUEUE_SIZE:-0}"
echo -e "\n๐ Service Status:"
services=("postfix" "dovecot" "opendkim" "spamassassin" "clamd@scan")
for service in "${services[@]}"; do
if systemctl is-active --quiet $service; then
echo "โ
$service: Running"
else
echo "โ $service: Stopped"
fi
done
echo -e "\n๐ Connection Statistics:"
SMTP_CONNECTIONS=$(ss -tuln | grep -c ":25 ")
IMAP_CONNECTIONS=$(ss -tuln | grep -c ":143\|:993")
echo "SMTP listeners: $SMTP_CONNECTIONS"
echo "IMAP listeners: $IMAP_CONNECTIONS"
echo -e "\n๐๏ธ Disk Usage:"
MAIL_SIZE=$(du -sh /var/mail/vhosts 2>/dev/null | cut -f1)
echo "Mail storage: ${MAIL_SIZE:-N/A}"
echo -e "\n๐ Recent Activity (last 100 lines):"
tail -n 100 /var/log/maillog | grep -c "$(date +%b\ %d)"
echo "Log entries today: $(tail -n 1000 /var/log/maillog | grep -c "$(date +%b\ %d)")"
echo -e "\nReport generated: $(date)"
EOF
chmod +x ~/mail-stats.sh
Example 3: Backup Email Data
# Create comprehensive backup script
cat > ~/backup-mail-server.sh << 'EOF'
#!/bin/bash
# Complete Mail Server Backup Script
BACKUP_DIR="/backup/mail-$(date +%Y%m%d)"
mkdir -p "$BACKUP_DIR"
echo "๐ Starting mail server backup..."
# Backup MySQL database
echo "๐ Backing up mail database..."
mysqldump -u mailuser -psecure_mail_password_here mailserver > "$BACKUP_DIR/mailserver.sql"
# Backup mail data
echo "๐ง Backing up mail data..."
tar -czf "$BACKUP_DIR/mail-data.tar.gz" -C /var/mail/vhosts .
# Backup configuration files
echo "โ๏ธ Backing up configurations..."
mkdir -p "$BACKUP_DIR/config"
cp -r /etc/postfix "$BACKUP_DIR/config/"
cp -r /etc/dovecot "$BACKUP_DIR/config/"
cp -r /etc/opendkim "$BACKUP_DIR/config/"
cp /etc/mail/spamassassin/local.cf "$BACKUP_DIR/config/"
# Backup SSL certificates
echo "๐ Backing up SSL certificates..."
mkdir -p "$BACKUP_DIR/ssl"
cp -r /etc/letsencrypt "$BACKUP_DIR/ssl/"
# Create restore script
cat > "$BACKUP_DIR/restore.sh" << 'RESTORE_EOF'
#!/bin/bash
echo "๐ Restoring mail server from backup..."
echo "โ ๏ธ This will overwrite existing configuration!"
read -p "Continue? (y/N): " -n 1 -r
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
exit 1
fi
# Restore database
mysql -u root -p < mailserver.sql
# Restore mail data
tar -xzf mail-data.tar.gz -C /var/mail/vhosts/
# Restore configurations
cp -r config/postfix/* /etc/postfix/
cp -r config/dovecot/* /etc/dovecot/
cp -r config/opendkim/* /etc/opendkim/
cp config/local.cf /etc/mail/spamassassin/
# Restore SSL
cp -r ssl/letsencrypt/* /etc/letsencrypt/
# Restart services
systemctl restart postfix dovecot opendkim spamassassin
echo "โ
Restore completed!"
RESTORE_EOF
chmod +x "$BACKUP_DIR/restore.sh"
# Compress backup
tar -czf "$BACKUP_DIR.tar.gz" -C "$(dirname "$BACKUP_DIR")" "$(basename "$BACKUP_DIR")"
rm -rf "$BACKUP_DIR"
echo "โ
Backup completed: $BACKUP_DIR.tar.gz"
echo "๐ก Store this backup in a safe location!"
EOF
chmod +x ~/backup-mail-server.sh
๐จ Fix Common Email Server Problems
Even email experts face challenges! Here are solutions to common issues: ๐ช
Problem 1: Emails Going to Spam Folder
# Symptoms: Emails sent from server end up in recipient's spam folder
# Solution: Improve email reputation and authentication
# Check SPF record
dig TXT yourdomain.com | grep -i spf
# Should contain: "v=spf1 mx a ip4:YOUR_SERVER_IP -all"
# Check DKIM record
dig TXT default._domainkey.yourdomain.com
# Should show your DKIM public key
# Check reverse DNS (PTR record)
dig -x YOUR_SERVER_IP
# Should return mail.yourdomain.com
# Test email reputation
echo "Subject: Test Email
From: [email protected]
To: [email protected]
This is a test email to check authentication." | sendmail [email protected]
# Check postfix logs for delivery issues
sudo tail -f /var/log/maillog | grep -i "reject\|warn"
Problem 2: Cannot Receive External Emails
# Symptoms: External emails not arriving at server
# Solution: Check DNS, firewall, and service configuration
# Verify MX record
dig MX yourdomain.com
# Should point to mail.yourdomain.com
# Check if port 25 is open and listening
sudo netstat -tlnp | grep :25
sudo telnet localhost 25
# Test external SMTP connectivity
telnet mail.yourdomain.com 25
# Check firewall rules
sudo firewall-cmd --list-all | grep smtp
# Verify Postfix is accepting external connections
sudo postconf inet_interfaces
# Should show: inet_interfaces = all
# Check for ISP port 25 blocking
nmap -p 25 mail.yourdomain.com
Problem 3: Authentication Failures
# Symptoms: Users cannot authenticate with email client
# Solution: Check Dovecot authentication and SSL configuration
# Test authentication manually
doveadm auth test [email protected] your_password
# Check SSL certificate validity
openssl s_client -connect localhost:993 -servername mail.yourdomain.com
# Verify user exists in database
mysql -u mailuser -psecure_mail_password_here mailserver -e "SELECT email FROM virtual_users WHERE email='[email protected]'"
# Check Dovecot logs
sudo tail -f /var/log/dovecot.log
# Test password hash
doveadm pw -s SHA512-CRYPT -p "your_test_password"
Problem 4: High Server Load from Spam
# Symptoms: Server performance degraded due to spam processing
# Solution: Implement rate limiting and enhanced filtering
# Add rate limiting to Postfix
echo "
# Rate Limiting
smtpd_client_connection_count_limit = 10
smtpd_client_connection_rate_limit = 30
smtpd_client_recipient_rate_limit = 100
smtpd_client_message_rate_limit = 100" | sudo tee -a /etc/postfix/main.cf
# Configure more aggressive SpamAssassin settings
sudo sed -i 's/required_score 4.0/required_score 3.0/' /etc/mail/spamassassin/local.cf
# Add greylisting
sudo dnf install -y postgrey
echo "check_policy_service inet:127.0.0.1:10023" | sudo tee -a /etc/postfix/main.cf
# Monitor connection attempts
sudo tail -f /var/log/maillog | grep "reject\|warning"
# Block suspicious IPs
sudo fail2ban-client status postfix
sudo fail2ban-client set postfix banip SUSPICIOUS_IP
Problem 5: Disk Space Issues
# Symptoms: Server running out of disk space
# Solution: Implement log rotation and mailbox quotas
# Set up log rotation
sudo tee /etc/logrotate.d/mail << 'EOF'
/var/log/maillog {
daily
rotate 30
compress
delaycompress
missingok
notifempty
postrotate
systemctl reload rsyslog
endscript
}
EOF
# Configure mailbox quotas in Dovecot
echo "
# Quota Configuration
mail_plugins = \$mail_plugins quota
quota = maildir:User quota
quota_rule = *:storage=1GB
quota_rule2 = Trash:storage=+100MB
quota_warning = storage=95%% quota-warning 95 %u
quota_warning2 = storage=80%% quota-warning 80 %u" | sudo tee -a /etc/dovecot/conf.d/90-quota.conf
# Clean old logs
sudo find /var/log -name "*.log" -mtime +30 -delete
sudo find /var/mail/vhosts -name ".Trash*" -mtime +30 -exec rm -rf {} +
# Check current disk usage
df -h /var/mail
du -sh /var/mail/vhosts/*
๐ Email Server Commands Summary
Hereโs your quick reference for email server operations! โก
Task | Command | Description |
---|---|---|
Check Mail Queue | postqueue -p | View messages in mail queue |
Flush Mail Queue | postqueue -f | Process all queued messages |
Test SMTP | telnet localhost 25 | Test SMTP connectivity |
Check Services | systemctl status postfix dovecot | Verify service status |
View Mail Logs | tail -f /var/log/maillog | Monitor email activity |
Test User Auth | doveadm auth test [email protected] pass | Verify user authentication |
Check SSL Cert | openssl s_client -connect localhost:993 | Test SSL certificate |
Add Email User | ./add-email-user.sh [email protected] pass | Create new email account |
Database Access | mysql -u mailuser -p mailserver | Access mail database |
Check DKIM | opendkim-testkey -d domain.com -s default | Verify DKIM configuration |
Reload Postfix | sudo systemctl reload postfix | Apply config changes |
Check Quotas | doveadm quota get -u [email protected] | View user mailbox quota |
๐ก Pro Tips for Email Server Excellence
Want to become an email server ninja? Here are expert secrets! ๐ฅท
Tip 1: Advanced Monitoring Setup
# Create comprehensive monitoring script
cat > ~/advanced-mail-monitor.sh << 'EOF'
#!/bin/bash
# Advanced Email Server Monitoring
LOG_FILE="/var/log/mail-monitor.log"
ALERT_EMAIL="[email protected]"
check_services() {
services=("postfix" "dovecot" "mysql" "opendkim" "spamassassin")
for service in "${services[@]}"; do
if ! systemctl is-active --quiet $service; then
echo "$(date): โ $service is down!" | tee -a $LOG_FILE
echo "Service $service is down on $(hostname)" | mail -s "Email Server Alert" $ALERT_EMAIL
systemctl start $service
fi
done
}
check_disk_space() {
USAGE=$(df /var/mail | tail -1 | awk '{print $5}' | sed 's/%//')
if [ $USAGE -gt 85 ]; then
echo "$(date): โ ๏ธ Disk usage at ${USAGE}%" | tee -a $LOG_FILE
echo "Mail server disk usage is at ${USAGE}%" | mail -s "Disk Space Warning" $ALERT_EMAIL
fi
}
check_mail_queue() {
QUEUE_SIZE=$(postqueue -p | tail -n1 | grep -o '[0-9]*' | head -1)
if [ "${QUEUE_SIZE:-0}" -gt 100 ]; then
echo "$(date): โ ๏ธ Large mail queue: $QUEUE_SIZE messages" | tee -a $LOG_FILE
echo "Mail queue has $QUEUE_SIZE messages" | mail -s "Mail Queue Alert" $ALERT_EMAIL
fi
}
check_ssl_expiry() {
EXPIRY=$(openssl x509 -enddate -noout -in /etc/ssl/certs/mail.yourdomain.com.pem | cut -d= -f2)
EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s)
CURRENT_EPOCH=$(date +%s)
DAYS_LEFT=$(( (EXPIRY_EPOCH - CURRENT_EPOCH) / 86400 ))
if [ $DAYS_LEFT -lt 30 ]; then
echo "$(date): โ ๏ธ SSL certificate expires in $DAYS_LEFT days" | tee -a $LOG_FILE
echo "SSL certificate expires in $DAYS_LEFT days" | mail -s "SSL Expiry Warning" $ALERT_EMAIL
fi
}
# Run checks
check_services
check_disk_space
check_mail_queue
check_ssl_expiry
echo "$(date): โ
Monitoring check completed" >> $LOG_FILE
EOF
chmod +x ~/advanced-mail-monitor.sh
# Add to crontab for every 15 minutes
echo "*/15 * * * * /home/$(whoami)/advanced-mail-monitor.sh" | crontab -
Tip 2: Email Performance Optimization
# Create performance optimization script
cat > ~/optimize-mail-server.sh << 'EOF'
#!/bin/bash
echo "๐ Optimizing email server performance..."
# Optimize MySQL for email workload
sudo tee -a /etc/my.cnf.d/mail-optimization.cnf << 'MYSQL_EOF'
[mysqld]
# Email server optimizations
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_method = O_DIRECT
query_cache_type = 1
query_cache_size = 256M
max_connections = 200
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2
MYSQL_EOF
# Optimize Postfix queue processing
echo "
# Performance Tuning
default_process_limit = 100
smtpd_client_connection_count_limit = 50
smtpd_client_connection_rate_limit = 60
qmgr_message_active_limit = 20000
qmgr_message_recipient_limit = 20000
" | sudo tee -a /etc/postfix/main.cf
# Optimize Dovecot performance
echo "
# Performance Settings
mail_cache_min_mail_count = 20
mailbox_idle_check_interval = 30 mins
mail_cache_record_header = yes
" | sudo tee -a /etc/dovecot/conf.d/10-mail.conf
# System-level optimizations
echo "# Email server optimizations
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
vm.swappiness = 10" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
# Restart services to apply optimizations
sudo systemctl restart mysql postfix dovecot
echo "โ
Performance optimizations applied!"
EOF
chmod +x ~/optimize-mail-server.sh
Tip 3: Security Hardening Checklist
# Create security audit and hardening script
cat > ~/harden-mail-server.sh << 'EOF'
#!/bin/bash
echo "๐ก๏ธ Hardening email server security..."
# Disable unnecessary services
services_to_disable=("telnet" "rsh" "rlogin")
for service in "${services_to_disable[@]}"; do
if systemctl is-enabled $service 2>/dev/null; then
sudo systemctl disable $service
echo "โ
Disabled $service"
fi
done
# Secure file permissions
sudo chmod 600 /etc/postfix/mysql-virtual-*.cf
sudo chmod 600 /etc/dovecot/dovecot-sql.conf.ext
sudo chmod 600 /etc/opendkim/keys/*/default.private
echo "โ
Secured configuration file permissions"
# Configure secure SSH (if not already done)
sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sudo systemctl reload sshd
echo "โ
Secured SSH configuration"
# Set up automated security updates
echo "0 2 * * * dnf update -y --security" | sudo crontab -
echo "โ
Configured automated security updates"
# Create intrusion detection
sudo tee /usr/local/bin/check-mail-intrusion.sh << 'INTRUSION_EOF'
#!/bin/bash
# Check for suspicious email activity
# Check for authentication failures
AUTH_FAILS=$(grep "authentication failed" /var/log/dovecot.log | grep "$(date +%b\ %d)" | wc -l)
if [ $AUTH_FAILS -gt 50 ]; then
echo "High authentication failures detected: $AUTH_FAILS" | mail -s "Security Alert" [email protected]
fi
# Check for unusual connection patterns
UNIQUE_IPS=$(grep "connect from" /var/log/maillog | grep "$(date +%b\ %d)" | awk '{print $NF}' | sort -u | wc -l)
if [ $UNIQUE_IPS -gt 100 ]; then
echo "Unusual connection pattern: $UNIQUE_IPS unique IPs today" | mail -s "Security Alert" [email protected]
fi
INTRUSION_EOF
sudo chmod +x /usr/local/bin/check-mail-intrusion.sh
echo "0 */4 * * * /usr/local/bin/check-mail-intrusion.sh" | sudo crontab -
echo "๐ Security hardening completed!"
EOF
chmod +x ~/harden-mail-server.sh
๐ What Youโve Accomplished - Email Server Mastery!
Congratulations! Youโve built a complete, professional-grade email server on AlmaLinux! ๐ Letโs celebrate your incredible achievements:
๐ Complete Email Infrastructure:
- โ Postfix SMTP server with virtual user support
- โ Dovecot IMAP/POP3 server with SSL/TLS encryption
- โ MySQL database for user and domain management
- โ SpamAssassin spam filtering with custom rules
- โ ClamAV antivirus scanning for email security
- โ OpenDKIM domain authentication for deliverability
- โ Letโs Encrypt SSL certificates with auto-renewal
- โ Fail2Ban protection against brute force attacks
- โ Comprehensive logging and monitoring systems
๐ช Professional Skills Gained:
- โ Email server architecture and design
- โ SMTP, IMAP, and POP3 protocol configuration
- โ DNS record management (MX, SPF, DKIM, DMARC)
- โ SSL/TLS certificate management and security
- โ Database-driven virtual user management
- โ Anti-spam and anti-virus implementation
- โ Email authentication and deliverability optimization
- โ Security hardening and intrusion prevention
- โ Performance tuning and monitoring
- โ Backup and disaster recovery procedures
๐ฏ Enterprise-Ready Features:
- โ Multiple domain support for hosting email services
- โ Virtual user management without system accounts
- โ Automated spam and virus protection
- โ Professional email authentication (SPF, DKIM, DMARC)
- โ Encrypted email transmission and storage
- โ Comprehensive monitoring and alerting
- โ Automated backups and maintenance scripts
- โ Performance optimization for high-volume usage
๐ฏ Why This Email Server Setup Matters
Your AlmaLinux email server is now a production-ready, enterprise-grade communication platform! ๐
Real-World Impact:
- ๐ Complete Privacy Control - Your emails never touch third-party servers
- ๐ฐ Significant Cost Savings - No monthly fees for unlimited email accounts
- ๐ก๏ธ Enhanced Security - Military-grade encryption and custom security policies
- ๐ Unlimited Scalability - Add domains and users without restrictions
- ๐ Professional Presence - Custom email addresses enhance business credibility
- ๐ฏ Regulatory Compliance - Meet data privacy requirements with on-premise hosting
- ๐ง Complete Customization - Tailor every aspect to your specific needs
- ๐ Detailed Analytics - Full visibility into email patterns and usage
- ๐ Learning Experience - Deep understanding of email infrastructure
- ๐ผ Career Advancement - Valuable skills for system administration and DevOps
Youโre not just running an email server - youโre operating critical communication infrastructure! Whether youโre supporting a small business, managing enterprise communications, or simply wanting complete control over your digital communications, this AlmaLinux email server provides everything needed for success! ๐
Your emails are now truly yours - secure, private, and professional! โญ Happy emailing! ๐