在 Ubuntu 22.04/24.04 上搭建可用的邮件服务器
一 准备与规划
hostname -f 能正确返回该值。mail.example.com → 服务器公网 IPexample.com → 优先级 10 mail.example.com.example.com → "v=spf1 mx -all"二 安装与基础配置 Postfix
sudo apt update && sudo apt install postfix -ymyhostname = mail.example.commydomain = example.commyorigin = $mydomaininet_interfaces = allinet_protocols = ipv4(或 all)mydestination = $myhostname, localhost.$mydomain, $mydomainmynetworks = 127.0.0.0/8 [::1]/128home_mailbox = Maildir/sudo systemctl restart postfix && sudo systemctl enable postfixtelnet localhost 25 → 输入 EHLO example.com,应看到 250-STARTTLS 等扩展三 安装与配置 Dovecot(IMAP/POP3 与投递)
sudo apt install dovecot-core dovecot-imapd dovecot-lmtpd -ymail_location = maildir:~/Maildirauth_mechanisms = plain loginservice auth 中创建 /var/spool/postfix/private/auth 的 unix listener(权限 0666,属主 postfix:postfix)smtpd_sasl_auth_enable = yessmtpd_sasl_type = dovecotsmtpd_sasl_path = private/authsmtpd_sasl_security_options = noanonymoussmtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destinationvirtual_transport = lmtp:unix:private/dovecot-lmtpservice lmtp 中创建 /var/spool/postfix/private/dovecot-lmtp(权限 0600,属主 postfix:postfix)sudo systemctl restart postfix dovecot && sudo systemctl enable dovecottelnet localhost 143 → a login 用户名 密码,a LIST "" "*"。四 安全与进阶配置
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.example.com/fullchain.pemsmtpd_tls_key_file = /etc/letsencrypt/live/mail.example.com/privkey.pemsmtpd_use_tls = yessmtp_tls_security_level = encryptsmtp_tls_note_starttls_offer = yesssl = requiredssl_cert = </etc/letsencrypt/live/mail.example.com/fullchain.pemssl_key = </etc/letsencrypt/live/mail.example.com/privkey.pemsudo ufw allow 25,587,143,993/tcp(按需增减)五 快速测试与常见问题
echo "主题:测试" | s-nail -s "测试邮件" -r from@you.com -S smtp=submission:587 -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user=you@you.com -S smtp-auth-password=密码 recipient@example.coms-nail -s "INBOX 测试" -S imaps -S ssl-verify=ignore recipient@example.com