Postfix+PostfixAdminでマルチドメイン対応のメールサーバーを作成する for RockyLinux 9.x

メールサーバーは、パブリッククラウドのSaaSサービスを利用する方が圧倒的に楽です。メールサーバーの面倒を見るのはしんどい（特に相手にメールが届いていないとかの個別の問い合わせ...）のですが、それでもオンプレミスでメールサーバーを構築する必用がある場合があります。今回は、RockyLinux8.xを利用して、Posftfix Adminを利用したマルチドメインに対応したメールサーバーを構築します。
Dovecot2.3での実装となります。


### 予め以下のソフトウェアをインストールしておいてください

- OpenSSL
- Apache2.4
- PHP8.x
- MariaDB
- PostgreSQL(SASLがどうしてもPGSQLライブラリが必要となるため）

## 1.ユーザーを作成しUIDとGIDを確認する

```:bash
useradd mailbox
cat /etc/passwd | grep mailbox
```

## 2. SASLを導入する

既存のパッケージを消す

```
dnf remove cyrus-sasl
dnf install libdb-devel
```


```
cd /usr/local/src
wget https://github.com/cyrusimap/cyrus-sasl/releases/download/cyrus-sasl-2.1.28/cyrus-sasl-2.1.28.tar.gz
tar xvzf cyrus-sasl-2.1.28.tar.gz
cd cyrus-sasl-2.1.28/
./configure \
--enable-sql \
--with-mysql=/usr/local/mysql \
--with-pgsql=/usr/local/pgsql \
--enable-login=yes \
--with-authdaemond \
--enable-plain \
--with-openssl=/usr/local/ssl \
--with-pam \
--enable-cram \
--with-des=no \
--enable-digest

make -j 6
make install
```

サービス起動出来るようにする

```
cat > /usr/lib/systemd/system/saslauthd.service << EOF

[Unit]
Description=SASL authentication daemon.
After=syslog.target

[Service]
Type=forking
Environment="PIDFile=/run/saslauthd/saslauthd.pid"
Environment="SOCKETDIR=/run/saslauthd"
Environment="MECH=pam"
Environment="FLAGS="


#EnvironmentFile=/etc/sysconfig/saslauthd
#ExecStart=/usr/local/sbin/saslauthd -m /run -a pam
ExecStart=/usr/local/sbin/saslauthd -m \$SOCKETDIR -a \$MECH \$FLAGS
RuntimeDirectory=saslauthd

[Install]
WantedBy=multi-user.target

EOF
```

設定ファイルを入れ、サービスを起動する

```
mkdir -p /usr/local/lib/sasl2/

cat > /usr/local/lib/sasl2/smtpd.conf << EOF
pwcheck_method: auxprop
auxprop_plugin: sql
allowanonymouslogin: no
allowplaintext: yes
mech_list: PLAIN LOGIN CRAM-MD5 DIGEST-MD5 #多分CRAM-MD5 DIGEST-MD5はいらない いらない
sql_engine: mysql
sql_hostnames: localhost
sql_user: postfixadminのデーターベースのユーザー
sql_passwd: ↑のパスワード
sql_database: postfixadminのデーターベース名
sql_statement: SELECT password FROM mailbox WHERE username = '%u@%r' AND active = '1'

EOF

mkdir -p /var/state/saslauthd
chmod 666 /var/state/saslauthd

systemctl enable saslauthd
systemctl start saslauthd
```

## 3.dovecotを導入する

最初に、PAM、OpenLdapをインストールしておく

```
dnf install pam-devel
dnf install openldap-devel #ldap.hがない場合びるどにしっぱいすることがあ
```

ユーザーを作成する

```
useradd dovecot
```

dovecotをインストールする

```:bash:
cd /usr/local/src
wget https://www.dovecot.org/releases/2.4/dovecot-2.4.0.tar.gz
tar xvzf dovecot-2.4.0.tar.gz
cd dovecot-2.4.0

#OpenSSLのライブラリがうまく見えないときはこちらを実行
export PKG_CONFIG_PATH=/usr/local/python-3.13.1/lib/pkgconfig:/usr/local/ssl/lib/pkgconfig:/usr/local/lib/pkgconfig
#export LD_RUN_PATH=/usr/local/lib64:/usr/local/lib:/usr/local/ssl/lib:/usr/lib:/usr/lib64
 ln -s /usr/local/ssl/lib/libcrypto.so.3 /usr/local/lib/libcrypto.so.3

./configure \
--with-pam \
--with-shadow \
--with-sql=yes \
--with-pgsql \
--with-mysql \
--with-zlib \
--with-ssl=openssl \
--without-icu \
--with-ssldir=/usr/local/ssl

make -j 6
make install
```

サービスの設定行う

```
cat > /usr/lib/systemd/system/dovecot.service << EOF
[Unit]
Description=Dovecot IMAP/POP3 email server
After=local-fs.target network.target network-online.target

[Service]
Type=simple
#ExecStartPre=/usr/libexec/dovecot/prestartscript
ExecStart=/usr/local/sbin/dovecot -F
ExecReload=/bin/kill -HUP \$MAINPID
PrivateTmp=true
NonBlocking=yes

[Install]
WantedBy=multi-user.target

EOF
```

設定ファイルを用意する

```
mkdir -p /usr/local/etc/dovecot
mkdir -p /usr/local/etc/dovecot/conf.d
cp /usr/local/share/doc/dovecot/example-config/dovecot.conf /usr/local/etc/dovecot/dovecot.conf
```

## 3.dovecotの設定を行う

#### dovecot.conf

```
vi /usr/local/etc/dovecot/dovecot.conf
```

```:/usr/local/etc/dovecot/dovecot.conf
###以下を変更###

#Dictionary server settings 配下を置き換える

---
##必要に応じて##
mail_debug = yes

#maillogにログを載せる
auth_verbose = yes
auth_debug = yes

default_login_user = mailbox
default_internal_user = mailbox

dict {
  #quota = mysql:/etc/dovecot/dovecot-dict-sql.conf.ext
  #expire = sqlite:/etc/dovecot/dovecot-dict-sql.conf.ext
  quotadict = mysql:/usr/local/etc/dovecot/dovecot-dict-sql.conf.ext
}

service stats {
    unix_listener stats-reader {
        user = mailbox
        group =mailbox
        mode = 0660
    }

    unix_listener stats-writer {
        user =mailbox
        group =mailbox
        mode = 0660
    }
}

#protocols = imap imaps pop3 pop3s
protocols = imap pop3 

!include conf.d/*.conf
!include_try local.conf
---
```

#### dovecot-dict-sql.conf.ext

ファイルをコピーして書き換える
Connectを追加
「table quota」 →　「table quota2」

```
cp /usr/local/share/doc/dovecot/example-config/dovecot-dict-sql.conf.ext /usr/local/etc/dovecot/
vi /usr/local/etc/dovecot/dovecot-dict-sql.conf.ext
```

```:dovecot-dict-sql.conf.ext
connect = host=localhost port=3306 dbname=postfix user=postfix password=postfix

map {
    pattern = priv/quota/storage
    table = quota2
    username_field = username
    value_field = bytes
}
map {
    pattern = priv/quota/messages
    table = quota2
    username_field = username
    value_field = messages
}
```

#### dovecot-sql.conf.ext

```
cp /usr/local/share/doc/dovecot/example-config/dovecot-sql.conf.ext /usr/local/etc/dovecot/conf.d/dovecot-sql.conf.ext
vi /usr/local/etc/dovecot/conf.d/dovecot-sql.conf.ext
```

```:dovecot-sql.conf.ext:
driver =  mysql
#MySQLの接続情報を入れる
connect = host=localhost port=3306 dbname=postfix user=postfix password=postfix

＃ここでは1003を指定している部分は、冒頭に作成したmailboxユーザーのUIDとGIDを入れる
default_pass_scheme = PLAIN
user_query = SELECT concat('/home/mailbox/', maildir) AS home, 1003 AS uid, 1003 AS gid, CONCAT('*:bytes=', CAST(mailbox.quota AS CHAR)) AS quota_rule FROM mailbox, domain WHERE username = '%u' AND mailbox.domain = domain.domain AND mailbox.active = '1' AND domain.active = '1'

password_query = SELECT password, 1003 AS userdb_uid, 1003 AS userdb_gid, CONCAT('*:bytes=', CAST(mailbox.quota AS CHAR)) AS userdb_quota_rule FROM mailbox, domain WHERE username = '%u' AND mailbox.domain = domain.domain AND mailbox.active = '1' AND domain.active = '1'

iterate_query = SELECT username FROM mailbox
```

権限設定を行う

```
chown root:dovecot /usr/local/etc/dovecot/dovecot-dict-sql.conf.ext
chown root:dovecot /usr/local/etc/dovecot/conf.d/dovecot-sql.conf.ext
chmod 644 /usr/local/etc/dovecot/dovecot-dict-sql.conf.ext
```

#### 10-mail.conf

```
cp /usr/local/share/doc/dovecot/example-config/conf.d/10-mail.conf /usr/local/etc/dovecot/conf.d/10-mail.conf
vi /usr/local/etc/dovecot/conf.d/10-mail.conf
```

```:10-mail.conf:
mail_location = maildir:/home/mailbox/%d/%n/
mail_access_groups = mailbox
#maildir_stat_dirs = yes

mail_uid = 1003
mail_gid = 1003

#first_valid_uid = 1002
#last_valid_uid  = 1002

#mail_privileged_group = mailbox
mail_plugins = quota
```

#### 10-auth.conf

```
cp /usr/local/share/doc/dovecot/example-config/conf.d/10-auth.conf /usr/local/etc/dovecot/conf.d/10-auth.conf
vi /usr/local/etc/dovecot/conf.d/10-auth.conf
```

```:10-auth.conf:
#↓Plainを無効にするか設定
disable_plaintext_auth = no
auth_mechanisms = cram-md5 plain login


#!include auth-system.conf.ext ←これをコメント入れる！
!include auth-sql.conf.ext     ←これをコメント外す！
#!include auth-ldap.conf.ext
```


#### 10-logging.conf

```
cp /usr/local/share/doc/dovecot/example-config/conf.d/10-logging.conf /usr/local/etc/dovecot/conf.d/10-logging.conf
vi /usr/local/etc/dovecot/conf.d/10-logging.conf
```

```:10-logging.conf:
#コメントを外す
log_path = syslog
```

#### 10-master.conf

```
cp /usr/local/share/doc/dovecot/example-config/conf.d/10-master.conf /usr/local/etc/dovecot/conf.d/10-master.conf
vi /usr/local/etc/dovecot/conf.d/10-master.conf
```

```:10-master.conf:
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 smtp-auth
  #コメントを外す
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
  }

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 = mailbox
    group = mailbox
  }
}

```


#### 10-ssl.conf

```
cp /usr/local/share/doc/dovecot/example-config/conf.d/10-ssl.conf /usr/local/etc/dovecot/conf.d/10-ssl.conf
vi /usr/local/etc/dovecot/conf.d/10-ssl.conf
```

```:10-ssl.conf:
#証明書ファイルパス "小なり｢<」" を消さないこと！
ssl = yes #コメントはすす
ssl_cert = </etc/letsencrypt/live/example.com/fullchain.pem
ssl_key = </etc/letsencrypt/live/example.com/privkey.pem
#ssl_ca = </usr/local/apache2/conf/cert/ルート証明書.cert
#ssl_verify_client_cert = yes
```

#### 20-imap.conf

```
cp /usr/local/share/doc/dovecot/example-config/conf.d/20-imap.conf  /usr/local/etc/dovecot/conf.d/20-imap.conf
vi /usr/local/etc/dovecot/conf.d/20-imap.conf
```

```:20-imap.conf:
#mail_plugins部分を書き換え
mail_plugins = quota imap_quota
```

#### 20-pop3.conf

```
cp /usr/local/share/doc/dovecot/example-config/conf.d/20-pop3.conf /usr/local/etc/dovecot/conf.d/20-pop3.conf
vi /usr/local/etc/dovecot/conf.d/20-pop3.conf
```

```:20-pop3.conf:
mail_plugins = quota
```

#### 90-quota.conf

```
cp /usr/local/share/doc/dovecot/example-config/conf.d/90-quota.conf /usr/local/etc/dovecot/conf.d/90-quota.conf
vi /usr/local/etc/dovecot/conf.d/90-quota.conf
```

```:90-quota.conf:
plugin {
  quota_rule = *:storage=1G:messages=100M
  quota_rule2 = Trash:storage=+100M
}

plugin {
  quota_warning = storage=95%% quota-warning 95 %u
  quota_warning2 = storage=80%% quota-warning 80 %u
}

plugin {
  quota = maildir:User quota
}
plugin {
  #追記
  quota2 = dict:User quota::proxy::quota
}

#追記
dict {
  quota = mysql:/usr/local/etc/dovecot/dovecot-dict-sql.conf.ext
}
````

#### 20-lmtp.conf

```
cp /usr/local/share/doc/dovecot/example-config/conf.d/20-lmtp.conf /usr/local/etc/dovecot/conf.d
vi /usr/local/etc/dovecot/conf.d/20-lmtp.conf
```

```:20-lmtp.conf:
protocol lmtp {
  postmaster_address = postmaster@exam.com
  mail_plugins = $mail_plugins
}
```


#### auth-sql.conf.ext

```
cp /usr/local/share/doc/dovecot/example-config/conf.d/auth-sql.conf.ext /usr/local/etc/dovecot/conf.d/auth-sql.conf.ext
vi /usr/local/etc/dovecot/conf.d/auth-sql.conf.ext
```

```:auth-sql.conf.ext:
passdb {
  driver = sql

  # Path for SQL configuration file, see example-config/conf.d/dovecot-sql.conf.ext
  args = /usr/local/etc/dovecot/conf.d/dovecot-sql.conf.ext
}

userdb {
  driver = sql
  args = /usr/local/etc/dovecot/conf.d/dovecot-sql.conf.ext
}
```

権限を設定変更する

```
#mkdir -p /usr/local/var/run/dovecot/stats-writer
#chmod -R 777 /usr/local/var/run/dovecot/stats-writer
chmod -R 777 /usr/local/var/run/dovecot
```


## 4.icu4cをインストールする

こちらは、PHPのライブラリと共に入れているのでスキップ
こちらを参照して頂き。PHPと共にインストールを行ってください
https://qiita.com/shadowhat/items/b46624c0bee1b9a59422


## 5.Kerberosをインストールする

あらかじめ必要なライブラリをインストールを行う

PowerToolsを有効化する

```
dnf config-manager --set-enabled crb
dnf install libnsl2-devel
dnf install libdb-devel
```

linbsl2が、OS側のkerberosライブラリと紐付いており、kerberosのライブラリがOSのOpenSSLのライブラリと紐付いてしまっているため、Kerberosを今回導入したOpenSSLに紐付けてビルドする

```
cd /usr/local/src
wget https://kerberos.org/dist/krb5/1.21/krb5-1.21.tar.gz
tar xvzf krb5-1.21.tar.gz
cd krb5-1.21/src
export PKG_CONFIG_PATH=/usr/local/ssl/lib:/usr/local/lib:/usr/local/lib64
./configure
make -j 6
make install
```


## 6.Postfixを導入する



以下のコマンドを実行

```
useradd postfix
groupadd postdrop
chown -R mailbox:mailbox /home/mailbox
chmod -R 755 /home/mailbox
```

Postfix をインストールする

```
ln -s /usr/local/pgsql/lib/libpq.so.5 /lib64/libpq.so.5
ln -s /usr/local/mysql/lib/libmariadb.so.3 /lib64/libmariadb.so.3
#インストールしたバージョンに合わせたライブラリのシンボリックリンクを張る
ln -s /usr/local/lib/libicuuc.so.76 /lib64/libicuuc.so.76
ln -s /usr/local/lib/libicudata.so.76 /lib64/libicudata.so.76

```

```
cd /usr/local/src
wget https://linorg.usp.br/postfix/release/official/postfix-3.9.1.tar.gz
tar xvzf postfix-3.9.1.tar.gz
cd postfix-3.9.1

export PKG_CONFIG_PATH=/usr/local/ssl/lib:/usr/local/lib:/usr/local/lib64:/usr/lib

make tidy
make clean
make -f Makefile.init makefiles \
'CCARGS=-DNO_EAI -DNO_IPV6 -DUSE_TLS -I/usr/local/ssl/include -DHAS_PGSQL -I/usr/local/pgsql/include -DUSE_SASL_AUTH -DUSE_CYRUS_SASL -I/usr/local/include/sasl -DHAS_DB -I/usr/local/BerkeleyDB.6.2/include -DHAS_MYSQL -I/usr/local/mysql/include/mysql -DHAS-KRB5 -I/usr/local/include/krb5 -I/usr/local/include/' \
'AUXLIBS=-L/usr/local/ssl/lib -lssl -L/usr/local/ssl/lib -lcrypto -L/usr/local/pgsql/lib -lpq  -L/usr/local/ssl/lib -lssl -lcrypto -lcrypt  -L/usr/local/lib/sasl2 -lsasl2 -L/usr/local/BerkeleyDB.6.2/lib -ldb -L/usr/local/mysql/lib -lmysqlclient -lz -lm -L/usr/local/lib -lkrb5 -L /usr/local/lib/libicuuc.so -licuuc' -j 8
# 参考
# http://www.postfix.org/INSTALL.html
make install -j 8

systemctl enable dovecot
systemctl start dovecot
```

make中に「#include <rpcsvc/ypclnt.h>」でエラーになる場合は、libnsl2がインストールされていない。
「dnf install libnsl2-devel」を実行する

起動スクリプトを配置する

```
cat > /usr/lib/systemd/system/postfix.service << EOF
[Unit]
Description=Postfix Mail Transport Agent
After=syslog.target network.target
Conflicts=sendmail.service exim.service

[Service]
Type=forking
PIDFile=/var/spool/postfix/pid/master.pid
EnvironmentFile=-/etc/sysconfig/network
PrivateTmp=true
CapabilityBoundingSet=~ CAP_NET_ADMIN CAP_SYS_ADMIN CAP_SYS_BOOT CAP_SYS_MODULE
ProtectSystem=true
PrivateDevices=true
ExecStartPre=-/usr/libexec/postfix/aliasesdb
ExecStartPre=-/usr/libexec/postfix/chroot-update
ExecStart=/usr/sbin/postfix start
ExecReload=/usr/sbin/postfix reload
ExecStop=/usr/sbin/postfix stop

[Install]
WantedBy=multi-user.target

EOF
```

## 7.PostfixAdminを導入する

以下よりダウンロードして、必用な場所に配置する

```
cd /usr/local/src
wget https://github.com/postfixadmin/postfixadmin/archive/refs/tags/postfixadmin-3.3.10.tar.gz
tar xvzf postfixadmin-3.3.10.tar.gz
mv postfixadmin-postfixadmin-3.3.10 /doscs
```

「config.inc.php」を以下の通り設定を入れる

```
$CONF['configured'] = true;
$CONF['setup_password'] = 'password'; //ハッシュ値を書く
$CONF['default_language'] = 'ja';

$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = '127.0.0.1';
$CONF['database_user'] = 'postfixadmin';
$CONF['database_password'] = 'postfixadmin';
$CONF['database_name'] = 'postfixadmin';
//$CONF['database_socket'] = '/opt/mariadb/mysql.sock';
$CONF['database_port'] = '3306';

$CONF['encrypt'] = 'cleartext'; #必用に応じて変更(md5crypt/md5/system/mysql_encrypt/authlib)

$CONF['dovecotpw'] = "/usr/local/bin/doveadm pw"; # debian

$CONF['show_password'] = 'YES';
$CONF['page_size'] = '100';

$CONF['password_validation'] = array(
#    '/regular expression/' => '$PALANG key (optional: + parameter)',
//    '/.{5}/'                => 'password_too_short 5',      # minimum length 5 characters
//    '/([a-zA-Z].*){3}/'     => 'password_no_characters 3',  # must contain at least 3 characters
//    '/([0-9].*){2}/'        => 'password_no_digits 2',      # must contain at least 2 digits

    /*  support a 'callable' value which if it returns a non-empty string will be assumed to have failed, non-empty string should be a PALANG key */
    // 'length_check'          => function($password) { if (strlen(trim($password)) < 3) { return 'password_too_short'; } },
);
// パスワードチェックをしないようにコメントアウトする


$CONF['default_aliases'] = array (
//    'abuse' => 'abuse@change-this-to-your.domain.tld',
//    'hostmaster' => 'hostmaster@change-this-to-your.domain.tld',
//    'postmaster' => 'postmaster@change-this-to-your.domain.tld',
//    'webmaster' => 'webmaster@change-this-to-your.domain.tld'
);
// コメントアウトする


$CONF['quota'] = 'YES';
$CONF['used_quotas'] = 'YES';

$CONF['vacation'] = 'YES';

$CONF['mailbox_postcreation_script'] = '/docs/mail.example.com/postfixadmin/ADDITIONS/postfixadmin-mailbox-postcreation.sh';
$CONF['mailbox_postedit_script'] = '';
$CONF['mailbox_postdeletion_script'] = '/docs/mail.example.com/postfixadmin/ADDITIONS/postfixadmin-domain-postdeletion.sh';
$CONF['domain_postdeletion_script'] = '/docs/vela.ofa.or.jp/postfixadmin/ADDITIONS/postfixadmin-domain-postdeletion.sh';
```

以下の③つのファイルの「basedir」を「/var/spool/maildirs」から「/home/mailbox」に変更する

```
vi postfixadmin/ADDITIONS/postfixadmin-mailbox-postcreation.sh
vi postfixadmin/ADDITIONS/postfixadmin-mailbox-postdeletion.sh
vi postfixadmin/ADDITIONS/postfixadmin-domain-postdeletion.sh
```

Webサーバーには、Postfixのディレクトリ配下に「public」を公開する

ディレクトリを作成する

```
cd postfixadmin
mkdir templates_c
chown daemon:daemon templates_c
chmod -R 666 templates_c
```

## 8. PostfixAdminの設定ファイルを渡す

```:virtual-alias-maps.cf
cat > /etc/postfix/virtual-alias-maps.cf  << EOF
hosts    = localhost
user     = postfix
password = postfix
dbname   = postfix

query = SELECT goto FROM alias WHERE address='%s' AND active = 1

EOF
```

```:virtual-mailbox-domains.cf
cat > /etc/postfix/virtual-mailbox-domains.cf << EOF
hosts    = localhost
user     = postfix
password = postfix
dbname   = postfix

query = SELECT domain FROM domain WHERE domain='%s' and backupmx = 0 and active = 1
EOF
```

```:virtual-mailbox-maps.cf
cat > /etc/postfix/virtual-mailbox-maps.cf << EOF
hosts    = localhost
user     = postfix
password = postfix
dbname   = postfix

query = SELECT maildir FROM mailbox WHERE username='%s' AND active = 1
EOF
```

```:virtual-mailbox-limit-maps.cf
cat > /etc/postfix/virtual-mailbox-limit-maps.cf << EOF
hosts    = localhost
user     = postfix
password = postfix
dbname   = postfix
query = SELECT quota FROM mailbox WHERE username='%s' AND active = '1'

EOF
```

### main.cfを編集する

```
vi /etc/postfix/main.cf
```

```
#コメントを外す
inet_interfaces = all

#空で設定
mydestination =

#smtputf8を拒否
smtputf8_enable = no

#メール添付サイズ
message_size_limit = 40960000

#
# TLS
#
smtpd_tls_cert_file = /etc/letsencrypt/live/example.com/fullchain.pem
smtpd_tls_key_file  = /etc/letsencrypt/live/example.com/privkey.pem
smtpd_tls_security_level = may
smtpd_use_tls = yes
#↓TLSを強制する場合
#smtpd_enforce_tls = yes

smtp_tls_protocols = !SSLv2, !SSLv3
smtp_tls_mandatory_protocols = !SSLv2, !SSLv3
smtpd_tls_protocols = !SSLv2, !SSLv3
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3

# Its DSA counterparts:
#smtpd_tls_dcert_file = /etc/postfix/server-dsa.pem
#smtpd_tls_dkey_file = $smtpd_tls_dcert_file

# CA関係の設定を変更
# smtpd_tls_CAfile = /etc/postfix/CAcert.pem
smtpd_tls_CAfile = /etc/letsencrypt/live/example.com/fullchain.pem

#smtpd_tls_CApath = /etc/postfix/certs
smtpd_tls_CApath = /etc/letsencrypt/live/example.com

# ログレベルの変更(最低レベル)
# 0:出力しない　1:TLSハンドシェイクと証明書情報　2:TLSネゴシエーションの全て
# smtpd_tls_loglevel = 0
smtpd_tls_loglevel = 2
smtp_tls_security_level = may


#
# SASL
#
smtpd_sasl_auth_enable          = yes
smtpd_sasl_type                 = dovecot
smtpd_sasl_path                 = private/auth
smtpd_sasl_security_options     = noanonymous
smtpd_sasl_tls_security_options = $smtpd_sasl_security_options
smtpd_sasl_local_domain         = $mydomain
smtpd_sasl_authenticated_header = yes
#リレー設定
#smtpd_recipient_restrictions    = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination

broken_sasl_auth_clients = yes

#
# Virtual mail box
#

#mailboxのuid/gidを入れる
virtual_uid_maps        = static:1003 #/home/mailboxのユーザーID
virtual_gid_maps        = static:1003 #/home/mailboxのグループID
virtual_minimum_uid     = 1003
virtual_mailbox_base    = /home/mailbox
#virtual_transport       = lmtp:unix:private/dovecot-lmtp
virtual_transport       = dovecot
virtual_mailbox_domains = mysql:/etc/postfix/virtual-mailbox-domains.cf
virtual_mailbox_maps    = mysql:/etc/postfix/virtual-mailbox-maps.cf
virtual_alias_maps      = mysql:/etc/postfix/virtual-alias-maps.cf

# 容量制限
#vdaパッチ適用時だけ利用
#virtual_create_maildirsize = yes
#virtual_mailbox_extended   = yes
#virtual_mailbox_limit      = 102400000
#virtual_mailbox_limit_maps = pgsql:/etc/postfix/virtual-mailbox-limit-maps.cf
#virtual_mailbox_limit_override = yes
#virtual_maildir_limit_message = Sorry, the user's maildir has overdrawn his diskspace quota, please try again later.
#virtual_overquota_bounce = yes

#doveot transfer stop
dovecot_destination_recipient_limit = 1
```

### master.confを編集する

```
vi /etc/postfix/master.cf
```

以下のコメントを外す（+部分のコメントを外す）

```
submission inet n       -       n       -       -       smtpd
*  -o syslog_name=postfix/submission
*  -o smtpd_tls_security_level=encrypt
*  -o smtpd_sasl_auth_enable=yes
*  -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=
* -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
* -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       n       -       -       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=
*  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
*  -o milter_macro_daemon_name=ORIGINATING


##一番下に追記する
dovecot   unix  -       n       n       -       -       pipe
  flags=DRhu user=mailbox:mailbox argv=/usr/local/libexec/dovecot/deliver -f ${sender} -d ${recipient}
```

## 9. PostfixAdminを設定する

ブラウザーで、「https://example.com/postfixadmin/public/setup.php」を開く

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/85495/04f40535-edf3-3011-93f4-b27a26dc318b.png)


Generate setup_passwordで出力されたセットアップパスワードハッシュを「config .inc.php」に追記します。

```:config.inc.php
$CONF['setup_password'] = 'password'; //ハッシュ値を書く
```

再度、ブラウザーを更新し「setup.php」を開きます。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/85495/94ce4f7e-5d2c-c60a-05da-b01aea1d39f2.png)


あとは、ドメイン作成と、メールボックスの作成をしてメールの送信テストを行います。
なお、作成するドメインのMXレコードの作成も先に行っておいてください。