Ubuntu搭建强健的邮箱服务器(五)

这一节是这个系统的最后一节,之后有跟这个相关的文章我会做为另一个话题写了,不再做为邮箱服务器的后续了。总之,这一节的内容是干货满满的。

这一节的内容为实例讲解,根据之前四个小节的内容知道做一个实例部署讲解。如果你对相关的知识或参数不是很了解的话,请参考前面的四节内容

Ubuntu搭建强健的邮箱服务器(一)
Ubuntu搭建强健的邮箱服务器(二)
Ubuntu搭建强健的邮箱服务器(三)
Ubuntu搭建强健的邮箱服务器(四)

日志文件的查看

实时监控 /var/log/mail.log 文件的末尾,并输出新添加的日志内容。这对于查看正在发生的事情、错误消息或调试信息非常有用,尤其是在处理邮件服务器问题时

tail -f /var/log/mail.log

## 其它相关常用的命令:查看端口
sudo netstat -tulpen | grep 25

请确保你的防火墙已经开启,请将以下端口号打开:

## 关于邮件端口
SMTP:   TCP  25
IMAP:   TCP  143
POP3:   TCP  110
SMTPS:  TCP  465
IMAPS:  TCP  993
POP3S:  TCP  995

Web环境配置

这里我要的Web环境的搭建是为了日后做邮件管理用的。如果你对这个感兴趣,就了解一下,如果不感兴趣,这个小节就可以跳过。
我准备亲手撸一个邮箱管理器,用第三方的着实不应手。但凡有标准协议的东西,只要不是什么逆天的算法,我应该都能把它给搓出来。我的想法是把邮件的管理做的和QQ一样,再把P2P整合进来,做这么个应用,理论上我的知识储备和技术储备应该没什么问题。Mac端、移动端、win平台都适配上。我的后台就以PHP为主,Python为辅。不知什么原因,我天生就排斥Java。好,废话不多说,先把环境搭好,供日后使用。

时区调整

查看当前日期时间

date

调整时区:

sudo dpkg-reconfigure tzdata
打开防火墙
sudo ufw enable
安装Nginx

我这儿用Nginx做反向代理。

sudo apt update
sudo apt install nginx

## 成功安装Nginx之后,您可以运行以下命令来启动并验证它:
sudo systemctl start nginx
sudo systemctl status nginx

## 要检查Nginx的版本,请运行:
sudo dpkg -l nginx

## 添加到防火墙,打开80和443端口
sudo ufw allow 'Nginx Full'

##重新加载防火墙
sudo ufw reload

## 查看防火墙状态
sudo ufw status

关于一些命令操作,咱就用一个学一个,不要一咕噜脑的学一大堆,日常又用不到,最后还是忘记了,这就太浪费时间和脑细胞了。一定要听话,哥不会害你。

PHP安装

安装php8时先添加源:后更新

## 添加更新源
sudo add-apt-repository ppa:ondrej/php
## 更新源
sudo apt-get update
##安装PHP主组件
sudo apt-get install php8.3 php8.3-fpm php8.3-cli
## 查看PHP运行状态:
systemctl status php8.3-fpm
## 安装扩展
sudo apt-get install php8.3-{dev,curl,mysql,gd,opcache,zip,intl,common,bcmath,imagick,xmlrpc,readline,mbstring,apcu,xml,dom}
安装MySql
sudo apt-get install mysql-server

常用命令:

service mysql start   #启动服务器
service mysql stop   #关闭服务器
service mysql restart ## 重启服务

## sudo mysql -u root -p

## mysql的配置文件地址:/etc/mysql/mysql.conf.d/mysqld.cnf

## 确认是否成功:
## mysql节点处于LISTEN状态表示启动成功:
sudo netstat -tap | grep mysql
## 如果提示sudo:netstat找不到命令,请进行以下安装:
sudo apt-get install net-tools
## 再次 运行
sudo netstat -tap | grep mysql 

## 版本查看
mysql -V;    # 注意 V 是大写
查看初始用户及密码
# 查看初始密码
sudo cat /etc/mysql/debian.cnf

# 进行安全配置
sudo mysql_secure_installation //进行安全配置

然后用初始用户及密码登录修改

有时候用这种初始用户和密码也无法登录,则使用下面的方法:
在终端键入命令:sudo mysql -u root -p 输入密码即可登录(这里随便输入一个密码都可以进入,进入之而后再根据对应的mysql版本输入语句修改密码,下次就可以不用sudo了),然后就可以用下面的方法修改root用户的密码了。

root模式
sudo mysql  //进入mysql,输出以下信息:
...
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

修改root密码
## 切换到root
mysql> use mysql 

## 更新权限
flush privileges;

## 修改密码
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY '<我的新密码';

## 测试新密码登录:
$ mysql -u root -p
Enter password:    # 这里输入刚刚修改的新密码, 输出以下信息
...
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>
创建用户并赋于权限

Mysql8.0后的版本需要先创建用户,然后再授权:

mysql> CREATE USER '用户名'@'%' IDENTIFIED BY '密码';
mysql>  GRANT ALL PRIVILEGES ON [数据库.* | *.*] TO '用户名'@'[localhost | %]';
## 上面的 “|” 表示二选一,根据自己的需求。 “ % ”表示允许远程登录。localhost表示只能本地登录。
配置php.ini中的重要参数
## 允许上传的文件大小为800M
upload_max_filesize = 800M 
## 允许post的文件大小为800M
post_max_size = 800M 
## 允许内容占有的最小容量为256M
memory_limit = 256M 
## 允许脚本执行的最大时间为600秒。考虑到有时要上传文件,所以要调大一些。
max_execution_time = 600 
max_input_vars = 3000 
max_input_time = 1000
phpredis的安装

redis是一款内存数据库,要想提高服务器的性能,redis应用是少不了的。

## 首先安装Redis-server
sudo apt-get install redis-server -y

## pickle的方式安装phpredis
wget https://github.com/FriendsOfPHP/pickle/releases/latest/download/pickle.phar
$ php pickle.phar
$ chmod +x pickle.phar
$ mv pickle.phar pickle
$ sudo php pickle install redis

## 在php.ini中添加:
extension=redis.so
swool的安装

swoole是一款PHP下的高性能的并发请求和管理组件,功能十分强大,一句话难以描述它,总之爱不释手。

## 安装相应的扩展:
sudo apt-get install libcurl4-openssl-dev
sudo pecl install igbinary

## 通过pecl安装swoole:
sudo pecl install swoole

## 通过源码安装swoole
sudo git clone https://github.com/swoole/swoole-src.git
sudo apt-get install php-dev
cd swoole-src
phpize
./configure
sudo make && sudo make install
php.ini中的加载
## 在php.ini中添加:
extension=swoole.so
重新启动nginx
## 要停止,然后再次启动该服务,键入:
$ sudo systemctl restart nginx

## 查看nginx状态:
systemctl status nginx
服务块的配置

所谓服务块是指一台服务器上设置多个站点应用。每个应用就叫一个服务块。

## 创建speedxcn站点目录
sudo mkdir -p /var/www/myexample.com/html

## 使用$USER环境变量分配目录的所有权:
$ sudo chown -R $USER:$USER /var/www/html
$ sudo chown -R $USER:$USER /var/www/myexample.com/html

## 如果我们没有修改自己的umask值,那么Web根目录的权限应该正确,我们可以通过输入以下命令来确认:
$ sudo chmod -R 755 /var/www/myexample.com

##向站点中添加测试文件
$ sudo nano /var/www/myexample.com/html/echophpini.php

echophpini.php

<?pbhp
  echo phpini();

完成后保存并关闭文件。
创建服务块配置文件

$ sudo nano /etc/nginx/sites-available/myexample.com

粘贴到以下内容添加到文件中,这个块的配置与默认块的配置相似,但针对我们的新目录和域名进行了更新:

server {
        listen 80;
        listen [::]:80;

        root /var/www/myexample.com/html;

        index index.html index.htm index.php;

        server_name myexample.com www.myexample.com;

        location / {
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;s
        }
}

将服务块的配置文件链接到Nginx

sudo ln -s /etc/nginx/sites-available/myexample.com  /etc/nginx/sites-enabled/

为避免可能由于添加其他服务器名称而引起的哈希存储区内存问题,有必要调整/etc/nginx/nginx.conf文件中的单个值。打开文件:

sudo nano /etc/nginx/nginx.conf

找到server_names_hash_bucket_size指令并删除#符号:

...
http {
    ...
    server_names_hash_bucket_size 64;
    ...
}
...

完成后保存并关闭文件。
测试nginx的配置文件,以确保我们在 Nginx 文件中的改动,没有任何问题:

$ sudo nginx -t

如果没有任何问题,请重新启动 Nginx:

sudo systemctl restart nginx
为网站配置SSL

这里我们借助Certbot来申请免费的证书,同样可以为我们的站点保驾护航。免费证书有效期只有90天,不过我们可以设置自动继订。总之使用起来还是很丝滑的。
如果之前安装了certbot, 请先卸载它:

sudo apt-get remove certbot
  • 安装snapd:
## 安装snapd
sudo apt-get install snapd
  • 使用snap安装Certbot
sudo snap install --classic certbot

## 创建命令行链接
sudo ln -s /snap/bin/certbot  /usr/bin/certbot
  • 获取证书且自动配置ssl:
