配置 Dovecot:在 Ubuntu 上搭建 IMAP 和 POP3 服务器

Dovecot IMAP POP3 Ubuntu
披露:Email Wiki 上的部分链接为 VPS 服务商(如 Vultr)的联盟链接。通过这些链接购买,我们可能获得佣金,但不会对您产生额外费用。这有助于我们保持网站免费。所有教程均独立撰写,我们仅推荐我们认为适合自建邮件服务器的可靠服务。

Dovecot 是领先的开源 IMAP 和 POP3 服务器。Postfix 负责收发邮件,而 Dovecot 则让你的邮件客户端(Thunderbird、Apple Mail 等)能够读取邮件。两者组合构成自建邮件服务器的完整栈。

前提条件

  • Ubuntu 22.04,已安装 Postfix
  • 有效的域名 DNS 记录
  • TLS 证书(推荐 Let’s Encrypt)

第一步:安装 Dovecot

sudo apt update
sudo apt install dovecot-core dovecot-imapd dovecot-pop3d -y

验证版本:

dovecot --version

第二步:配置 Maildir 存储

Dovecot 支持 mbox(单文件)和 Maildir(每封邮件一个文件)两种格式,推荐使用 Maildir 以获得更好的性能和可靠性。

编辑 /etc/dovecot/conf.d/10-mail.conf

mail_location = maildir:~/Maildir

这与 Postfix 的 home_mailbox = Maildir/ 设置对应,每个用户的邮件存储在 ~用户名/Maildir/ 目录下。

第三步:配置认证

编辑 /etc/dovecot/conf.d/10-auth.conf

# 仅允许通过 TLS 进行明文认证
disable_plaintext_auth = yes
auth_mechanisms = plain login

Dovecot 默认使用系统用户(PAM)认证,适合小规模部署。若需虚拟用户,可使用 auth-sql.conf.extauth-ldap.conf.ext

第四步:启用 TLS

编辑 /etc/dovecot/conf.d/10-ssl.conf

ssl = required
ssl_cert = </etc/letsencrypt/live/mail.example.com/fullchain.pem
ssl_key  = </etc/letsencrypt/live/mail.example.com/privkey.pem
ssl_min_protocol = TLSv1.2
ssl_cipher_list = HIGH:!SSLv3:!aNULL

注意 < 前缀——Dovecot 使用此语法读取证书文件内容。

第五步:配置监听端口

编辑 /etc/dovecot/conf.d/10-master.conf,启用 IMAP(143/993 端口)和 POP3(110/995 端口):

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
  }
}

第六步:与 Postfix 集成(SASL)

Dovecot 可以为 Postfix 提供 SASL 认证,允许 Postfix 对发件进行身份验证。在 10-master.conf 中暴露认证套接字:

service auth {
  unix_listener /var/spool/postfix/private/auth {
    mode = 0660
    user = postfix
    group = postfix
  }
}

然后在 Postfix 的 /etc/postfix/main.cf 中添加:

smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes

重新加载两个服务:

sudo systemctl reload dovecot postfix

第七步:测试 IMAP 连接

使用 openssl 测试 TLS 上的 IMAP:

openssl s_client -connect mail.example.com:993

连接成功后,你会看到 Dovecot 的欢迎信息:

* OK [CAPABILITY IMAP4rev1 ...] Dovecot ready.

登录命令:

a1 LOGIN 用户名 密码

第八步:创建测试用户

sudo useradd -m -s /bin/bash testuser
sudo passwd testuser

然后在邮件客户端(如 Thunderbird)中配置:

  • IMAP 服务器mail.example.com,端口 993,SSL/TLS
  • SMTP 服务器mail.example.com,端口 587,STARTTLS
  • 用户名testuser

常见问题

“认证失败” — 查看 /var/log/mail.log/var/log/auth.log,确认客户端使用了 SSL 连接。

Maildir 目录权限问题 — 手动创建目录:sudo -u testuser mkdir -p ~/Maildir/{cur,new,tmp}

Dovecot 无法启动 — 执行 sudo dovecot -F 在前台运行查看错误,或用 doveconf -n 查看当前配置摘要。

下一步

Postfix + Dovecot 运行正常后,下一步是配置邮件认证(SPF、DKIM、DMARC),防止邮件被拒绝或进入垃圾箱。

准备好部署你的邮件服务器了吗?

你需要一台 IP 信誉干净的可靠 VPS。立即使用 Vultr——独立 IP、NVMe SSD、全球数据中心,最低 $6/月。