๐ง AlmaLinux Mail Server Setup: Complete Postfix & Dovecot Guide
Welcome to the comprehensive world of mail server setup on AlmaLinux! ๐ Think of mail servers as the postal system of the digital world - they receive, sort, store, and deliver electronic messages across the internet! Whether youโre setting up email for a small business, managing corporate communications, or learning about email infrastructure, mastering mail server configuration is an incredibly valuable skill! ๐ฎ
Mail servers might seem complex at first, but theyโre actually quite logical and rewarding to work with! ๐ช From sending your first email to implementing advanced spam filtering and security features, weโll learn everything step by step. Get ready to become an email infrastructure expert and take control of your organizationโs communications! โจ
๐ค Why is Mail Server Setup Important?
Mail server setup is crucial for modern communications! Hereโs why you should master it:
- ๐ฌ Complete Control: Own your email infrastructure and data
- ๐ Enhanced Security: Implement advanced security measures and encryption
- ๐ฐ Cost Savings: Reduce dependency on third-party email services
- ๐ Custom Features: Add specialized functionality for your organization
- ๐ก๏ธ Privacy Protection: Keep sensitive communications on your own servers
- ๐ Scalability: Scale email services to match your growing needs
- ๐ฏ Compliance: Meet regulatory requirements for email retention and security
- ๐ Professional Image: Use your own domain for all email communications
๐ฏ What You Need
Before we start setting up mail servers, make sure you have:
โ AlmaLinux 8 or 9 installed and running โ Domain name with proper DNS records (MX, A, PTR) โ Static IP address for reliable mail delivery โ Root or sudo access to install and configure mail server software โ SSL/TLS certificate for secure email communications โ Basic understanding of DNS and email concepts โ Sufficient storage for email data and logs
๐ Understanding Mail Server Components
Letโs start by understanding how mail servers work! ๐
Mail Server Architecture
# Mail server components:
echo "Mail Transfer Agent (MTA) - Postfix:"
echo "- Handles sending and receiving emails"
echo "- SMTP protocol (port 25, 587, 465)"
echo "- Mail routing and delivery"
echo ""
echo "Mail Delivery Agent (MDA) - Dovecot:"
echo "- Stores and retrieves emails"
echo "- IMAP (port 143, 993) and POP3 (port 110, 995)"
echo "- User authentication and mailbox management"
echo ""
echo "Additional components:"
echo "- SpamAssassin: Spam filtering"
echo "- ClamAV: Virus scanning"
echo "- Roundcube: Web-based email client"
# Check if any mail services are running
sudo netstat -tlnp | grep -E ':25|:587|:465|:143|:993|:110|:995'
# Output: Shows if mail ports are in use
DNS Requirements
# Check DNS configuration for mail server
dig MX example.com
dig A mail.example.com
dig PTR your_server_ip
# Required DNS records:
echo "Required DNS records:"
echo "MX record: example.com. IN MX 10 mail.example.com."
echo "A record: mail.example.com. IN A your_server_ip"
echo "PTR record: your_server_ip IN PTR mail.example.com."
echo "SPF record: example.com. IN TXT \"v=spf1 mx ~all\""
# Test DNS resolution
nslookup example.com
host -t MX example.com
# Output: Shows DNS configuration
๐ง Installing Postfix (SMTP Server)
Basic Postfix Installation
# Install Postfix and related packages
sudo dnf install postfix postfix-mysql -y
# Output: Installs Postfix mail server
# Stop and disable sendmail if installed
sudo systemctl stop sendmail
sudo systemctl disable sendmail
# Start and enable Postfix
sudo systemctl start postfix
sudo systemctl enable postfix
# Output: Starts Postfix and enables it at boot
# Check Postfix status
sudo systemctl status postfix
# Output: Shows Postfix service status
# Configure firewall for mail services
sudo firewall-cmd --permanent --add-service=smtp
sudo firewall-cmd --permanent --add-service=smtps
sudo firewall-cmd --permanent --add-service=submission
sudo firewall-cmd --reload
# Output: Opens SMTP ports (25, 465, 587)
# Test Postfix installation
echo "Test email" | mail -s "Test Subject" user@localhost
# Output: Sends test email locally
Basic Postfix Configuration
# Backup original Postfix configuration
sudo cp /etc/postfix/main.cf /etc/postfix/main.cf.backup
# Configure Postfix main settings
sudo nano /etc/postfix/main.cf
# Basic Postfix configuration:
# Network settings
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
inet_protocols = ipv4
# Mail delivery settings
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mynetworks = 127.0.0.0/8, 192.168.1.0/24
home_mailbox = Maildir/
# Security settings
smtpd_banner = $myhostname ESMTP
disable_vrfy_command = yes
smtpd_helo_required = yes
# Basic SMTP restrictions
smtpd_helo_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_invalid_helo_hostname, reject_non_fqdn_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
# Message size limits
message_size_limit = 52428800
mailbox_size_limit = 1073741824
# Test Postfix configuration
sudo postfix check
# Output: Should show no errors
# Reload Postfix configuration
sudo systemctl reload postfix
# Output: Reloads Postfix with new settings
๐ Installing Dovecot (IMAP/POP3 Server)
Dovecot Installation and Setup
# Install Dovecot
sudo dnf install dovecot dovecot-mysql -y
# Output: Installs Dovecot mail server
# Start and enable Dovecot
sudo systemctl start dovecot
sudo systemctl enable dovecot
# Output: Starts Dovecot and enables it at boot
# Check Dovecot status
sudo systemctl status dovecot
# Output: Shows Dovecot service status
# Configure firewall for IMAP/POP3
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
# Output: Opens IMAP/POP3 ports (143, 993, 110, 995)
# Backup Dovecot configuration
sudo cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf.backup
Dovecot Configuration
# Configure Dovecot main settings
sudo nano /etc/dovecot/dovecot.conf
# Basic Dovecot configuration:
# Protocols to serve
protocols = imap pop3 lmtp
# Listen on all interfaces
listen = *, ::
# Base directory for mail storage
base_dir = /var/run/dovecot/
# Configure mail location
sudo nano /etc/dovecot/conf.d/10-mail.conf
# Mail storage configuration:
mail_location = maildir:~/Maildir
mail_privileged_group = mail
first_valid_uid = 1000
last_valid_uid = 0
# Configure authentication
sudo nano /etc/dovecot/conf.d/10-auth.conf
# Authentication settings:
disable_plaintext_auth = yes
auth_mechanisms = plain login
!include auth-system.conf.ext
# Configure SSL/TLS
sudo nano /etc/dovecot/conf.d/10-ssl.conf
# SSL configuration:
ssl = required
ssl_cert = </etc/ssl/certs/dovecot.pem
ssl_key = </etc/ssl/private/dovecot.pem
ssl_protocols = !SSLv3 !TLSv1 !TLSv1.1
ssl_cipher_list = ECDHE+AESGCM:ECDHE+AES256:ECDHE+AES128:!RSA:!aNULL:!MD5:!DSS
ssl_prefer_server_ciphers = yes
# Generate SSL certificate for Dovecot
sudo openssl req -new -x509 -days 365 -nodes \
-keyout /etc/ssl/private/dovecot.pem \
-out /etc/ssl/certs/dovecot.pem \
-subj "/C=US/ST=State/L=City/O=Organization/CN=mail.example.com"
# Set proper permissions for SSL files
sudo chmod 600 /etc/ssl/private/dovecot.pem
sudo chmod 644 /etc/ssl/certs/dovecot.pem
# Test Dovecot configuration
sudo doveconf -n
# Output: Shows compiled Dovecot configuration
# Restart Dovecot to apply changes
sudo systemctl restart dovecot
# Output: Restarts Dovecot with new configuration
โ Integrating Postfix and Dovecot
SASL Authentication Setup
# Configure Postfix to use Dovecot for authentication
sudo nano /etc/postfix/main.cf
# Add SASL authentication settings:
# SASL Configuration
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
# Update SMTP restrictions to require authentication
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
# Configure Dovecot authentication socket
sudo nano /etc/dovecot/conf.d/10-master.conf
# Add Postfix authentication service:
service auth {
unix_listener auth-postfix {
mode = 0666
user = postfix
group = postfix
}
}
# Configure mail delivery via Dovecot
sudo nano /etc/postfix/main.cf
# Add local delivery agent settings:
mailbox_transport = lmtp:unix:private/dovecot-lmtp
# Configure Dovecot LMTP service
sudo nano /etc/dovecot/conf.d/20-lmtp.conf
# LMTP configuration:
protocol lmtp {
mail_plugins = $mail_plugins
postmaster_address = [email protected]
}
# Add LMTP service to master configuration
sudo nano /etc/dovecot/conf.d/10-master.conf
# Add LMTP service:
service lmtp {
unix_listener /var/spool/postfix/private/dovecot-lmtp {
mode = 0600
user = postfix
group = postfix
}
}
# Restart both services
sudo systemctl restart postfix dovecot
# Output: Restarts both mail services
SSL/TLS Configuration for SMTP
# Configure Postfix SSL/TLS
sudo nano /etc/postfix/main.cf
# Add TLS settings:
# TLS Configuration
smtpd_tls_cert_file = /etc/ssl/certs/dovecot.pem
smtpd_tls_key_file = /etc/ssl/private/dovecot.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
tls_random_source = dev:/dev/urandom
# Client TLS settings
smtp_tls_security_level = may
smtp_tls_note_starttls_offer = yes
# Configure submission port (587)
sudo nano /etc/postfix/master.cf
# Uncomment and configure submission service:
submission inet n - n - - smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_security_level=encrypt
-o smtpd_sasl_auth_enable=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
-o milter_macro_daemon_name=ORIGINATING
# Configure SMTPS port (465)
smtps inet n - n - - smtpd
-o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
-o milter_macro_daemon_name=ORIGINATING
# Restart Postfix
sudo systemctl restart postfix
# Output: Restarts Postfix with TLS configuration
๐ง Advanced Mail Server Features
Spam Protection with SpamAssassin
# Install SpamAssassin
sudo dnf install spamassassin -y
# Output: Installs spam filtering software
# Configure SpamAssassin
sudo nano /etc/mail/spamassassin/local.cf
# SpamAssassin configuration:
required_score 5.0
report_safe 0
rewrite_header Subject [SPAM]
use_bayes 1
bayes_auto_learn 1
bayes_auto_expire 1
# Start and enable SpamAssassin
sudo systemctl start spamassassin
sudo systemctl enable spamassassin
# Configure Postfix to use SpamAssassin
sudo nano /etc/postfix/master.cf
# Add content filter:
smtp inet n - n - - smtpd
-o content_filter=spamassassin
spamassassin unix - n n - - pipe
user=spamd argv=/usr/bin/spamc -f -e
/usr/sbin/sendmail -oi -f ${sender} ${recipient}
# Update Postfix main configuration
sudo nano /etc/postfix/main.cf
# Add content filter:
content_filter = spamassassin
# Restart services
sudo systemctl restart postfix spamassassin
Virus Scanning with ClamAV
# Install ClamAV
sudo dnf install clamav clamav-update clamd -y
# Output: Installs antivirus software
# Update virus definitions
sudo freshclam
# Output: Downloads latest virus definitions
# Configure ClamAV
sudo nano /etc/clamd.d/scan.conf
# ClamAV configuration:
LogFile /var/log/clamd.scan
LogTime yes
LogSyslog yes
LocalSocket /var/run/clamd.scan/clamd.sock
User clamscan
AllowSupplementaryGroups yes
# Start and enable ClamAV
sudo systemctl start clamd@scan
sudo systemctl enable clamd@scan
# Install amavisd-new for mail integration
sudo dnf install amavisd-new -y
# Configure amavisd-new
sudo nano /etc/amavisd/amavisd.conf
# Basic amavisd configuration:
$mydomain = 'example.com';
$inet_socket_port = 10024;
$inet_socket_bind = '127.0.0.1';
$myhostname = 'mail.example.com';
# Configure Postfix to use amavisd
sudo nano /etc/postfix/main.cf
# Add content filter:
content_filter = amavis:[127.0.0.1]:10024
# Add transport configuration
sudo nano /etc/postfix/master.cf
# Add amavis configuration:
amavis unix - - n - 2 smtp
-o smtp_data_done_timeout=1200
-o smtp_send_xforward_command=yes
127.0.0.1:10025 inet n - n - - smtpd
-o content_filter=
-o local_recipient_maps=
-o relay_recipient_maps=
-o smtpd_restriction_classes=
-o smtpd_client_restrictions=permit_mynetworks,reject
-o smtpd_helo_restrictions=
-o smtpd_sender_restrictions=
-o smtpd_recipient_restrictions=permit_mynetworks,reject
-o mynetworks=127.0.0.0/8
-o strict_rfc821_envelopes=yes
# Start amavisd
sudo systemctl start amavisd
sudo systemctl enable amavisd
# Restart Postfix
sudo systemctl restart postfix
๐ฎ Quick Examples
Example 1: Small Business Mail Server
# Set up complete mail server for small business
DOMAIN="company.com"
HOSTNAME="mail.company.com"
# Install all required packages
sudo dnf install postfix dovecot postfix-mysql dovecot-mysql roundcubemail -y
# Configure Postfix for business use
sudo nano /etc/postfix/main.cf
# Business mail configuration:
myhostname = $HOSTNAME
mydomain = $DOMAIN
myorigin = \$mydomain
inet_interfaces = all
mydestination = \$myhostname, localhost.\$mydomain, localhost, \$mydomain
mynetworks = 127.0.0.0/8, 192.168.1.0/24
home_mailbox = Maildir/
# Security and anti-spam measures
smtpd_helo_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, warn_if_reject 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, check_policy_service inet:127.0.0.1:10023
# Message limits
message_size_limit = 52428800
mailbox_size_limit = 2147483648
# TLS configuration
smtpd_tls_cert_file = /etc/ssl/certs/mail.pem
smtpd_tls_key_file = /etc/ssl/private/mail.pem
smtpd_tls_security_level = may
smtpd_tls_auth_only = yes
# Create business users
for user in admin sales support info; do
sudo useradd -m -s /bin/bash ${user}
echo "BusinessPass2024!" | sudo passwd --stdin ${user}
sudo mkdir -p /home/${user}/Maildir/{cur,new,tmp}
sudo chown -R ${user}:${user} /home/${user}/Maildir
sudo chmod -R 755 /home/${user}/Maildir
done
# Configure Dovecot for business
sudo nano /etc/dovecot/dovecot.conf
# Business Dovecot configuration:
protocols = imap pop3 lmtp
listen = *
mail_location = maildir:~/Maildir
ssl_cert = </etc/ssl/certs/mail.pem
ssl_key = </etc/ssl/private/mail.pem
auth_mechanisms = plain login
# Create mail monitoring script
sudo nano /usr/local/bin/mail-monitor.sh
# Add this content:
#!/bin/bash
# Business mail server monitoring script
LOG_FILE="/var/log/mail-monitor.log"
DATE=$(date '+%Y-%m-%d %H:%M:%S')
# Function to log messages
log_msg() {
echo "[$DATE] $1" >> "$LOG_FILE"
}
# Check Postfix status
if systemctl is-active postfix >/dev/null; then
log_msg "Postfix is running"
else
log_msg "ERROR: Postfix is down"
systemctl start postfix
fi
# Check Dovecot status
if systemctl is-active dovecot >/dev/null; then
log_msg "Dovecot is running"
else
log_msg "ERROR: Dovecot is down"
systemctl start dovecot
fi
# Check mail queue
QUEUE_SIZE=$(postqueue -p | tail -n 1 | awk '{print $5}')
if [ "$QUEUE_SIZE" != "empty" ]; then
log_msg "Mail queue has $QUEUE_SIZE messages"
fi
# Check disk usage for mail storage
DISK_USAGE=$(df /home | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$DISK_USAGE" -gt 80 ]; then
log_msg "WARNING: Mail storage disk usage is ${DISK_USAGE}%"
fi
# Check recent mail activity
RECENT_MAIL=$(grep "$(date +'%b %d')" /var/log/maillog | wc -l)
log_msg "Mail activity today: $RECENT_MAIL log entries"
# Make script executable and schedule
sudo chmod +x /usr/local/bin/mail-monitor.sh
echo "*/15 * * * * /usr/local/bin/mail-monitor.sh" | sudo crontab -
# Start all services
sudo systemctl restart postfix dovecot
sudo systemctl enable postfix dovecot
# Test mail server
echo "Test email from business mail server" | mail -s "Test Subject" admin@$DOMAIN
Example 2: Secure Mail Server with Virtual Domains
# Set up mail server with virtual domains support
sudo dnf install postfix dovecot postfix-mysql dovecot-mysql mariadb-server -y
# Set up MySQL database for virtual domains
sudo systemctl start mariadb
sudo mysql_secure_installation
# Create mail database
sudo mysql -u root -p << 'EOF'
CREATE DATABASE mailserver;
CREATE USER 'mailuser'@'localhost' IDENTIFIED BY 'MailPass2024!';
GRANT ALL PRIVILEGES ON mailserver.* TO 'mailuser'@'localhost';
FLUSH PRIVILEGES;
USE mailserver;
CREATE TABLE virtual_domains (
id int(11) NOT NULL auto_increment,
name varchar(50) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE virtual_users (
id int(11) NOT NULL auto_increment,
domain_id int(11) NOT NULL,
password varchar(106) NOT NULL,
email varchar(100) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY email (email),
FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
);
CREATE TABLE virtual_aliases (
id int(11) NOT NULL auto_increment,
domain_id int(11) NOT NULL,
source varchar(100) NOT NULL,
destination varchar(100) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
);
INSERT INTO virtual_domains (name) VALUES
('example.com'),
('company.com');
INSERT INTO virtual_users (domain_id, email, password) VALUES
(1, '[email protected]', ENCRYPT('AdminPass123!', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16)))),
(2, '[email protected]', ENCRYPT('AdminPass456!', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))));
EXIT;
EOF
# Configure Postfix for virtual domains
sudo nano /etc/postfix/main.cf
# 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_mailbox_base = /var/mail/vhosts
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
# Create MySQL configuration files
sudo nano /etc/postfix/mysql-virtual-mailbox-domains.cf
# Add:
user = mailuser
password = MailPass2024!
hosts = 127.0.0.1
dbname = mailserver
query = SELECT 1 FROM virtual_domains WHERE name='%s'
sudo nano /etc/postfix/mysql-virtual-mailbox-maps.cf
# Add:
user = mailuser
password = MailPass2024!
hosts = 127.0.0.1
dbname = mailserver
query = SELECT 1 FROM virtual_users WHERE email='%s'
sudo nano /etc/postfix/mysql-virtual-alias-maps.cf
# Add:
user = mailuser
password = MailPass2024!
hosts = 127.0.0.1
dbname = mailserver
query = SELECT destination FROM virtual_aliases WHERE source='%s'
# Create virtual mailbox directory
sudo mkdir -p /var/mail/vhosts
sudo groupadd -g 5000 vmail
sudo useradd -g vmail -u 5000 vmail -d /var/mail/vhosts
sudo chown -R vmail:vmail /var/mail/vhosts
# Configure Dovecot for virtual users
sudo nano /etc/dovecot/conf.d/10-auth.conf
# Disable system authentication and enable SQL
!include auth-sql.conf.ext
sudo nano /etc/dovecot/conf.d/auth-sql.conf.ext
# Add:
passdb {
driver = sql
args = /etc/dovecot/dovecot-sql.conf.ext
}
userdb {
driver = static
args = uid=vmail gid=vmail home=/var/mail/vhosts/%d/%n
}
sudo nano /etc/dovecot/dovecot-sql.conf.ext
# Add:
driver = mysql
connect = host=127.0.0.1 dbname=mailserver user=mailuser password=MailPass2024!
default_pass_scheme = SHA512-CRYPT
password_query = SELECT email as user, password FROM virtual_users WHERE email='%u';
# Set permissions
sudo chown -R vmail:dovecot /etc/dovecot
sudo chmod -R o-rwx /etc/dovecot
# Update mail location
sudo nano /etc/dovecot/conf.d/10-mail.conf
mail_location = maildir:/var/mail/vhosts/%d/%n
mail_uid = vmail
mail_gid = vmail
# Restart services
sudo systemctl restart postfix dovecot mariadb
sudo systemctl enable postfix dovecot mariadb
Example 3: High-Availability Mail Cluster
# Set up mail server clustering with backup
# Primary server configuration
PRIMARY_SERVER="mail1.example.com"
BACKUP_SERVER="mail2.example.com"
# Install cluster software
sudo dnf install pacemaker corosync pcs -y
# Configure shared storage for mail data
sudo mkdir -p /shared/mail
sudo chown vmail:vmail /shared/mail
# Create mail replication script
sudo nano /usr/local/bin/mail-replication.sh
# Add this content:
#!/bin/bash
# Mail data replication script
PRIMARY_HOST="192.168.1.10"
BACKUP_HOST="192.168.1.11"
MAIL_DIR="/var/mail/vhosts"
BACKUP_DIR="/backup/mail"
# Function to replicate mail data
replicate_mail() {
local source=$1
local destination=$2
# Sync mail data
rsync -avz --delete "$MAIL_DIR/" "$destination:$MAIL_DIR/"
# Sync configuration files
rsync -avz /etc/postfix/ "$destination:/etc/postfix/"
rsync -avz /etc/dovecot/ "$destination:/etc/dovecot/"
# Log replication
echo "$(date): Mail data replicated to $destination" >> /var/log/mail-replication.log
}
# Determine if this is primary or backup server
if hostname -f | grep -q "mail1"; then
# This is primary server
replicate_mail "$MAIL_DIR" "$BACKUP_HOST"
else
# This is backup server - receive replication
echo "$(date): Backup server ready for replication" >> /var/log/mail-replication.log
fi
# Create mail monitoring and failover script
sudo nano /usr/local/bin/mail-failover.sh
# Add this content:
#!/bin/bash
# Mail server failover monitoring
PRIMARY_IP="192.168.1.10"
BACKUP_IP="192.168.1.11"
VIP="192.168.1.100"
INTERFACE="eth0"
# Check if primary server is responding
check_primary() {
if ping -c 3 "$PRIMARY_IP" >/dev/null 2>&1; then
if telnet "$PRIMARY_IP" 25 </dev/null 2>&1 | grep -q "220"; then
return 0 # Primary is up
fi
fi
return 1 # Primary is down
}
# Activate virtual IP on backup server
activate_vip() {
ip addr add "$VIP/24" dev "$INTERFACE"
echo "$(date): Virtual IP activated on backup server" >> /var/log/mail-failover.log
}
# Deactivate virtual IP
deactivate_vip() {
ip addr del "$VIP/24" dev "$INTERFACE" 2>/dev/null
echo "$(date): Virtual IP deactivated" >> /var/log/mail-failover.log
}
# Main failover logic
if hostname -f | grep -q "mail2"; then
# This is backup server
if ! check_primary; then
echo "$(date): Primary server down, activating failover" >> /var/log/mail-failover.log
activate_vip
systemctl start postfix dovecot
else
deactivate_vip
systemctl stop postfix dovecot
fi
fi
# Make scripts executable and schedule
sudo chmod +x /usr/local/bin/mail-replication.sh
sudo chmod +x /usr/local/bin/mail-failover.sh
# Schedule replication every 5 minutes
echo "*/5 * * * * /usr/local/bin/mail-replication.sh" | sudo crontab -
# Schedule failover monitoring every minute
echo "* * * * * /usr/local/bin/mail-failover.sh" | sudo crontab -
# Configure mail client access script
sudo nano /usr/local/bin/mail-client-config.sh
# Add this content:
#!/bin/bash
# Generate mail client configuration
DOMAIN="example.com"
MAIL_SERVER="mail.example.com"
VIP="192.168.1.100"
echo "Mail Client Configuration for $DOMAIN"
echo "====================================="
echo ""
echo "Incoming Mail (IMAP):"
echo "Server: $MAIL_SERVER"
echo "Port: 993 (SSL/TLS)"
echo "Security: SSL/TLS"
echo ""
echo "Outgoing Mail (SMTP):"
echo "Server: $MAIL_SERVER"
echo "Port: 587 (STARTTLS)"
echo "Security: STARTTLS"
echo "Authentication: Required"
echo ""
echo "High Availability IP: $VIP"
echo "For maximum reliability, configure clients to use the HA IP address."
sudo chmod +x /usr/local/bin/mail-client-config.sh
๐จ Fix Common Problems
Problem 1: Mail Server Not Receiving Email
Symptoms: External emails not reaching the server
Solution:
# Check DNS MX records
dig MX yourdomain.com
nslookup -type=MX yourdomain.com
# Check if Postfix is listening
sudo netstat -tlnp | grep :25
sudo ss -tlnp | grep :25
# Check firewall settings
sudo firewall-cmd --list-services
sudo firewall-cmd --list-ports
# Test SMTP connectivity
telnet localhost 25
# Should get: 220 hostname ESMTP
# Check Postfix logs
sudo tail -f /var/log/maillog
sudo journalctl -u postfix -f
# Test mail delivery
echo "test" | mail -s "test" [email protected]
sudo postqueue -p
# Check for errors in configuration
sudo postfix check
sudo postconf -n
Problem 2: SMTP Authentication Failures
Symptoms: Cannot send email through SMTP with authentication
Solution:
# Check SASL authentication configuration
sudo postconf | grep sasl
sudo doveconf | grep auth
# Check if Dovecot auth socket exists
ls -la /var/spool/postfix/private/auth*
# Test SASL authentication
sudo testsaslauthd -u username -p password
# Check Dovecot authentication logs
sudo tail -f /var/log/dovecot.log
# Verify user credentials
sudo doveadm auth test username password
# Check SSL/TLS configuration
openssl s_client -connect localhost:587 -starttls smtp
# Test authenticated SMTP
telnet localhost 587
# Commands: EHLO, STARTTLS, AUTH PLAIN
Problem 3: Email Clients Cannot Connect
Symptoms: Email clients show connection errors
Solution:
# Check if services are running and listening
sudo systemctl status postfix dovecot
sudo netstat -tlnp | grep -E ':993|:143|:587|:465'
# Test IMAP connection
telnet localhost 993
openssl s_client -connect localhost:993
# Test SMTP submission
telnet localhost 587
# Check SSL certificates
openssl x509 -in /etc/ssl/certs/dovecot.pem -text -noout
# Verify certificate validity
openssl verify /etc/ssl/certs/dovecot.pem
# Check firewall and SELinux
sudo firewall-cmd --list-all
sestatus
sudo setsebool -P httpd_can_network_connect 1
# Test with email client settings:
# IMAP: port 993, SSL/TLS
# SMTP: port 587, STARTTLS
# Authentication: Normal password
๐ Simple Commands Summary
Command | Purpose | Example |
---|---|---|
systemctl start postfix | Start mail server | sudo systemctl start postfix |
systemctl start dovecot | Start IMAP/POP3 server | sudo systemctl start dovecot |
postfix check | Check Postfix config | sudo postfix check |
doveconf -n | Check Dovecot config | sudo doveconf -n |
postqueue -p | Check mail queue | sudo postqueue -p |
mail -s "subject" user@domain | Send test email | echo "test" | mail -s "test" [email protected] |
tail -f /var/log/maillog | Monitor mail logs | sudo tail -f /var/log/maillog |
telnet localhost 25 | Test SMTP | telnet localhost 25 |
๐ก Tips for Success
Here are proven strategies to master mail server setup! ๐
Best Practices
- ๐ Monitor Continuously: Keep track of mail server performance and logs
- ๐ก๏ธ Security First: Implement strong authentication, encryption, and spam filtering
- ๐พ Regular Backups: Backup mail data, configurations, and databases regularly
- ๐ Update Frequently: Keep mail server software updated with security patches
- ๐ Document Everything: Maintain detailed documentation of configurations and procedures
- ๐งช Test Thoroughly: Test all mail functionality before going into production
- ๐ Plan for Growth: Design infrastructure to handle increasing email volume
- ๐ฏ User Training: Educate users about email security and best practices
Security Guidelines
- Use strong SSL/TLS certificates from trusted authorities ๐
- Implement SPF, DKIM, and DMARC records for email authentication ๐ง
- Enable comprehensive spam and virus filtering ๐ก๏ธ
- Regular security audits and vulnerability assessments ๐
- Monitor for suspicious activity and unauthorized access attempts ๐๏ธ
- Implement proper access controls and user management ๐ฅ
- Keep detailed logs for security incident investigation ๐
- Regular penetration testing of mail infrastructure ๐งช
๐ What You Learned
Congratulations! Youโve mastered mail server setup on AlmaLinux! ๐ Hereโs what you can now do:
โ Install Mail Servers: Set up Postfix and Dovecot for complete email functionality โ Configure Security: Implement SSL/TLS, SASL authentication, and secure protocols โ Spam Protection: Deploy SpamAssassin and ClamAV for comprehensive email filtering โ Virtual Domains: Support multiple domains and virtual users with MySQL backend โ High Availability: Configure mail server clustering and failover systems โ Monitor and Maintain: Set up monitoring, logging, and maintenance procedures โ Troubleshoot Issues: Diagnose and fix common mail server problems โ Optimize Performance: Configure mail servers for optimal performance and reliability
๐ฏ Why This Matters
Mastering mail server setup is crucial for modern communications infrastructure! ๐ With these skills, you can:
- Control Your Communications: Own and manage your organizationโs email infrastructure ๐ผ
- Ensure Privacy and Security: Protect sensitive communications with advanced security measures ๐ก๏ธ
- Reduce Costs: Eliminate dependency on third-party email service providers ๐ฐ
- Enable Compliance: Meet regulatory requirements for email retention and security ๐
- Customize Features: Implement specialized functionality for specific business needs ๐ฏ
- Scale Efficiently: Build email systems that grow with your organization ๐
Mail server setup is a fundamental skill in the digital age! Whether youโre supporting a small business or enterprise organization, these skills will help you create reliable, secure, and efficient email systems. Remember, email is often the lifeline of business communications - make sure itโs in good hands! โญ
Excellent work on mastering mail server setup on AlmaLinux! You now have the expertise to build and manage enterprise-grade email infrastructure that meets any organizationโs needs! ๐