## 如果你的服务器只有一个站点且没有其它服务块的配置,则直接运行以下命令即可
sudo certbot --nginx

## 如果是多域名且有多服务块运行,则运行以下命令
sudo certbot --nginx -d myexample.com -d www.myexample.com 

## 获取证书成功后显示类似如下:
sudo certbot --nginx -d www.myexample.com -d myexample.com -d mail.myexample.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Requesting a certificate for www.myexample.com and 2 more domains

Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/www.myexample.com/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/www.myexample.com/privkey.pem
This certificate expires on 2024-03-09.
These files will be updated when the certificate renews.
Certbot has set up a scheduled task to automatically renew this certificate in the background.

Deploying certificate
Successfully deployed certificate for www.myexample.com to /etc/nginx/sites-enabled/myexample.com
Successfully deployed certificate for myexample.com to /etc/nginx/sites-enabled/myexample.com
Successfully deployed certificate for mail.myexample.com to /etc/nginx/sites-enabled/mail.myexample.com.conf
Congratulations! You have successfully enabled HTTPS on https://www.myexample.com, https://myexample.com, and https://mail.myexample.com

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If you like Certbot, please consider supporting our work by:
 * Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
 * Donating to EFF:                    https://eff.org/donate-le
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
## 上面显示了证书的目录、到期日期等信息。
  • 测试自动续签:

系统上的 Certbot 软件包附带一个 cron 作业或 systemd 计时器,它们将在证书过期之前自动续订证书。除非您更改配置,否则您无需再次运行 Certbot。您可以通过运行以下命令来测试证书的自动续订:

sudo certbot renew --dry-run

这时的配置文件应该是这样的:

server {
        listen 443 ssl;

        root /var/www/myexample.com/html;

        index index.html index.htm index.php;

        server_name myexample.com www.myexample.com;

        location / {
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
        }

    ssl_certificate /etc/letsencrypt/live/www.myexample.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/www.myexample.com/privkey.pem; # managed by Certbot

}
server {
    if ($host = myexample.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = www.myexample.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    listen [::]:80;

    server_name myexample.com www.myexample.com;
    return 404; # managed by Certbot
}

postfix的安装与配置

安装
sudo apt install postfix postfix-mysql opendkim opendkim-tools spf-tools-perl

或使用以下命令安装Postfix:

sudo apt install mailutils

打开交互配置如下:

sudo dpkg-reconfigure postfix

配置交互中的各项信息为:

  1. 邮件配置的一般类型 : Internet站点
  2. 系统邮件名称:myexample.com(不是mail.myexample.com)
  3. Root 和 postmaster 邮件收件人:您的主要 Linux 帐户的用户名(在我们的示例中为 admin@myexample.com
  4. 其他接收邮件的目的地:$myhostname, myexample.com, mail.myexample.com, localhost.myexample.com, localhost
  5. 强制同步更新邮件队列?
  6. 本地网络:127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
  7. 邮箱大小限制:0
  8. 本地地址扩展字符:+
  9. 要使用的互联网协议所有

生成的Postfix配置项如下所示:

sudo nano /etc/postfix/main.cf

## 确保以下设置正确

myhostname = mail.myexample.com
mydomain = myexample.com
myorigin = $mydomain
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128

更改主机的hostname

sudo hostnamectl set-hostname mail.myexample.com

##显示本机的hostname
hostname -f

## 我们还需要使用命令行文本编辑器(如 Nano)更新文件。/etc/hosts
sudo nano /etc/hosts

## 更改如下:
127.0.0.1       localhost
127.0.0.1       mail.myexample.com 
配置DNS

确保你的DNS记录包括MX记录,指向你的邮件服务器

Type: TXT
Name: @
Value: v=spf1 include:myexample.com ~all
Priority: 10

Type: TXT
Name: _dmarc
Value: v=DMARC1; p=quarantine; rua=mailto:dmarc@myexample.com; 
				ruf=mailto:dmarc@myexample.com; fo=1;
Priority: 10

Type: TXT
Name: default._domainkey
Value: v=DKIM1;h=sha256;k=rsa;p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAif6k
				......
        L5Jsztmv+7Bf1cBNZjHXVwiricNSm87G5q1Y8Qev0JRXAAX95h1Bc8C//fvVG3UBrlxwbKzA
        pyWxzQSyvDjWR29wboqhXmkiPneUfP8Hsry4Xz6mrWK2g9oAsDQIDAQAB
Priority: 10

Type: MX
Name: @
Value: myexample.com
Priority: 10

Type: A
Name: mail
Value: 192.168.1.17
Priority: 10

Type: A
Name: imap
Value: 192.168.1.17
Priority: 10

Type: A
Name: smtp
Value: 192.168.1.17
Priority: 10

Type: A
Name: pop3
Value: 192.168.1.17
Priority: 10

Type: A
Name: www
Value: 192.168.1.17
Priority: 10

Type: A
Name: @
Value: 192.168.1.17
Priority: 10

其中imap.myexample.cn用于接收邮件服务,smtp.myexample.cn用于发送邮件服务, 如果MX记录的目标是mail.myexample.com,那么邮件服务器将尝试将邮件发送到mail.myexample.com。如果这个MX记录的目标是myexample.com,那么邮件服务器会尝试将邮件发送到myexample.com。在后一种情况下,邮件服务器可能会查找myexample.com域的MX记录,以确定实际处理邮件的邮件服务器。

安装SASL服务

SASLauthd(SASL authentication daemon)是一个独立的服务, 负责处理基于 SASL 的身份验证。

sudo apt-get update
sudo apt-get install libsasl2-modules sasl2-bin libsasl2-modules-db

## 确保 saslauthd 服务已经启动。你可以使用以下命令来启动和检查服务状态:
sudo systemctl start saslauthd
sudo systemctl enable saslauthd
sudo systemctl status saslauthd

## 验证 SASLauthd 是否正在监听 saslauthd 的默认套接字 
sudo netstat -ln | grep saslauthd

安装完成后,你需要配置和启动 SASLauthd 服务。在配置文件中指定要使用的验证机制和认证源(例如,PAM、LDAP等),然后启动服务。

SASL认证数据库

配置SASL以使用适当的认证数据库。在/etc/postfix/sasl/smtpd.conf文件中添加以下内容:

pwcheck_method: saslauthd
mech_list: plain login

此配置使用saslauthd作为密码验证方法,并指定支持的身份验证机制。

SASL认证用户源

配置SASL以指定认证用户的来源。在 /etc/default/saslauthd 文件中添加以下行:

START=yes
MECHANISMS="pam"

上述配置使用PAM(Pluggable Authentication Modules)来提供SASL认证。

开启Postfix的SASL服务及提交服务
## 打开postfix的进程服务配置文件
sudo nano /etc/postfix/master.cf

#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (no)    (never) (100)
# ==========================================================================
smtp      inet  n       -       y       -       -       smtpd
#smtp      inet  n       -       y       -       1       postscreen
#smtpd     pass  -       -       y       -       -       smtpd
#dnsblog   unix  -       -       y       -       0       dnsblog
#tlsproxy  unix  -       -       y       -       0       tlsproxy
# Choose one: enable submission for loopback clients only, or for any client.
#127.0.0.1:submission inet n -   y       -       -       smtpd
submission inet n       -       y       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_tls_security_level=may
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_sasl_type=cyrus
  -o smtpd_sasl_type=dovecot
#  -o smtpd_sasl_path=smtpd
  -o smtpd_sasl_path=private/auth
  -o smtpd_tls_wrappermode=no
#  -o smtpd_tls_auth_only=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
  -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
# Choose one: enable smtps for loopback clients only, or for any client.
#127.0.0.1:smtps inet n  -       y       -       -       smtpd
smtps     inet  n       -       y       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
  -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
  -o smtpd_sasl_type=dovecot
  -o smtpd_sasl_path=private/auth
#  -o milter_macro_daemon_name=ORIGINATING

## 配置SPF验证功能
policyd-spf  unix  -       n       n       -       0       spawn
  user=policyd-spf argv=/usr/bin/policyd-spf

这里,smtpd_sasl_auth_enable 启用 SASL 身份验证,smtpd_sasl_typesmtpd_sasl_path 配置了 Cyrus SASL。smtpd_tls_security_level 设置为 may,以允许启用 TLS 包装模式,但不要求客户端使用 TLS。这是通常的设置,适用于保护身份验证信息的同时仍然允许非加密通信。

重启服务
sudo systemctl restart postfix
## sudo systemctl restart saslauthd
sudo systemctl start saslauthd
## 如何没有错误,开启开机启动
sudo systemctl enable saslauthd
SMTP身份验证

配置SMTP身份验证可以防止未经授权的用户使用邮件服务器来发送邮件。你可以启用SMTP身份验证以要求用户在发送邮件之前提供用户名和密码。

##打开/etc/postfix/main.cf
sudo nano /etc/postfix/main.cf

## 确保以下配置参数的设置正确

## 这个参数启用了 SMTP 身份验证。
smtpd_sasl_auth_enable = yes

## 设置SASL库的类型。在这里,使用CyrusSASL(Simple Authentication and Security Layer)
## 来处理SMTP身份验证。
smtpd_sasl_type = dovecot
## 指定了 Cyrus SASL 库的路径,这里设置为 smtpd。
smtpd_sasl_path = private/auth

## 指定 Postfix 服务器的本地域
smtpd_sasl_local_domain = $myhostname

## 设置 SASL 的安全选项,这里禁用了匿名登录,即 noanonymous。
smtpd_sasl_security_options = noanonymous

## 该参数启用了对于一些不太规范的 SASL 客户端的兼容性处理。
broken_sasl_auth_clients = yes

## 限制每个客户端在60秒内只能发送30封邮件
smtpd_client_message_rate_limit = 30

## 该设置指定了用于验证对方SMTP服务器证书的证书颁发机构(CA)路径。在这里,
## 它指定了系统SSL证书存储的路径。
smtp_tls_CApath=/etc/ssl/certs

## 该设置指定了用于外部SMTP服务器连接的TLS加密级别。may 表示Postfix将尝试使用TLS,
##但如果连接失败或对方服务器不支持TLS,仍然允许未加密的连接。
smtp_tls_security_level = may

## 该设置指定了Postfix用于缓存SMTP会话状态的数据库文件。这有助于提高性能,
## 避免在TLS握手过程中进行重复的计算。这里使用了BDB(Berkeley Database)格式的数据库。
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache:

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination:
## 该设置定义了允许邮件中继的规则。具体地说:
## permit_mynetworks 允许来自Postfix服务器的内部网络的邮件中继。
## permit_sasl_authenticated 允许经过SMTP身份验证的用户进行邮件中继。
## defer_unauth_destination 会推迟对于未认证目标域的邮件中继,直到后续的规则进一步处理。这是一种常见的配置,以防止未授权的邮件中继。

本实例不中继其它服务的邮件,所以把与中继(relay)有关的服务可关闭了。

TLS/SSL加密
## 打开配置文件
sudo nano /etc/postfix/main.cf

## 配置如下,这里的证书就是上面我们为站点申请的SSL证书,拿来用也是一样的。省事。
smtpd_tls_cert_file=/etc/letsencrypt/live/www.myexample.com/fullchain.pem
smtpd_tls_key_file=/etc/letsencrypt/live/www.myexample.com/privkey.pem
smtpd_use_tls = yes
smtpd_tls_auth_only = yes

上述配置中,smtpd_tls_cert_file 和 smtpd_tls_key_file 分别指定TLS证书和私钥的文件路径。

日志

指定日志文件路径:

maillog_file = /var/log/mail.log

这里的路径可以根据你的系统和偏好进行调整。

配置SPF

检查SPF记录

安装工具:

sudo apt install bind9-dnsutils

输入命令:

dig myexample.com txt

显示内容如下所示:

; <<>> DiG 9.18.18-0ubuntu0.22.04.1-Ubuntu <<>> myexample.com txt
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 27336
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;myexample.com.			IN	TXT

;; ANSWER SECTION:
myexample.com.		600	IN	TXT	"v=spf1 include:myexample.com ~all"

;; Query time: 43 msec
;; SERVER: 127.0.0.53#53(127.0.0.53) (UDP)
;; WHEN: Sun Dec 31 15:22:57 CST 2023
;; MSG SIZE  rcvd: 86

配置SPF策略代理

SPF 用于指定哪些邮件服务器被允许发送来自特定域名的电子邮件。俗称 白名单
安装工具

sudo apt-get install spf-tools-perl

打开 /etc/default/spf-policyd 文件以编辑:

sudo nano /etc/default/spf-policyd

## 输入以下内容
HELO_DOMAIN=myexample.com
DEF_POLICY_NXDOMAIN=yes
## DEF_POLICY_NXDOMAIN 设置为 yes 表示如果 SPF 记录不存在时,默认行为是拒绝。

我们还需要告诉我们的Postfix SMTP服务器检查传入电子邮件的SPF记录。这有助于检测伪造的传入电子邮件。
首先,安装所需的软件包:

sudo apt install postfix-policyd-spf-python

然后编辑 Postfix 主进程配置文件。

sudo nano /etc/postfix/master.cf

在文件末尾添加以下行,告诉 Postfix 在启动 SPF 策略守护程序时启动它。

policyd-spf  unix  -       n       n       -       0       spawn
    user=policyd-spf argv=/usr/bin/policyd-spf

保存并关闭文件。
接下来,编辑 Postfix 主配置文件。
在文件末尾追加以下行。第一行指定 Postfix 策略代理超时设置。以下几行将通过拒绝未经授权的电子邮件和检查 SPF 记录来限制传入的电子邮件。

sudo nano /etc/postfix/main.cf

## 添加以下记录, SPF验证功能
policyd-spf_time_limit = 3600
smtpd_recipient_restrictions =
   permit_mynetworks,
   permit_sasl_authenticated,
   reject_unauth_destination,
   check_policy_service unix:private/policyd-spf

保存并关闭文件。然后重新启动 Postfix。

sudo systemctl restart postfix

下次,当您收到来自具有 SPF 记录的域的电子邮件时,您可以在原始电子邮件标题中看到 SPF 检查结果。以下标头指示发件人从授权主机发送电子邮件。

Received-SPF: Pass (sender SPF authorized).
配置PTR记录

PTR记录也叫做pointer记录,它将IP地址转换成主机名,与A记录刚好相反。这种解析被称为反向DNS解析(rDNS)。
PTR记录可以帮助我们过滤垃圾邮件。很多SMTP服务器会查找对方SMTP服务器的PTR记录,得到一个主机名,然后与对方SMTP声称的主机名作比较,如果两者一致,就接收邮件,反之不接收邮件或放进垃圾箱。为了不让你的邮件被拒收或放进垃圾箱,你应该为你的服务器IP设置PTR记录。
查找一个IP地址的PTR记录的命令为:

dig -x <IP> +short

## 或
host <IP>

因为你是从主机商获得服务器的IP,所以你得在主机商那里设置PTR记录(反向DNS解析),而不是在域名注册商那里设置。

设置DKIM
  1. 安装:
sudo apt-get install opendkim opendkim-tools 
## 将 postfix 用户添加到 opendkim 组
sudo usermod -G opendkim postfix
## 或
sudo gpasswd -a postfix opendkim
  1. 生成密钥对:
sudo mkdir -p /etc/opendkim/keys/mail.myexample.com
sudo chown -R opendkim:opendkim /etc/opendkim
sudo chmod go-rw /etc/opendkim/keys

sudo opendkim-genkey -b 2048 -d myexample.com -D /etc/opendkim/keys/mail.myexample.com -s default -v

## 生成密钥后,需要对私钥文件设置适当的权限:
sudo chown opendkim:opendkim /etc/opendkim/keys
## 更改权限,以便只有用户才能对文件进行读写访问。opendkim
sudo chmod 600 /etc/opendkim/keys/mail.myexample.com/default.private
  1. 将DKIM TXT记录添加到DNS
    上面的命令完成后还会生成一个default.txt的文件,把里面的内容根据前几个小节介绍的方法把内容进行拼接好写入DNS。
default._domainkey IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB........n49i/xLNCrlavz9n8lLpQIDAQAB"
  1. 配置OpenDKIM

修改 OpenDKIM 的配置文件以指向生成的私钥。
打开 /etc/opendkim.conf 文件,并确保以下行的设置:

# This is a basic configuration for signing and verifying. It can easily be
# adapted to suit a basic installation. See opendkim.conf(5) and
# /usr/share/doc/opendkim/examples/opendkim.conf.sample for complete
# documentation of available configuration parameters.

Syslog                  yes
SyslogSuccess           yes
#LogWhy                 no
LogWhy                  yes

# Common signing and verification parameters. In Debian, the "From" header is
# oversigned, because it is often the identity key used by reputation systems
# and thus somewhat security sensitive.
Canonicalization        relaxed/simple
Mode                    sv
SubDomains              no
OversignHeaders         From

# Signing domain, selector, and key (required). For example, perform signing
# for domain "example.com" with selector "2020" (2020._domainkey.example.com),
# using the private key stored in /etc/dkimkeys/example.private. More granular
# setup options can be found in /usr/share/doc/opendkim/README.opendkim.

## 确保 Domain 匹配你的域名,KeyFile 指向你生成的私钥文件。
Domain                  myexample.com
KeyFile                 /etc/opendkim/keys/mail.myexample.com/default.private
Selector                default

# In Debian, opendkim runs as user "opendkim". A umask of 007 is required when
# using a local socket with MTAs that access the socket as a non-privileged
# user (for example, Postfix). You may need to add user "postfix" to group
# "opendkim" in that case.

## 接下来,确保将 UserID 设置为 opendkim
# Remember to add user postfix to group opendkim
UserID             opendkim
UMask                   007

# Socket for the MTA connection (required). If the MTA is inside a chroot jail,
# it must be ensured that the socket is accessible. In Debian, Postfix runs in
# a chroot in /var/spool/postfix, therefore a Unix socket would have to be
# configured as shown on the last line below.
#Socket                 local:/run/opendkim/opendkim.sock
#Socket                 inet:8891@localhost
#Socket                 inet:8891
Socket                  local:/var/spool/postfix/opendkim/opendkim.sock

PidFile                 /run/opendkim/opendkim.pid

# Hosts for which to sign rather than verify, default is 127.0.0.1. See the
# OPERATION section of opendkim(8) for more information.
#InternalHosts          192.168.0.0/16, 10.0.0.0/8, 172.16.0.0/12

# The trust anchor enables DNSSEC. In Debian, the trust anchor file is provided
# by the package dns-root-data.
TrustAnchorFile         /usr/share/dns/root.key
#Nameservers            127.0.0.1

AutoRestart                     yes
AutoRestartRate                 10/1M
Background                      yes
DNSTimeout                      5
SignatureAlgorithm              rsa-sha256

KeyTable            refile:/etc/opendkim/KeyTable
SigningTable        refile:/etc/opendkim/SigningTable
ExternalIgnoreList  refile:/etc/opendkim/TrustedHosts
InternalHosts       refile:/etc/opendkim/TrustedHosts
创建签名表、密钥表、受信主机文件
  1. 创建签名表SigningTable
sudo nano /etc/opendkim/SigningTable

将以下两行添加到文件中。这告诉OpenDKIM,如果服务器上的发件人使用地址,则应使用由标识的私钥对其进行签名。第二行表明您的子域也将由私钥签名。

*@myexample.com    default._domainkey.myexample.com
*@*.myexample.com    default._domainkey.myexample.com

保存并关闭文件。

  1. 然后创建键表KeyTable。
sudo nano /etc/opendkim/KeyTable

添加以下行,该行告知私钥的位置。

default._domainkey.myexample.com     myexample.com:default:/etc/opendkim/keys/mail.myexample.com/default.private

保存并关闭文件。

  1. 创建受信任的主机文件TrustedHosts
sudo nano /etc/opendkim/TrustedHosts

将以下行添加到新创建的文件中。这告诉OpenDKIM,如果电子邮件来自本地主机或来自同一域,则OpenDKIM应该只对电子邮件进行签名,而不对电子邮件执行DKIM验证。

127.0.0.1
localhost

*.myexample.com

保存并关闭文件。

  1. 权限

如果运行错误,有可能是文件权限问题:

## 查看文件的权限
ls -l /etc/opendkim/TrustedHosts

## 如果不对,则进行以下操作
sudo chmod 644 /etc/opendkim/KeyTable
sudo chmod 644 /etc/opendkim/SigningTable
sudo chmod 644 /etc/opendkim/TrustedHosts

sudo chown :opendkim /etc/opendkim/KeyTable
sudo chown :opendkim /etc/opendkim/SigningTable
sudo chown :opendkim /etc/opendkim/TrustedHosts

sudo chmod g+r /etc/opendkim/TrustedHosts
sudo chmod g+r /etc/opendkim/KeyTable
sudo chmod g+r /etc/opendkim/SigningTable
  1. 重启OpenDKIM

在完成以上步骤后,重新启动 OpenDKIM 服务以应用更改:

sudo systemctl restart opendkim

## 查看运行状态
sudo systemctl status opendkim
  1. 请确保没有错误,并监视系统日志以查找潜在的 DKIM 配置问题:
## 按服务查看日志: opendkim 日志
sudo journalctl -u opendkim

## 查看最新的日志:
sudo journalctl

## 按时间范围查看日志:
sudo journalctl -u opendkim --since "2024-01-01 00:00:00" --until "2024-01-02 00:00:00"

## 按关键字搜索日志:
sudo journalctl | grep "keyword"
  1. 验证DNS记录
## 此命令会检查密钥的语法和配置。
sudo opendkim-testkey -d myexample.com -s default -vvv 

## 输出信息如下:
opendkim-testkey: using default configfile /etc/opendkim.conf
opendkim-testkey: key loaded from /etc/opendkim/keys/mail.myexample.com/default.private
opendkim-testkey: checking key 'default._domainkey.myexample.com'
opendkim-testkey: key not secure
opendkim-testkey: key OK

完成上述步骤后,你的邮件服务器就使用 DKIM 进行签名了。确保邮件发送到目标邮箱时,目标邮箱服务器能够验证 DKIM 签名。

将Postfix连接到OpenDKIM

Postfix 可以通过 Unix 套接字文件与 OpenDKIM 通信。OpenDKIM 使用的默认套接字文件是 /var/run/opendkim/opendkim.sock。但是 Ubuntu 附带的 postfix SMTP 守护程序在 chroot jail 中运行,这意味着 SMTP 守护程序会解析相对于 Postfix 队列目录 (/etc/opendkim.conf) 的所有文件名。因此,我们需要更改OpenDKIM Unix套接字文件 /var/spool/postfix。

  1. 首先,我们将更改 OpenDKIM套接字文件的位置。让我们使用以下命令创建一个新目录,并仅允许用户和组访问它。opendkim :postfix
sudo mkdir /var/spool/postfix/opendkim 
sudo chown opendkim:postfix /var/spool/postfix/opendkim
  1. 现在在文本编辑器中编辑OpenDKIM配置文件:
sudo nano /etc/opendkim.conf

搜索 Socket 条目并按如下方式更新它:

Socket    local:/var/spool/postfix/opendkim/opendkim.sock
  1. 接下来编辑 /etc/default/opendkim 文件:
sudo nano /etc/default/opendkim

并设置SOCKET条目,如下所示:

SOCKET=local:/var/spool/postfix/opendkim/opendkim.sock
  1. 接下来,您需要编辑位于 /etc/postfix/main.cf 的配置文件。在此文件中,您需要添加以下参数:
sudo nano /etc/postfix/main.cf

在此文件的末尾添加以下行,以便 Postfix 能够通过 milter 协议调用 OpenDKIM。

# Milter configuration
milter_default_action = accept
milter_protocol = 6
smtpd_milters = local:opendkim/opendkim.sock,local:opendmarc/opendmarc.sock
non_smtpd_milters = $smtpd_milters
  1. 添加参数后,您需要重新启动 OpenDKIm 和 Postfix 服务。为此,您需要运行以下命令:
sudo systemctl restart opendkim postfix

## 添加到开机自启
sudo systemctl enable opendkim

此命令将重新启动这两个服务,您将准备好使用 OpenDKIM 发送电子邮件。

配置DMARC

DNS的设置

**DMARC**记录是一种TXT记录,有助于防止电子邮件欺骗
要为您的域生成 DMARC 记录,您需要在 DNS 上创建一个具有以下值的 TXT 记录:

_dmarc.myexample.com   TXT   "v=DMARC1; p=none; rua=mailto:dmarc_report@myexample.com; fo=1;"
安装和配置DMARC

通过包管理器安装 DMARC 解析工具opendmarc。

sudo apt-get update
sudo apt-get install opendmarc

如果要求你为OpenDMARC配置数据库,你可以放心地选择**“否**”。如果你想为其他邮箱提供商生成DMARC报告,你只需要为OpenDMARC配置一个数据库。对于像我们这样的小型邮件服务器运营商来说,生成DMARC报告不是很有用,所以我们可以跳过它。
安装后,它将自动启动。使用以下方式检查其状态:

systemctl status opendmarc

## 显示如下:
opendmarc.service - OpenDMARC Milter
   Loaded: loaded (/lib/systemd/system/opendmarc.service; disabled; vendor preset: enabled)
   Active: active (running) since Tue 2018-10-30 19:49:52 CST; 23s ago
     Docs: man:opendmarc(8)
           man:opendmarc.conf(5)
 Main PID: 14858 (opendmarc)
    Tasks: 6 (limit: 1110)
   CGroup: /system.slice/opendmarc.service
           └─14858 /usr/sbin/opendmarc

请注意,系统启动时的自动启动功能处于禁用状态。我们可以通过以下方式启用它:

sudo systemctl enable opendmarc

配置 DMARC 设置。编辑 /etc/opendmarc.conf 文件,根据你的需求进行配置。确保设置了 AuthservID,这是邮件服务器的身份标识。

AuthservID OpenDMARC

接下来,添加以下行。将主机名替换为您的真实 Postfix 主机名。这告诉OpenDMARC信任ID中的认证结果。当您运行 OpenDKIM 进行 DKIM 验证时,这是必需的。

TrustedAuthservIDs myexample.com

如果 Postfix 主机名未包含在 中,或者您的主机名中有拼写错误,那么 OpenDMARC 将忽略 OpenDKIM 生成的身份验证结果标头,您将在邮件日志 /var/log/mail.log 中找到以下错误消息

opendmarc[1133]: A436A205C9 ignoring Authentication-Results at 1 from mail.myexample.com

然后找到这一行:

# RejectFailures false

默认情况下,OpenDMARC不会拒绝未通过DMARC检查的电子邮件,即使域名的政策设置为.p=reject。如果您希望在域的政策设置为p=reject 时拒绝未通过 DMARC 检查的电子邮件,请取消注释此行并更改falsetrue

RejectFailures true

你可能希望OpenDMARC忽略通过SMTP AUTH成功认证的SMTP客户端。例如,我有一个Postfix SMTP服务器在我的博客网络服务器上运行,它使用我的主邮件服务器作为中继来发送通知电子邮件,所以我希望openDMARC忽略从我的博客网络服务器提交的电子邮件。这也适用于通过端口 587 提交传出电子邮件的桌面/移动邮件客户端。在这种情况下,请在此文件的末尾添加以下行。

IgnoreAuthenticatedClients true

在此文件的末尾添加以下行。

RequiredHeaders    true

这将拒绝不符合RFC5322中所述的电子邮件标题标准的电子邮件。例如,如果传入的电子邮件没有标题或标题,它将被拒绝。无法从中提取域名的 From: 字段也将被拒绝。From📅
建议在此文件的末尾添加以下行。这将使OpenDMARC在邮件头中找不到SPF结果时执行回退SPF检查。

SPFSelfValidate true

OpenDMARC是作为milter(邮件过滤器)实现的。Postfix 可以通过 Unix 套接字与 milter 应用程序通信。OpenDMARC使用的默认套接字文件是/var/run/opendmarc/opendmarc.sock/。但是 Ubuntu 附带的 Postfix SMTP 守护程序在 chroot jail 中运行,这意味着 SMTP 守护程序会解析相对于 Postfix 队列目录 (var/spool/postfix) 的所有文件名。所以我们需要改变OpenDMARC使用的套接字文件。
找到以下行。

Socket local:/var/run/opendmarc/opendmarc.sock

将其更改为:

Socket local:/var/spool/postfix/opendmarc/opendmarc.sock

保存并关闭文件。

注意:该文件也可以设置套接字文件位置,但是 Ubuntu 18.04 和 20.04
上的包不会读取此文件,因此我们需要在文件中设置套接字文件路径。/etc/default/opendmarcopendmarc/etc/opendmarc.conf

创建一个目录来保存OpenDMARC套接字文件,并更改所有权,以便用户和组可以访问它。

sudo mkdir -p /var/spool/postfix/opendmarc
sudo chown opendmarc:opendmarc /var/spool/postfix/opendmarc -R

sudo chmod 750 /var/spool/postfix/opendmarc/ -R
sudo adduser postfix opendmarc

启用 DMARC。编辑 /etc/default/opendmarc 文件,确保 OPENDMARC_ENABLED 被设置为 true。

OPENDMARC_ENABLED=true

然后重新启动OpenDMARC。

sudo systemctl restart opendmarc
Postfix的相关配置
  1. 启用 DMARC 功能: 在 Postfix 中,你需要确保启用了 DMARC 功能。这通常是通过在主配置文件中添加以下行来完成:
sudo nano /etc/postfix/main.cf

## 如何下面设置了插件rspamd,没注意端口的设置 smtpd_milters
milter_default_action = accept
milter_protocol = 6
smtpd_milters = local:opendkim/opendkim.sock,local:opendmarc/opendmarc.sock
non_smtpd_milters = $smtpd_milters

请确保 Postfix 启用了 milter 协议,并与一个 DMARC 验证器通信。你可能需要调整端口号和 IP 地址,以匹配你系统上的实际设置。
保存并关闭文件。然后重新启动 Postfix 以使更改生效。

sudo systemctl restart postfix

Postfix配置

配置检测

使用 Postfix 内置的配置语法检查来测试你的配置文件,如果没用发现语法错误,不会输出任何内容。

$ sudo postfix check  

使用 netstat 来验证 postfix 是否正在监听 25 端口。

$ netstat -ant 
tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN 
tcp6 0 0 :::25  :::*  LISTEN 

查看Postfix的监听情况:

sudo netstat -lnpt

## 显示中有以下信息表示正常
tcp        0      0 0.0.0.0:25              0.0.0.0:*               LISTEN      2278/master  

查看端口的开放情况

sudo nmap 192.168.1.17
常规配置参数
#邮箱总大小限制,单位字节, 0为不限制
mailbox_size_limit = 0

#附件大小,下面是50M
message_size_limit = 52428800

#启动sasl 验证
smtpd_sasl_auth_enable = yes
退信模板

默认是有英文模板的,但如果改成中文的,当然需要自己配置一个模板。

sudo nano /etc/postfix/main.cf

这是postfix的主要配置文件,在这个配置文件中添加一行内容,配置模板内容:

bounce_template_file = /etc/postfix/bounce.cf

根据上面的配置,建立一个模板内容,可以配置4种模板,分别为:

  1. 失败退信(failure_template):投递失败。
  2. 延时退信( delay_template):如果发信时发生了临时性错误,系统会延时一定的时间再次尝试重发,直到在队列中的时间超过了maximal_queue_litetime就从队形中删除了。
  3. 成功退信(success_template):发信成功了,给发件人一封通知信。
  4. verify退信(ver-ify_template):对收件人验证不成功的退信
    这里我主要配置一个失败的退信:
failure_template=<<EOF
Charset: utf-8,gb2312
From: =?utf-8?B?6YKu566x566h55CG5ZGY?=<Admin@zjp.com>
Subject: =?utf-8?B?6YCA5L+h6YCa55+l?=
Postmaster-Subject:Postmaster Copy: Undelivered Mail

退信通知: 您好,很抱歉您发送的邮件被系统退回,相关信息如下
退信原因: 您投递的邮件地址不存在,所以您的邮件不能准确送达。
解决方案:1.请检查输入的地址是否有误;2.联系收件方确认邮箱是否存在过期、被禁用或冻结等情况。
EOF

这里的failure_template表示什么模板,模板内容在<<EOF和EOF之间。
charset配置字符集。
下面关键的内容来了,From和Subject如果配置中文的话,需要配置为base64,语法是:
=?应该的字符集?B?中文的base64?=
=?表示开头,?=表示结尾

使用doveadm产生加密密码:

doveadm pw - s SHA512 - CRYPT 是 Dovecot 提供的命令行工具,用于生成使用 SHA512 - CRYPT 算法加密的密码。这通常用于在配置文件(如 dovecot - sql.conf.ext)中设置用户的密码。

以下是使用 doveadm pw - s SHA512 - CRYPT 的基本用法:

doveadm pw -s SHA512-CRYPT

运行此命令后,系统会提示你输入要加密的密码,然后生成相应的 SHA256-CRYPT 加密后的密码。示例:

Enter new password: [your-password]
{SHA256-CRYPT}$6$rounds=5000$SALT$ENCRYPTED_PASSWORD
  • 在这个示例中:
  • { SHA256 - CRYPT } 表示使用 SHA256 - CRYPT 算法。
  • ENCRYPTED_PASSWORD 是经过加密的密码。
  • 你可以将生成的 { SHA512 - CRYPT } 6 6 6rounds = 5000 S A L T SALT SALTENCRYPTED_PASSWORD 部分复制到配置文件中,以配置 Dovecot 使用此密码进行用户认证。

请注意,实际的 salt 和密码值会根据每次生成而不同,以提高密码的安全性。

## 示例:
doveadm pw -s SHA512-CRYPT
## 将生成如下密码:
mayi@speedxserver:~$ sudo doveadm pw -s SHA512-CRYPT
doveadm(mayi): Error: net_connect_unix(/var/run/dovecot/stats-writer) failed: Permission denied
Enter new password: <password>
Retype new password: <password>
{SHA256-CRYPT}$6$KH42OaxILaLRqBbZ$ept8sWlQXrj9RZrWriA7FZo.VBjQqskSko9lpWzSu2.
配置Mysql
  1. 创建数据库
## 本示例的root密码为:<mydbpasswd>
mysql -u root -p <mydbpasswd>

## 创建数据库servermail
create database mydatabase;

## 添加用户并授权
CREATE USER 'user'@'localhost' IDENTIFIED BY 'mydbpasswd';
GRANT ALL ON mydatabase.* TO 'user'@'localhost';
FLUSH PRIVILEGES;

## 切换到刚建的数据库
USE mydatabase;
  1. 创建数据表
-- 定义系统用户账号信息,用于登录验证
CREATE TABLE users (
  	id INT PRIMARY KEY AUTO_INCREMENT,
    user VARCHAR(128) NOT NULL,
    password VARCHAR(255) NOT NULL,
    domain VARCHAR(255) NOT NULL DEFAULT "speedxcn.com",
    source VARCHAR(255) NOT NULL DEFAULT CONCAT_WS("@", user, domain),
    home VARCHAR(255) NOT NULL,
    active BOOLEAN DEFAULT TRUE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO users (user, password, home,source, active) VALUES
   ("admin", "$6$kgaDSTx91flCbn6R$w2y6zTG5gjMA2dy/JsDIMjcnCPX5nZ14ENoMsL4FLhcCEbaWsOW6yvNgOtaBA54Ynr7BIwmRXK0PtsxQAtGiL/", CONCAT_WS("/", "/var/mail/mail.myexample.com",user), CONCAT_WS("@", user, domain), true);

-- 这个密码,不用多说了吧,就是之前介绍的工具生成的。--

-- 用于存储可接受的虚拟域的信息。--
CREATE TABLE domains (
    id INT PRIMARY KEY AUTO_INCREMENT,
    domain VARCHAR(255) NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO domains (domain) VALUES ('example.com');
配置说明main.cf
sudo groupadd -g 5000 adminmail
sudo useradd -m -g adminmail -u 5000 -d /home/vmail -s /bin/bash adminmail

## 设置邮箱本地主机名
sudo postconf -e 'myhostname = mail.example.com'
## 设置邮名
sudo postconf -e 'mydomain = example.com'
## 设置发送者的身份
sudo postconf -e 'myorigin = $mydomain'
## 监听所有接口
sudo postconf -e 'inet_interfaces = all'

## 设置用户邮箱的位置。因为已经设置了Dovecot,此处不无需设置
# sudo postconf -e 'home_mailbox=/var/mail/%d/%n'

## 指定 Dovecot 用于用户的本地邮箱的传输代理。通过Dovecot实现
## 当使用 LMTP 时,投递到本地邮箱的邮件将通过 Dovecot 的 LMTP 服务器进行处理,
## 而不是使用 mailbox_transport 指定的传输代理。
sudo postconf -e 'mailbox_transport = lmtp:unix:private/dovecot-lmtp'

## 指定接收邮件的域
sudo postconf -e 'mydestination = $myhostname localhost.$mydomain localhost $mydomain'


## 用于定义邮件的本地别名。在这里,/etc/postfix/aliases 中包含了本地邮件地址的别名映射,
## 这通常用于将邮件发送到系统中的本地用户或邮件别名。
sudo postconf -e 'alias_maps = hash:/etc/postfix/aliases' 

## 指定了一个正则表达式文件,用于定义邮件头部的检查规则。在这里,
## /etc/postfix/header_checks 包含了一组正则表达式规则,用于匹配和过滤邮件的头部信息,
## 实现内容过滤和检查。
# sudo postconf -e 'header_checks = regexp:/etc/postfix/header_checks' 

## 用于定义邮件的传输方式。在这里,/etc/postfix/transport 中包含了一组规则,
## 指定了不同域名或地址的邮件应该如何被路由和传输,例如通过不同的邮件传输代理(MTA)。
# sudo postconf -e 'transport_maps = hash:/etc/postfix/transport'      


##定义接受虚拟用户邮件的邮件域列表
# sudo postconf -e 'virtual_mailbox_domains = 'speedxcn.com'
sudo postconf -e 'virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf'

## 指定了虚拟邮箱的基本存储路径,虚拟用户的实际存储路径是基于这个基本路径的
## 启用了Dovecot,此外无需设置
## sudo postconf -e 'virtual_mailbox_base = /var/mail'

## 指定虚拟用户和实际存储路径的映射关系,通过Dovecot实现
## 在dovecot中要开启sevice lmtp服务,配置正确的套接字方可实现通信。
sudo postconf -e 'virtual_mailbox_maps = lmtp:unix:private/dovecot-lmtp'
# sudo postconf -e 'virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf'

## 用于指定 Dovecot 用于投递虚拟用户邮箱的传输代理。通过Dovecot实现,这一步非常重要
sudo postconf -e 'virtual_transport = lmtp:unix:private/dovecot-lmtp'


## 将邮件地址映射到其他邮件地址,用于实现虚拟域和虚拟用户的功能。
## 实现虚拟用户到真实用户或邮箱地址的映射或是转发
# sudo postconf -e 'virtual_alias_maps= hash:/etc/postfix/virtual'
## 数据库定义方法:
# sudo postconf -e 'virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf'

## 用户的UID号和GID号
sudo postconf -e 'virtual_uid_maps = static:5000'
sudo postconf -e 'virtual_gid_maps = static:5000'
# sudo postconf -e 'virtual_uid_maps = mysql:/etc/postfix/mysql-virtual-uid-maps.cf'
# sudo postconf -e 'virtual_gid_maps = mysql:/etc/postfix/mysql-virtual-gid-maps.cf'

## 以允许合法用户发送邮件
smtpd_recipient_restrictions =
  permit_mynetworks,
  permit_sasl_authenticated,
  reject_unauth_destination,
  check_recipient_access mysql:/etc/postfix/mysql-recipient-access.cf

完整的配置示例如下:
# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname
myhostname = mail.example.com
mydomain = example.com
alias_maps = hash:/etc/aliases
#alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = mail.example.com localhost.example.com localhost example.com

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 3.6 on
# fresh installs.
compatibility_level = 3.6

## 启用SASL认证服务
## 这个参数启用了 SMTP 身份验证。
smtpd_sasl_auth_enable = yes
## 设置 SASL 库的类型。在这里,它被设置为 cyrus,表示使用 Cyrus SASL。
# smtpd_sasl_type = cyrus
## 指定dovecot认证类型
smtpd_sasl_type = dovecot
## 指定认证路径
smtpd_sasl_path = private/auth
## 指定 Postfix 服务器的本地域
smtpd_sasl_local_domain = $mydomain
## 设置 SASL 的安全选项,这里禁用了匿名登录,即 noanonymous。
smtpd_sasl_security_options = noanonymous
## 该参数启用了对于一些不太规范的 SASL 客户端的兼容性处理。
broken_sasl_auth_clients = yes
## 限制每个客户端在60秒内只能发送30封邮件
smtpd_client_message_rate_limit = 30

# TLS parameters
## 系统默认的证书只能用于测试环境,生产环境不可使用
## smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
## smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_cert_file=/etc/letsencrypt/live/mail.example.com/fullchain.pem
smtpd_tls_key_file=/etc/letsencrypt/live/mail.example.com/privkey.pem
smtpd_use_tls = yes
smtpd_tls_auth_only = yes
smtpd_tls_protocols = TLSv1.2  # 适用于现代客户端
smtpd_tls_ciphers = high

smtp_tls_CApath=/etc/ssl/certs
smtp_tls_security_level=may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination


relayhost = 
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all

## dovecot代理设置
#smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination

## 当邮件发送错误时的退信模板
bounce_template_file = /etc/postfix/bounce.cf

## 虚拟用户相关设置
# virtual_mailbox_base = /var/mail/virtual/
# virtual_mailbox_domains = speedxcn.com
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf

## 指定虚拟用户和实际存储路径的映射关系,通过Dovecot实现,
## 在dovecot中要开启sevice lmtp服务,配置正确的套接字方可实现通信。
virtual_mailbox_maps = lmtp:unix:private/dovecot-lmtp
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf

#virtual_uid_maps = mysql:/etc/postfix/mysql-virtual-uid-maps.cf
#virtual_gid_maps = mysql:/etc/postfix/mysql-virtual-gid-maps.cf

## 邮件传输控制
## 用于指定 Dovecot 用于投递用户的本地邮箱的传输代理
mailbox_transport = lmtp:unix:private/dovecot-lmtp
## 用于指定 Dovecot 用于投递虚拟用户邮箱的传输代理
virtual_transport = lmtp:unix:private/dovecot-lmtp
## 用于指定 Dovecot 投递邮件时使用的 UID(用户标识)
virtual_uid_maps = static:5000
##  GID(组标识)
virtual_gid_maps = static:5000

## 配置OpenDKIM、DMARC服务
# Milter configuration
milter_default_action = accept
milter_protocol = 6
smtpd_milters = local:opendkim/opendkim.sock,local:opendmarc/opendmarc.sock
non_smtpd_milters = $smtpd_milters

## 添加以下内容, 这告诉 Postfix 使用 SPF 验证服务。
policyd-spf_time_limit = 3600
smtpd_recipient_restrictions =
   permit_mynetworks,
   permit_sasl_authenticated,
   reject_unauth_destination,
   check_policy_service unix:private/policyd-spf

## 配置日志
maillog_file = /var/log/mail.log
home_mailbox = /var/mail/mail.speedxcn.com/%n/mail

Postfix配置示例文件:

virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf

sudo nano mysql-virtual-alias-maps.cf

user = user
password = <mypassword>
hosts = 127.0.0.1
dbname = mydatabase
query = SELECT user as destination FROM users WHERE source='%s'

## 这里的source是指终端指定的邮件地址。当这个source与配置的用户名不一致时,这个配置文件一定要
## 存在。也就是说,当客户端指定的收件的地址为:usr@example.com时,而users表里的user名为"usr"
## 这时就需要把usr@example.com的邮件转发到用户usr,所以这里要有这个虚拟转发的配置文件存在。

## query:根据源地址检索目标地址的查询。在这里,它将返回与源地址相关联的目标地址。

virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf

sudo nano /etc/postfix/mysql-virtual-mailbox-maps.cf
## 编辑Postfix配置文件: 打开Postfix的主配置文件 /etc/postfix/main.cf 并添加以下行:
user = user
password = <mypassword>
hosts = 127.0.0.1
dbname = mydatabase
query = SELECT home FROM users WHERE username='%s'

## 重新编译
postmap /etc/postfix/mysql-virtual-mailbox-maps.cf

virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf

sudo nano /etc/postfix/mysql-virtual-mailbox-domains.cf
## /etc/postfix/mysql-virtual-mailbox-domains.cf
user = user
password = <mypassword>
hosts = 127.0.0.1
dbname = mydatabase
query = SELECT 1 FROM domains WHERE domain='%s'

## 重新编译
postmap /etc/postfix/mysql-virtual-mailbox-domains.cf

header_checks配置示例

  • 作用:header_checks 用于定义邮件头部的正则表达式规则,以实现内容过滤和检查。
  • 用法: 通过指定一个包含正则表达式规则的文件,匹配规则会检查邮件的头部内容。
  • 示例:header_checks = regexp:/etc/postfix/header_checks
/^Subject: .*viagra/ 
/^From: .*@example\.com/

这个示例包含两个规则,第一个规则检查邮件主题是否包含 “viagra”,如果是则拒绝该邮件。第二个规则检查发件人是否来自 example.com,如果是则直接丢弃该邮件。

Postfix测试

如果不是通过mailutils安装的Postfix, 则要进行安装邮件测试工具:

sudo apt-get install mailutils
默认发送邮件测试(root@example.com)
echo "This is the body of the email" | mail -s "This is the subject line" <你的163邮箱或其它邮箱>
转发系统邮件

root通过运行测试发送电子邮件是否有效:

echo "This is the body of the email" | mail -s "This is the subject line" root

您应该会在您的电子邮件地址收到电子邮件。如果它不在那里,请检查您的垃圾邮件文件夹。
在此步骤中,您设置将系统生成的消息转发到您的电子邮件地址。您现在将启用消息加密,这样您的服务器发送的所有电子邮件都不会在传输过程中受到篡改,并且会被视为更合法。

指定身份发送邮件
echo "This is a test email body" | mail -s "Test Email" -a "From: admin@example.com" <你的QQ邮箱>

在这个例子中,我们使用 echo 命令来创建邮件正文,然后通过管道将其传递给 mail 命令。选项 -s 用于指定邮件主题,而 -a 用于指定发件人地址。
确保替换以下部分为实际值:

  • “This is a test email body”:邮件正文。
  • “Test Email”:邮件主题。
  • admin@mail.example.com:发件人地址。
  • <你的QQ邮箱>:收件人地址。

Dovecot

相关操作命令
  1. 查看配置参数
doveconf
  1. 查看特定配置参数的值
doveconf mail_location
  1. 查看配置的有效性
doveconf -n
  1. 以指定的参数测试参数的有效性(并没有真正更改配置文件)
doveconf -n -c /etc/dovecot/dovecot.conf mail_location=maildir:~/Maildir
Dovecot的安装
sudo apt install dovecot-core dovecot-imapd dovecot-lmtpd dovecot-mysql dovecot-pop3d dovecot-sieve dovecot-managesieved
配置dovecot.conf

创建管理用户:

sudo mkdir -p /var/mail/mail.example.com
sudo groupadd -g 5000 adminmail
sudo useradd -r -g adminmail -u 5000 adminmail -d /var/mail/mail.example.com -c "virtual mail user"
sudo chown -R adminmail:adminmail /var/mail/mail.example.com
sudo chown -R adminmail:dovecot /etc/dovecot
sudo chmod -R o-rwx /etc/dovecot

# 然后将 dovecot 添加到 mail 组中,以便 Dovecot 可以读取收件箱。
sudo adduser dovecot mail
配置数据库来管理用户认证

打开/etc/dovecot/dovecot.conf,添加以下设置

sudo nano /etc/dovecot/dovecot.conf

# "doveconf -n" command gives a clean output of the changed settings. Use it
# instead of copy&pasting files when posting to the Dovecot mailing list.

protocols = imap pop3 lmtp sieve

# Enable installed protocols
!include_try /usr/share/dovecot/protocols.d/*.protocol

listen = *, ::

# Base directory where to store runtime data.
#base_dir = /var/run/dovecot/

dict {
  #quota = mysql:/etc/dovecot/dovecot-dict-sql.conf.ext
}

# Most of the actual configuration gets included below. The filenames are
# first sorted by their ASCII value and parsed in that order. The 00-prefixes
# in filenames are intended to make it easier to understand the ordering.
!include conf.d/*.conf

# A config file can also tried to be included without giving an error if
# it's not found:
!include_try local.conf

##---自定义设置 ---
#mail_location = maildir:/var/mail/%d/%n

disable_plaintext_auth = no
mail_privileged_group = mail

passdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}

userdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext
}

plugin {
  autocreate = Trash
  autocreate2 = Sent
  autosubscribe = Trash
  autosubscribe2 = Sent
}

创建并编辑Mysql认证配置文件:

sudo nano /etc/dovecot/dovecot-sql.conf.ext

## /etc/dovecot/dovecot-sql.conf.ext
driver = mysql
connect = host=127.0.0.1 dbname=mydatabase user=user password=mypasswd
default_pass_scheme = SHA512-CRYPT
password_query = SELECT user,password,domain FROM users WHERE user = '%u' AND active = true
user_query = SELECT home, 5000 AS uid, 5000 AS gid FROM users WHERE user = '%u'

##关于通配符
%u = 匹配完全的 user@domain
%n = 匹配 user@domain 中的user
%d = 匹配 user@domain 中的domain

请确保替换 ‘hashedpassword’ 为实际的哈希密码。你可以使用以下方式生成哈希密码:

doveadm pw -s SHA512-CRYPT

完整配置如下 :

# If you prefer to use the sql userdb module, you'll want to add fields
# for home, uid, and gid. Here is an example table:
#
# CREATE TABLE users (
#     username VARCHAR(128) NOT NULL,
#     domain VARCHAR(128) NOT NULL,
#     password VARCHAR(64) NOT NULL,
#     home VARCHAR(255) NOT NULL,
#     uid INTEGER NOT NULL,
#     gid INTEGER NOT NULL,
#     active CHAR(1) DEFAULT 'Y' NOT NULL
# );

# Database driver: mysql, pgsql, sqlite
driver = mysql

# Database connection string. This is driver-specific setting.
#
# HA / round-robin load-balancing is supported by giving multiple host
# settings, like: host=sql1.host.org host=sql2.host.org
#
# pgsql:
#   For available options, see the PostgreSQL documentation for the
#   PQconnectdb function of libpq.
#   Use maxconns=n (default 5) to change how many connections Dovecot can
#   create to pgsql.
#
#connect =
connect = host=localhost dbname=mydatabase user=user password=mypasswd
# Default password scheme.
#
# List of supported schemes is in
# http://wiki2.dovecot.org/Authentication/PasswordSchemes
#
default_pass_scheme = SHA512-CRYPT

password_query = SELECT user,password,domain FROM users WHERE user = '%u' AND active = true
user_query = SELECT home, 5000 AS uid, 5000 AS gid FROM users WHERE user = '%u'

主配置文件
sudo nano /etc/dovecot/conf.d/10-mail.conf

# There are a few special variables you can use, eg.:
#
#   %u - username
#   %n - user part in user@domain, same as %u if there's no domain
#   %d - domain part in user@domain, empty if there's no domain
#   %h - home directory
#
# See doc/wiki/Variables.txt for full list. Some examples:
#
#   mail_location = maildir:~/Maildir
#   mail_location = mbox:~/mail:INBOX=/var/mail/%u
#   mail_location = mbox:/var/mail/%d/%1n/%n:INDEX=/var/indexes/%d/%1n/%n
#
mail_home = /var/mail/mail.example.co/%n
mail_location = maildir:~/mail
#mail_location = maildir:/var/mail/%u
# <doc/wiki/MailLocation.txt>
#
# mail_location = mbox:~/mail:INBOX=/var/mail/%u

namespace inbox {
  # Namespace type: private, shared or public
  type = private

  # Hierarchy separator to use. You should use the same separator for all
  # namespaces or some clients get confused. '/' is usually a good one.
  # The default however depends on the underlying mail storage format.
  separator = / 

  # Prefix required to access this namespace. This needs to be different for
  # all namespaces. For example "Public/".
  prefix = INBOX/ 

  # Physical location of the mailbox. This is in same format as
  # mail_location, which is also the default for it.
  #location =

  # There can be only one INBOX, and this setting defines which namespace
  # has it.
  inbox = yes

  mailbox Trash {
    auto = subscribe
    special_use = \Trash
  }
  mailbox Drafts {
    auto = subscribe
    special_use = \Drafts
  }
  mailbox Sent {
    auto = subscribe
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    auto = subscribe
    special_use = \Sent
  }
  mailbox Spam {
    auto = subscribe
    special_use = \Junk
  }
}

# Example shared namespace configuration
#namespace {
  #type = shared
  #separator = /

  # Mailboxes are visible under "shared/user@domain/"
  # %%n, %%d and %%u are expanded to the destination user.
  #prefix = shared/%%u/

  # Mail location for other users' mailboxes. Note that %variables and ~/
  # expands to the logged in user's data. %%n, %%d, %%u and %%h expand to the
  # destination user's data.
  #location = maildir:%%h/Maildir:INDEX=~/Maildir/shared/%%u

  # Use the default namespace for saving subscriptions.
  #subscriptions = no

  # List the shared/ namespace only if there are visible shared mailboxes.
  #list = children
#}

mail_uid = 5000
mail_gid = 5000

# Group to enable temporarily for privileged operations. Currently this is
# used only with INBOX when either its initial creation or dotlocking fails.
# Typically this is set to "mail" to give access to /var/mail.
mail_privileged_group = mail



# UNIX socket path to master authentication server to find users.
# This is used by imap (for shared users) and lda.
#auth_socket_path = /var/run/dovecot/auth-userdb

# Directory where to look up mail plugins.
#mail_plugin_dir = /usr/lib/dovecot/modules

# Space separated list of plugins to load for all services. Plugins specific to
# IMAP, LDA, etc. are added to this list in their own .conf files.
# mail_plugins = autocreate 

protocol !indexer-worker {
  # If folder vsize calculation requires opening more than this many mails from
  # disk (i.e. mail sizes aren't in cache already), return failure and finish
  # the calculation via indexer process. Disabled by default. This setting must
  # be 0 for indexer-worker processes.
  #mail_vsize_bg_after_count = 0
}
监听器配置

/etc/dovecot/conf.d/10-master.conf
完整的示例如下:

sudo nano /etc/dovecot/conf.d/10-master.conf

#default_process_limit = 100
#default_client_limit = 1000

# Default VSZ (virtual memory size) limit for service processes. This is mainly
# intended to catch and kill processes that leak memory before they eat up
# everything.
#default_vsz_limit = 256M

# Login user is internally used by login processes. This is the most untrusted
# user in Dovecot system. It shouldn't have access to anything at all.
#default_login_user = dovenull

# Internal user is used by unprivileged processes. It should be separate from
# login user, so that login processes can't disturb other processes.
#default_internal_user = dovecot

service imap-login {
  inet_listener imap {
    #port = 143
    #禁用未加密的imap连接
    port = 0
  }

  inet_listener imaps {
    address = *    
    port = 993
    ssl = yes
  }

  # Number of connections to handle before starting a new process. Typically
  # the only useful values are 0 (unlimited) or 1. 1 is more secure, but 0
  # is faster. <doc/wiki/LoginProcess.txt>
  #service_count = 1

  # Number of processes to always keep waiting for more connections.
  #process_min_avail = 0

  # If you set service_count=0, you probably need to grow this.
  #vsz_limit = $default_vsz_limit
}

service pop3-login {
  inet_listener pop3 {
    #port = 110
    # 禁用未加密的接口
    port = 0
  }

  inet_listener pop3s {
    address = *
    port = 995
    ssl = yes
  }
}

service submission-login {
  inet_listener submission {
    port = 587
  }
}

service lmtp {
  unix_listener /var/spool/postfix/private/dovecot-lmtp {
    group = postfix
    mode = 0600
    user = postfix
  }
  
  # Create inet listener only if you can't use the above UNIX socket
  #inet_listener lmtp {
    # Avoid making LMTP visible for the entire internet
    #address =
    #port = 
  #}
}

service imap {
  # Most of the memory goes to mmap()ing files. You may need to increase this
  # limit if you have huge mailboxes.
  #vsz_limit = $default_vsz_limit

  # Max. number of IMAP processes (connections)
  process_limit = 1024
}

service pop3 {
  # Max. number of POP3 processes (connections)
  process_limit = 1024
}

service submission {
  # Max. number of SMTP Submission processes (connections)
  process_limit = 1024
}

service auth {
  # auth_socket_path points to this userdb socket by default. It's typically
  # used by dovecot-lda, doveadm, possibly imap process, etc. Users that have
  # full permissions to this socket are able to get a list of all usernames and
  # get the results of everyone's userdb lookups.
  #
  # The default 0666 mode allows anyone to connect to the socket, but the
  # userdb lookups will succeed only if the userdb returns an "uid" field that
  # matches the caller process's UID. Also if caller's uid or gid matches the
  # socket's uid or gid the lookup succeeds. Anything else causes a failure.
  #
  # To give the caller full permissions to lookup all users, set the mode to
  # something else than 0666 and Dovecot lets the kernel enforce the
  # permissions (e.g. 0777 allows everyone full permissions).
  unix_listener auth-userdb {
    mode = 0666
    user = adminmail
    group = adminmail 
  }

  # Postfix smtp-auth
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
    user = postfix
    group = postfix
  }

  # Auth process is run as this user.
  #user = $default_internal_user
  user = dovecot
}

service auth-worker {
  # Auth worker process is run as root by default, so that it can access
  # /etc/shadow. If this isn't necessary, the user should be changed to
  # $default_internal_user.
  #user = root
   user = adminmail
}

service dict {
  # If dict proxy is used, mail processes should have access to its socket.
  # For example: mode=0660, group=vmail and global mail_access_groups=vmail
  unix_listener dict {
    mode = 0600
    user = adminmail 
    group = adminmail
  }
}

SSL/TLS

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

# 启用 SSL/TLS
ssl = required

# SSL/TLS 使用的证书和私钥文件路径
ssl_cert = </etc/letsencrypt/live/www.example.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/www.example.com/privkey.pem

# 配置支持的加密协议和密码套件
ssl_protocols = TLSv1.2 TLSv1.3
ssl_cipher_list = TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384

# 是否使用强制加密,如果设置为 yes,只有支持 SSL/TLS 的连接将被接受
ssl_require_ciphers = yes
ssl_ciphers = HIGH

# 是否启用 SSL/TLS session 缓存
ssl_session_cache = built-in:1000
ssl_session_timeout = 1 hour

# 配置 Diffie-Hellman 参数的长度,用于支持 Perfect Forward Secrecy (PFS)。
ssl_dh_parameters_length = 2048

# 是否启用 SSL/TLS 的客户端证书验证
# ssl_client_require_cert = no
# ssl_client_cert_file = </etc/dovecot/client.pem
# ssl_client_key_file = </etc/dovecot/client.key
验证 SSL 连接
  • 你可以使用 OpenSSL 工具验证 Dovecot 是否正确配置了 SSL。例如,使用以下命令连接到 Dovecot 服务器:
openssl s_client -connect your_mail_server:993

确保连接成功,且 SSL 证书链和信息正确显示。

认证配置

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

sudo nano /etc/dovecot/conf.d/10-auth.conf


# Disable LOGIN command and all other plaintext authentications unless
# SSL/TLS is used (LOGINDISABLED capability). Note that if the remote IP
# matches the local IP (ie. you're connecting from the same computer), the
# connection is considered secure and plaintext authentication is allowed.
# See also ssl=required setting.
disable_plaintext_auth = no

# Authentication cache size (e.g. 10M). 0 means it's disabled. Note that
# bsdauth and PAM require cache_key to be set for caching to be used.
auth_cache_size = 1M
# Time to live for cached data. After TTL expires the cached record is no
# longer used, *except* if the main database lookup returns internal failure.
# We also try to handle password changes automatically: If user's previous
# authentication was successful, but this one wasn't, the cache isn't used.
# For now this works only with plaintext authentication.
auth_cache_ttl = 1 hour
# TTL for negative hits (user not found, password mismatch).
# 0 disables caching them completely.
auth_cache_negative_ttl = 1 hour
# List of allowed characters in username. If the user-given username contains
# a character not listed in here, the login automatically fails. This is just
# an extra check to make sure user can't exploit any potential quote escaping
# vulnerabilities with SQL/LDAP databases. If you want to allow all characters,
# set this value to empty.
auth_username_chars = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890.-_@
auth_worker_max_count = 30

auth_mechanisms = plain login

# <doc/wiki/PasswordDatabase.txt>
#
# User database specifies where mails are located and what user/group IDs
# own them. For single-UID configuration use "static" userdb.
#
# <doc/wiki/UserDatabase.txt>

## 下面的认证只能打开一个,不然会冲突。这里我们采用mysql来对用户进行认证。
#!include auth-deny.conf.ext
#!include auth-master.conf.ext

#!include auth-system.conf.ext
!include auth-sql.conf.ext
#!include auth-ldap.conf.ext
#!include auth-passwdfile.conf.ext
#!include auth-checkpassword.conf.ext
#!include auth-static.conf.ext

服务的启用

sudo systemctl enable dovecot.service

## 其它命令
ssudoudo systemctl start dovecot.service
sudo systemctl stop dovecot.service

## 查看服务状态
sudo systemctl status dovecot.service

OK,大功告成。你现在可以任意邮件终端来连接到我们的服务器了。是不是很爽。什么IOS上的,Android上的,win上的,mac上的,都可以。快去试试吧。

  • 17
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
要在Ubuntu搭建Teamspeak 3服务器,可以按以下步骤进行操作: 1. 首先,确保你的Ubuntu系统已经更新到最新版本,并安装了必要的依赖项。可以使用以下命令进行更新和安装: ``` sudo apt update sudo apt upgrade sudo apt install wget tar ``` 2. 接下来,创建一个新的用户来运行Teamspeak 3服务器。使用以下命令创建一个名为"teamspeak"的新用户: ``` sudo adduser teamspeak ``` 3. 切换到新创建的用户并进入其主目录: ``` su - teamspeak cd ~ ``` 4. 下载Teamspeak 3服务器的最新版本。可以从Teamspeak官方网站上找到下载链接,或者使用以下命令下载最新版本: ``` wget https://files.teamspeak-services.com/releases/server/3.13.6/teamspeak3-server_linux_amd64-3.13.6.tar.bz2 ``` 5. 解压下载的文件: ``` tar -xvf teamspeak3-server_linux_amd64-3.13.6.tar.bz2 ``` 6. 进入解压后的目录: ``` cd teamspeak3-server_linux_amd64 ``` 7. 启动Teamspeak 3服务器,并接受使用条款: ``` ./ts3server_startscript.sh start ``` 8. 在首次启动时,会显示一些许可协议条款。按照提示输入"yes"以接受条款,并设置管理员密码。 9. Teamspeak 3服务器已经成功搭建。你可以使用Teamspeak客户端连接到服务器并进行配置。 请注意,为了让Teamspeak 3服务器在系统启动时自动启动,你可以将启动脚本添加到系统服务中。这样,在每次系统启动时,Teamspeak 3服务器就会自动启动。 希望以上步骤对你有所帮助!如有任何疑问,请随时向我提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码蚁先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值