Outils pour utilisateurs

Outils du site


tutoriaux:install-email-server:install-email-server-part-3

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
tutoriaux:install-email-server:install-email-server-part-3 [2023/01/06 16:41] – supprimée - modification externe (Unknown date) 127.0.0.1tutoriaux:install-email-server:install-email-server-part-3 [2023/01/06 18:22] (Version actuelle) – créée - modification externe 127.0.0.1
Ligne 1: Ligne 1:
 +====== Build Email Server From Scratch on Debian – Part 3 - Create Virtual Mailboxes ======
 +
 +In previous articles, we discussed how to set up your own mail server on Debian from scratch. In [[tutoriaux:install-email-server:install-email-server-part-1|part 1]] and [[tutoriaux:install-email-server:install-email-server-part-2|part 2]] of this tutorial series, we learned how to set up **Postfix SMTP server** and **Dovecot IMAP server**, but so far we can only have email addresses for users with local Unix account. This tutorial is going to show you how to create virtual mailboxes on Debian mail server with **PostfixAdmin**, which is an open-source web-based interface to configure and manage a Postfix-based email server for many domains and users.
 +
 +With **virtual mailboxes**, we don’t need to create local Unix account for each email address. If you are going to set up a mail server for a company or organization, it’s always better to have an easy way to create virtual mailboxes in a web-based interface, which also allows users to change their passwords. That’s where PostfixAdmin comes in.
 +
 +==== PostfixAdmin Features ====
 +
 +  * manage mailboxes, virtual domains, and aliases
 +  * vacation/out-of-office messages (Personally I think this feature is better done in Roundcube Webmail.)
 +  * alias domains (forwarding one domain to another with recipient validation)
 +  * users can manage their own mailbox (change alias, password, and vacation message)
 +  * quota support for single mailboxes and total quota of a domain
 +  * fetchmail integration: You can fetch emails from your original email address to your new email address.
 +  * command line client postfixadmin-cli for those who don’t want to click around in a web interface 😉
 +
 +<WRAP round info>
 +Once you finish part 3, you can no longer use local Unix accounts as email addresses. You must create email addresses from the PostfixAdmin web interface.
 +</WRAP>
 +
 +==== Requirements ====
 +
 +I assume that you have followed [[tutoriaux:install-email-server:install-email-server-part-1|part 1]] and [[tutoriaux:install-email-server:install-email-server-part-2|part 2]] of this tutorial series. If you followed mail server tutorials on other websites, I recommend purging your configurations (''sudo apt purge postfix dovecot-core'') and start over with my tutorial series, so you are not going to be confused by different setup processes.
 +
 +Once the above requirements are met, let’s install and configure PostfixAdmin.
 +
 +===== Install MariaDB Database Server =====
 +
 +PostfixAdmin is written in PHP and requires a database (MySQL/MariaDB, PostgreSQL or SQLite). This article will use MariaDB database, which is a drop-in replacement for MySQL. It is developed by former members of MySQL team who are concerned that Oracle might turn MySQL into a closed-source product. Enter the following commands to install MariaDB on Debian.
 +
 +<code bash>sudo apt update
 +
 +sudo apt install mariadb-server mariadb-client</code>
 +
 +After it’s installed, MariaDB server should be automatically started. Use **systemctl** to check its status.
 +
 +<code bash>sudo systemctl status mariadb</code>
 +
 +Sample output:
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-mysql-status.png |}}
 +
 +If it’s not running, start it with this command:
 +
 +<code bash>sudo systemctl start mariadb</code>
 +
 +To enable MariaDB to automatically start at boot time, run
 +
 +<code bash>sudo systemctl enable mariadb</code>
 +
 +Now run the post-installation security script.
 +
 +<code bash>sudo mysql_secure_installation</code>
 +
 +When it asks you to enter MariaDB root password, press Enter key as the root password isn’t set yet. Your root account is already secured, so you should answer n to not set password.
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-mysql-secure-setup-1.png |}}
 +
 +Next, you can press ''Enter'' to answer all remaining questions, which will remove anonymous user, disable remote root login and remove test database. This step is a basic requirement for MariaDB database security. (Notice that Y is __capitalized__, which means it is the default answer. )
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-mysql-secure-setup-2.png |}}
 +
 +===== Download PostfixAdmin on Debian Server =====
 +
 +PostfixAdmin is included in the default Debian repository. However, I don’t recommend it for the following reasons:
 +
 +  * It can create problems when you upgrade the Ubuntu system to a new version, resulting in upgrade failure.
 +  * If you use Nginx, the postfixadmin package might automatically install Apache on your system.
 +  * If you use MySQL, this package might remove MySQL from your system.
 +  * The default postfixadmin package has a login loop issue from time to time.
 +
 +So I will show you how to install the latest version of PostfixAdmin. Go to [[https://github.com/postfixadmin/postfixadmin/releases|PostfixAdmin Gitbub page]] to download the latest version. You can use the ''wget'' tool to download it from command line. The download link is always available in the format below. If a new version comes out, simply replace 3.3.11 with the new version number.
 +
 +<code bash>sudo apt install wget</code>
 +
 +<code bash>wget https://github.com/postfixadmin/postfixadmin/archive/postfixadmin-3.3.11.tar.gz</code>
 +
 +Once downloaded, extract the archive to the ''/var/www/'' directory and rename it to ''postfixadmin''.
 +
 +<code bash>sudo mkdir -p /var/www/
 +
 +sudo tar xvf postfixadmin-3.3.11.tar.gz -C /var/www/
 +
 +sudo mv /var/www/postfixadmin-postfixadmin-3.3.11 /var/www/postfixadmin
 +</code>
 +
 +===== Setting Up Permissions =====
 +
 +PostfixAdmin requires a ''templates_c'' directory, and the web server needs read and write access to this directory, so run the following commands.
 +
 +<code bash>sudo mkdir /var/www/postfixadmin/templates_c
 +
 +sudo apt install acl
 +sudo setfacl -R -m u:www-data:rwx /var/www/postfixadmin/templates_c/
 +</code>
 +
 +Starting with Dovecot 2.3.11, the web server user needs permission to read Let’s Encrypt TLS certificate in order to do password hashing. Run the following two commands to grant permissions.
 +
 +<code bash>sudo setfacl -R -m u:www-data:rx /etc/letsencrypt/live/ /etc/letsencrypt/archive/</code>
 +
 +===== Create a Database and User for PostfixAdmin =====
 +
 +Log into MySQL/MariaDB shell as root with the following command.
 +
 +<code bash>sudo mysql -u root</code>
 +
 +Once you are logged in, create a database for PostfixAdmin using the following command. I named it ''postfixadmin'', but you can use whatever name you like. (Don’t leave out the semicolon.)
 +
 +<code sql>create database postfixadmin;</code>
 +
 +Then enter the command below to create a database user for PostfixAdmin. This command also grants all privileges of postfixadmin database to the user. Replace ''postfixadmin_password'' with your preferred password. Note that the password should not contain the # character, or you might not be able to log in later.
 +
 +<code sql>grant all privileges on postfixadmin.* to 'postfixadmin'@'localhost' identified by 'postfixadmin_password';</code>
 +
 +Flush the privileges table for the changes to take effect and then get out of MariaDB shell.
 +
 +<code sql>flush privileges;
 +
 +exit;</code>
 +
 +===== Configure PostfixAdmin =====
 +
 +The default PostfixAdmin configuration file is ''config.inc.php''. We need to create a ''config.local.php'' file and add custom configurations.
 +
 +<code bash>sudo nano /var/www/postfixadmin/config.local.php</code>
 +
 +Add the following lines in the file, so PostfixAdmin can connect to MySQL/MariaDB database. Replace ''postfixadmin_password'' with the real PostfixAdmin password created in the previous step.
 +
 +<code php>
 +<?php
 +$CONF['configured'] = true;
 +$CONF['database_type'] = 'mysqli';
 +$CONF['database_host'] = 'localhost';
 +$CONF['database_port'] = '3306';
 +$CONF['database_user'] = 'postfixadmin';
 +$CONF['database_password'] = 'postfixadmin_password';
 +$CONF['database_name'] = 'postfixadmin';
 +$CONF['encrypt'] = 'dovecot:ARGON2I';
 +$CONF['dovecotpw'] = "/usr/bin/doveadm pw -r 5";
 +if(@file_exists('/usr/bin/doveadm')) { // @ to silence openbase_dir stuff; see https://github.com/postfixadmin/postfixadmin/issues/171
 +    $CONF['dovecotpw'] = "/usr/bin/doveadm pw -r 5"; # debian
 +}
 +</code>
 +
 +Save and close the file. Note that we will use the [[https://password-hashing.net/|ARGON2I]] password scheme.
 +You should need to install this package:
 +
 +<code bash>sudo apt -y install argon2</code>
 +
 +===== Create Apache Virtual Host or Nginx Config File for PostfixAdmin =====
 +
 +==== Apache ====
 +
 +If you use Apache web server, create a virtual host for PostfixAdmin.
 +
 +<code bash>sudo nano /etc/apache2/sites-available/postfixadmin.conf</code>
 +
 +Put the following text into the file. Replace ''postfixadmin.example.com'' with your real domain name and don’t forget to set DNS A record for it.
 +
 +<code apache>
 +<VirtualHost *:80>
 +  ServerName postfixadmin.example.com
 +  DocumentRoot /var/www/postfixadmin/public
 +
 +  ErrorLog ${APACHE_LOG_DIR}/postfixadmin_error.log
 +  CustomLog ${APACHE_LOG_DIR}/postfixadmin_access.log combined
 +
 +  <Directory />
 +    Options FollowSymLinks
 +    AllowOverride All
 +  </Directory>
 +
 +  <Directory /var/www/postfixadmin/>
 +    Options FollowSymLinks MultiViews
 +    AllowOverride All
 +    Order allow,deny
 +    allow from all
 +  </Directory>
 +
 +</VirtualHost>
 +</code>
 +
 +Save and close the file. Then enable this virtual host with:
 +
 +<code bash>sudo a2ensite postfixadmin.conf</code>
 +
 +Reload Apache for the changes to take effect.
 +
 +<code bash>sudo systemctl reload apache2</code>
 +
 +Now you should be able to see the PostfixAdmin web-based install wizard at http://postfixadmin.example.com/setup.php.
 +
 +==== Nginx ====
 +
 +If you use Nginx web server, create a virtual host for PostfixAdmin.
 +
 +<code bash>sudo nano /etc/nginx/conf.d/postfixadmin.conf</code>
 +
 +Put the following text into the file. Replace postfixadmin.example.com with your real domain name and don’t forget to set DNS A record for it.
 +
 +<code nginx>
 +server {
 +   listen 80;
 +   listen [::]:80;
 +   server_name postfixadmin.example.com;
 +
 +   root /var/www/postfixadmin/public/;
 +   index index.php index.html;
 +
 +   access_log /var/log/nginx/postfixadmin_access.log;
 +   error_log /var/log/nginx/postfixadmin_error.log;
 +
 +   location / {
 +       try_files $uri $uri/ /index.php;
 +   }
 +
 +   location ~ ^/(.+\.php)$ {
 +        try_files $uri =404;
 +        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
 +        fastcgi_index index.php;
 +        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 +        include /etc/nginx/fastcgi_params;
 +   }
 +}
 +</code>
 +
 +Note: Debian 11 ships PHP7.4 and Debian 10 ships with PHP7.3. If you use Debian 10, then change ''php7.4-fpm'' to ''php7.3-fpm'' in the above file.
 +
 +Save and close the file. Then test Nginx configuration.
 +
 +<code bash>sudo nginx -t</code>
 +
 +If the test is successful, reload Nginx for the changes to take effect.
 +
 +<code bash>sudo systemctl reload nginx</code>
 +
 +Now you should be able to see the PostfixAdmin web-based install wizard at ''http://postfixadmin.example.com/setup.php.''
 +
 +===== Install Required and Recommended PHP Modules =====
 +
 +Run the following command to install PHP modules required or recommended by PostfixAdmin on Debian 11.
 +
 +<code bash>sudo apt install php7.4-fpm php7.4-imap php7.4-mbstring php7.4-mysql php7.4-json php7.4-curl php7.4-zip php7.4-xml php7.4-bz2 php7.4-intl php7.4-gmp</code>
 +
 +If you use Debian 10, run the following command.
 +
 +<code bash>sudo apt install php7.3-fpm php7.3-imap php7.3-mbstring php7.3-mysql php7.3-json php7.3-curl php7.3-zip php7.3-xml php7.3-bz2 php7.3-intl php7.3-gmp</code>
 +
 +Then restart Apache. (If you use Nginx, you don’t need to restart Nginx.)
 +
 +<code bash>sudo systemctl restart apache2</code>
 +
 +===== Enabling HTTPS =====
 +
 +To encrypt the HTTP traffic, we can enable HTTPS by installing a free TLS certificate issued from Let’s Encrypt. Run the following command to install Let’s Encrypt client (certbot) on Debian server.
 +
 +Normally this step should have been performed during the [[tutoriaux:install-email-server:install-email-server-part-2#obtaining_tls_certificate_with_apache_web_server|previous part]].
 +
 +<code bash>sudo apt install certbot</code>
 +
 +If you use Apache, install the Certbot Apache plugin.
 +
 +<code bash>sudo apt install python3-certbot-apache</code>
 +
 +And run this command to obtain and install TLS certificate.
 +
 +<code bash>sudo certbot --apache --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d postfixadmin.example.com</code>
 +
 +If you use Nginx, then you also need to install the Certbot Nginx plugin.
 +
 +<code bash>sudo apt install python3-certbot-nginx</code>
 +
 +Next, run the following command to obtain and install TLS certificate.
 +
 +<code bash>sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d postfixadmin.example.com</code>
 +
 +Where
 +
 +^ certonly        | obtain the TLS certificate but don’t install it in the web server                                                         |
 +^ --apache        | Use the Apache plugin for authentication                                                                                  |
 +^ --nginx         | Use the nginx plugin.                                                                                                     |
 +^ --agree-tos     | Agree to terms of service.                                                                                                |
 +^ --no-eff-email  | Don’t receive emails from EFF foundation.                                                                                 |
 +^ --redirect      | Force HTTPS by 301 redirect.                                                                                              |
 +^ --hsts          | Add the Strict-Transport-Security header to every HTTP response. Forcing browser to always use TLS for the domain. Defends against SSL/TLS Stripping. |
 +^ --staple-ocsp   | Enables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS connection.  |
 +^ --email         | Enter your email address, which is used for important notifications and account recovery.                                 |
 +^ -d              | domain, aka your mail server hostname.                                                                                    |
 +
 +The certificate should now be obtained and automatically installed, which is indicated by the message below.
 +
 +{{ tutoriaux:debian-email:debian-tls-certibot-success.png |}}
 +===== Enable Statistics in Dovecot =====
 +
 +PostfixAdmin needs to read Dovecot statistics. Edit the Dovecot configuration file.
 +
 +<code bash>sudo nano /etc/dovecot/conf.d/10-master.conf</code>
 +
 +Add the following lines to the end of this file.
 +
 +<code ini>
 +service stats {
 +    unix_listener stats-reader {
 +    user = www-data
 +    group = www-data
 +    mode = 0660
 +}
 +
 +unix_listener stats-writer {
 +    user = www-data
 +    group = www-data
 +    mode = 0660
 +  }
 +}
 +</code>
 +
 +Save and close the file. Then add the web server to the ''dovecot'' group.
 +
 +<code bash>sudo gpasswd -a www-data dovecot</code>
 +Restart Dovecot.
 +
 +<code bash>sudo systemctl restart dovecot</code>
 +Grant permissions to the ''www-data'' user.
 +
 +<code bash>sudo setfacl -R -m u:www-data:rwx /var/run/dovecot/stats-reader /var/run/dovecot/stats-writer</code>
 +
 +===== Finish the Installation in Web Browser =====
 +
 +Go to ''postfixadmin.example.com/setup.php'' to run the web-based setup wizard. First, you need to create a setup password for PostfixAdmin.
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-postfixadmin-setup.png |}}
 +
 +After creating the password hash, PostfixAdmin will display a line like below.
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-postfixadmin-passwordkey.png |}}
 +
 +<code php>
 +$CONF['setup_password'] = '$2y$10$Fp7rhH8/2miXfUeMcGnRkulpCyLA.k35Gta3WYfJYTrTXTvYyUGDa';
 +</code>
 +
 +You need to open the ''config.local.php'' file.
 +
 +<code bash>sudo nano /var/www/postfixadmin/config.local.php</code>
 +
 +Add the line displayed on PostfixAdmin setup page to the end of the file like below.
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-postfixadmin-config.png |}}
 +
 +After saving the file, you need to refresh the PostfixAdmin setup page and enter the setup password again, then create the admin account.  Please don’t use a Gmail, Yahoo Mail, or Microsoft email address for the admin account, or you might not be able to log in later. Use an email address on your own domain. You can create the email address later in PostfixAdmin.
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-postfixadmin-add-admin.png |}}
 +
 +Once the superadmin account is created, you can log into PostfixAdmin at ''postfixadmin.example.com/login.php''.
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-postfixadmin-login.png |}}
 +
 +===== Configure Postfix to Use MySQL/MariaDB Database =====
 +
 +By default, Postfix delivers emails only to users with a local Unix account. To make it deliver emails to virtual users whose information is stored in the database, we need to configure Postfix to use virtual mailbox domains.
 +
 +First, we need to add MySQL map support for Postfix by installing the ''postfix-mysql'' package.
 +
 +<code bash>sudo apt install postfix-mysql</code>
 +
 +Then edit the Postfix main configuration file.
 +
 +<code bash>sudo nano /etc/postfix/main.cf</code>
 +
 +Add the following lines at the end of this file.
 +
 +<code ini>
 +virtual_mailbox_domains = proxy:mysql:/etc/postfix/sql/mysql_virtual_domains_maps.cf
 +virtual_mailbox_maps =
 +   proxy:mysql:/etc/postfix/sql/mysql_virtual_mailbox_maps.cf,
 +   proxy:mysql:/etc/postfix/sql/mysql_virtual_alias_domain_mailbox_maps.cf
 +virtual_alias_maps =
 +   proxy:mysql:/etc/postfix/sql/mysql_virtual_alias_maps.cf,
 +   proxy:mysql:/etc/postfix/sql/mysql_virtual_alias_domain_maps.cf,
 +   proxy:mysql:/etc/postfix/sql/mysql_virtual_alias_domain_catchall_maps.cf
 +</code>
 +   
 +Where:
 +
 +  * ''virtual_mailbox_domains'' points to a file that will tell Postfix how to look up domain information from the database.
 +  * ''virtual_mailbox_maps'' points to files that will tell Postfix how to look up email addresses from the database.
 +  * ''virtual_alias_maps'' points to files that will tell Postfix how to look up aliases from the database.
 +
 +We want to use dovecot to deliver incoming emails to the virtual users’ message store, so also add the following line at the end of this file.
 +
 +<code ini>virtual_transport = lmtp:unix:private/dovecot-lmtp</code>
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-dovecot-transport.png |}}
 +
 +Save and close the file. Next, we need to create the ''.cf'' files one by one. Create the sql directory.
 +
 +<code bash>sudo mkdir /etc/postfix/sql/</code>
 +
 +Create the //mysql_virtual_domains_maps.cf// file.
 +
 +<code bash>sudo nano /etc/postfix/sql/mysql_virtual_domains_maps.cf</code>
 +
 +Add the following content. Replace ''password'' with the postfixadmin password you set in Step 2.
 +
 +<code ini>
 +user = postfixadmin
 +password = postfixadmin_password
 +hosts = localhost
 +dbname = postfixadmin
 +query = SELECT domain FROM domain WHERE domain='%s' AND active = '1'
 +#query = SELECT domain FROM domain WHERE domain='%s'
 +#optional query to use when relaying for backup MX
 +#query = SELECT domain FROM domain WHERE domain='%s' AND backupmx = '0' AND active = '1'
 +#expansion_limit = 100
 +</code>
 +
 +Create the //mysql_virtual_mailbox_maps.cf// file.
 +
 +<code bash>sudo nano /etc/postfix/sql/mysql_virtual_mailbox_maps.cf</code>
 +
 +Add the following content.
 +
 +<code ini>
 +user = postfixadmin
 +password = postfixadmin_password
 +hosts = localhost
 +dbname = postfixadmin
 +query = SELECT maildir FROM mailbox WHERE username='%s' AND active = '1'
 +#expansion_limit = 100
 +</code>
 +
 +Create the //mysql_virtual_alias_domain_mailbox_maps.cf// file.
 +
 +<code bash>sudo nano /etc/postfix/sql/mysql_virtual_alias_domain_mailbox_maps.cf</code>
 +
 +Add the following content.
 +
 +<code ini>
 +user = postfixadmin
 +password = postfixadmin_password
 +hosts = localhost
 +dbname = postfixadmin
 +query = SELECT maildir FROM mailbox,alias_domain WHERE alias_domain.alias_domain = '%d' and mailbox.username = CONCAT('%u', '@', alias_domain.target_domain) AND mailbox.active = 1 AND alias_domain.active='1'
 +</code>
 +
 +Create the //mysql_virtual_alias_maps.cf// file.
 +
 +<code bash>sudo nano /etc/postfix/sql/mysql_virtual_alias_maps.cf</code>
 +
 +Add the following content.
 +
 +<code ini>
 +user = postfixadmin
 +password = postfixadmin_password
 +hosts = localhost
 +dbname = postfixadmin
 +query = SELECT goto FROM alias WHERE address='%s' AND active = '1'
 +#expansion_limit = 100
 +</code>
 +
 +Create the //mysql_virtual_alias_domain_maps.cf// file.
 +
 +<code bash>sudo nano /etc/postfix/sql/mysql_virtual_alias_domain_maps.cf</code>
 +
 +Add the following content.
 +
 +<code ini>
 +user = postfixadmin
 +password = postfixadmin_password
 +hosts = localhost
 +dbname = postfixadmin
 +query = SELECT goto FROM alias,alias_domain WHERE alias_domain.alias_domain = '%d' and alias.address = CONCAT('%u', '@', alias_domain.target_domain) AND alias.active = 1 AND alias_domain.active='1'
 +</code>
 +
 +Create the //mysql_virtual_alias_domain_catchall_maps// file.
 +
 +<code bash>sudo nano /etc/postfix/sql/mysql_virtual_alias_domain_catchall_maps.cf</code>
 +
 +Add the following content.
 +
 +<code ini>
 +# handles catch-all settings of target-domain
 +user = postfixadmin
 +password = postfixadmin_password
 +hosts = localhost
 +dbname = postfixadmin
 +query = SELECT goto FROM alias,alias_domain WHERE alias_domain.alias_domain = '%d' and alias.address = CONCAT('@', alias_domain.target_domain) AND alias.active = 1 AND alias_domain.active='1'
 +</code>
 +
 +Since the database passwords are stored in plain text so they should be readable only by user postfix and root, which is done by executing the following two commands.
 +
 +<code bash>
 +sudo chmod 0640 /etc/postfix/sql/*
 +sudo setfacl -R -m u:postfix:rx /etc/postfix/sql/
 +</code>
 +
 +Next, we need to change the value of the ''mydestination'' parameter in Postfix. Display the current value:
 +
 +<code bash>sudo postconf mydestination</code>
 +
 +Sample output:
 +
 +<code ini>mydestination = $myhostname, linuxbabe.com, localhost.$mydomain, localhost</code>
 +
 +The ''mydestination'' parameter contains a list of domain names that will receive emails delivered to local Unix accounts. In part 1, we added the apex domain name (like linuxbabe.com) to ''mydestination''. Since we are going to use virtual mailbox, we need to remove the apex domain name from the list by issuing the following command.
 +
 +<code bash>sudo postconf -e "mydestination = \$myhostname, localhost.\$mydomain, localhost"</code>
 +
 +Now let’s open the Postfix main configuration file again.
 +
 +<code bash>sudo nano /etc/postfix/main.cf</code>
 +
 +Add the following lines at the end of this file.
 +
 +<code ini>
 +virtual_mailbox_base = /var/vmail
 +virtual_minimum_uid = 2000
 +virtual_uid_maps = static:2000
 +virtual_gid_maps = static:2000
 +</code>
 +
 +The first line defines the base location of mail files. The remaining 3 lines define which user ID and group ID Postfix will use when delivering incoming emails to the mailbox. We use the user ID 2000 and group ID 2000.
 +
 +Save and close the file. Restart Postfix for the changes to take effect.
 +
 +<code bash>sudo systemctl restart postfix</code>
 +
 +Next, we need to create a user named ''vmail'' with ID 2000 and a group with ID 2000.
 +
 +<code bash>sudo adduser vmail --system --group --uid 2000 --disabled-login --no-create-home</code>
 +
 +Create the mail base location.
 +
 +<code bash>sudo mkdir /var/vmail/</code>
 +Make vmail as the owner.
 +
 +<code bash>sudo chown vmail:vmail /var/vmail/ -R</code>
 +
 +===== Configure Dovecot to Use MySQL/MariaDB Database =====
 +
 +We also need to configure the Dovecot IMAP server to query user information from the database. First, run the following command to add MySQL support for Dovecot.
 +
 +<code bash>sudo apt install dovecot-mysql</code>
 +
 +Then edit the //10-mail.conf// file.
 +
 +<code bash>sudo nano /etc/dovecot/conf.d/10-mail.conf</code>
 +
 +In part 2, we used the following ''mail_location''. Email messages are stored under the ''Maildir'' directory under each user’s home directory.
 +
 +<code>mail_location = maildir:~/Maildir</code>
 +
 +Since we are using virtual mailbox domain now, we need to enable mail_home for the virtual users by adding the following line in the file, because virtual users don’t have home directories by default.
 +
 +<code>mail_home = /var/vmail/%d/%n/</code>
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-box-location.png |}}
 +
 +Save and close the file. Then edit the //10-auth.conf// file.
 +
 +<code bash>sudo nano /etc/dovecot/conf.d/10-auth.conf</code>
 +
 +In part 2, we used the following value for ''auth_username_format''.
 +
 +<code>auth_username_format = %n</code>
 +
 +The ''%n'' would drop the domain if it was given. Because in part 2 we were using local Unix account for the username of every email address, we must use ''%n'' to drop the domain, so users were able to login with the full email address.
 +
 +Now we are using virtual mailbox domains, which means the username of every email address includes the domain part, so we need to change the ''auth_username_format'' as follows. ''%u'' won’t drop away the domain. This allows users to login with the full email address.
 +
 +<code>auth_username_format = %u</code>
 +
 +Uncomment the following line at the end of this file, so Dovecot can query user information from MySQL/MariaDB database.
 +
 +<code>!include auth-sql.conf.ext</code>
 +
 +Now you probably don’t want local Unix users to send emails without registering email addresses in PostfixAdmin, then comment out the following line by adding the # character at the beginning, so Dovecot won’t query the local ''/etc/passwd'' or ''/etc/shadow'' file.
 +
 +<code>#!include auth-system.conf.ext</code>
 +
 +It can be helpful to add the following two lines in this file to debug login issues. The login errors would be logged into ''/var/log/mail.log'' file. (Once users can login without problems, you can comment out the following two lines.)
 +
 +<code>auth_debug = yes
 +auth_debug_passwords = yes</code>
 +
 +{{ tutoriaux:debian-email:debian-virtualmail-auth-config.png |}}
 +
 +Save and close the file.
 +
 +Edit the //dovecot-sql.conf.ext// file.
 +
 +<code bash>sudo nano /etc/dovecot/dovecot-sql.conf.ext</code>
 +
 +Here is the content that you should have in this file. By default, all lines in this file are commented out, so you can simply copy and paste them at the bottom. Replace postfixadmin_password with the postfixadmin password you set in Step 2.
 +
 +<code>
 +driver = mysql
 +connect = host=localhost dbname=postfixadmin user=postfixadmin password=postfixadmin_password
 +default_pass_scheme = ARGON2I
 +password_query = SELECT username AS user,password FROM mailbox WHERE username = '%u' AND active='1'
 +user_query = SELECT maildir, 2000 AS uid, 2000 AS gid FROM mailbox WHERE username = '%u' AND active='1'
 +iterate_query = SELECT username AS user FROM mailbox
 +</code>
 +
 +Restart Dovecot.
 +
 +<code bash>sudo systemctl restart dovecot</code>
 +
 +When a user tries to log in, Dovecot would use the Argon2 algorithm to generate a password hash from the password entered by the user, then compare it with the password hash stored in the database. If they match, then the user can log in successfully.
 +
 +===== Add Domain and Mailboxes in PostfixAdmin =====
 +
 +Log in to PostfixAdmin web interface as the admin. Click the ''Domain List'' tab and select ''New Domain'' to add a domain. You can choose how many aliases and mailboxes are allowed for this domain.
 +
 +[[..:debian_postfixadmin_add_domain]]
 +
 +Then click ''Virtual List'' tab and select ''Add Mailbox'' to add a new email address for your domain.
 +
 +[[..:debian_postfixadmin_create_a_new_mailbox]]
 +
 +Next, you can open your desktop email client such as Mozilla Thunderbird and add a mail account.
 +
 +  * Liste à puceIn the incoming server section, select IMAP protocol, enter ''mail.your-domain.com'' as the server name, choose port 143 and STARTTLS. Choose ''normal password'' as the authentication method.
 +  * In the outgoing section, select SMTP protocol, enter ''mail.your-domain.com'' as the server name, choose port 587 and STARTTLS. Choose ''normal password'' as the authentication method.
 +
 +[[..:thunderbird-mail-client-configuration]]
 +
 +<WRAP round tip>
 +You can also use port 993 with SSL/TLS encryption for IMAP, and use port 465 with SSL/TLS encryption for SMTP. You should **not** use port 25 as the SMTP port in mail clients to submit outgoing emails.
 +</WRAP>
 +
 +You should now be able to connect to your own email server and also send and receive emails with your desktop email client! Note that you cannot use local Unix accounts to login now. You must log in with the virtual user created from PostfixAdmin web interface.
 +
 +===== Troubleshooting Tips =====
 +
 +As a rule of thumb, you should always check the mail log (''/var/log/mail.log'') on your mail server when an error happens. The following is a list of specific errors and troubleshooting tips.
 +
 +==== Can’t login from Mail Clients ====
 +
 +If you can’t log into your mail server from a desktop mail client, scan your mail server to find if the ports are open. Note that you should run the following command from another Linux computer or server. If you run it on your mail server, then the ports will always appear to be open.
 +
 +<code bash>sudo nmap mail.your-domain.com</code>
 +And check if Dovecot is running.
 +
 +<code bash>systemctl status dovecot</code>
 +
 +You can also check the mail log (''/var/log/mail.log''), which may give you some clues. If Dovecot fails to start, the error might not be logged to the ''/var/log/mail.log'' file, you can run the following command to see what’s wrong.
 +
 +<code bash>sudo journalctl -eu dovecot</code>
 +
 +If you see the following error in the mail log, it’s likely that you didn’t set a correct password in the ''.cf'' files under ''/etc/postfix/sql/'' directory.
 +
 +<code>
 +postfix/trivial-rewrite[28494]: warning: virtual_alias_domains: proxy:mysql:/etc/postfix/sql/mysql_virtual_alias_maps.cf: table lookup problem
 +postfix/trivial-rewrite[28494]: warning: virtual_alias_domains lookup failure
 +</code>
 +If you see the following error in the mail log, it’s because you forgot to add ''mail_location = maildir:~/Maildir'' in the ''/etc/dovecot/conf.d/10-mail.conf'' file.
 +
 +<code>open(/var/mail/username@domain.com) failed: Permission denied (euid=2000(vmail) egid=2000(vmail) missing +w perm: /var/mail, we're not in group 8(mail), dir owned by 0:8 mode=0775</code>
 +
 +==== Cloudflare DNS ====
 +
 +As I said in part 1, if you use Cloudflare DNS service, you should not enable the CDN (proxy) feature when creating DNS A record and AAAA record for the hostname of your mail server. Cloudflare doesn’t support SMTP or IMAP proxy.
 +
 +==== Relay Access Denied ====
 +
 +If you see the “relay access denied” error when trying to send emails from a mail client, it’s most likely that you use port 25 as the SMTP port in your mail client. As I said a while ago, you should use port 587 or 465 as the SMTP port in mail clients (Mozilla Thunberbird, Microsoft Outlook, etc) to submit outgoing emails. Port 25 should be used for SMTP server to SMTP server communications.
 +
 +[[..:postfix_dovecot_relay_access_denied]]
 +
 +==== iOS Mail App ====
 +
 +If you use the iOS Mail app to log into your mail server and encounter the following error.
 +
 +ios the mail server is not responding
 +
 +You can try to fix it by enforcing SSL encryption, for both SMTP and IMAP.
 +
 +ios mail enforce SSL encryption
 +
 +Fun fact: It seems the iOS Mail app has difficulty in supporting STARTTLS on IMAP port 143, but it supports STARTTLS on the submission port 587.
 +
 +==== Temporary Lookup Failure ====
 +
 +If your mail server was working fine for some time, but suddenly you find the following error in the mail log,
 +
 +<code>
 +Aug 25 20:25:24 mx postfix/trivial-rewrite[3313]: warning: virtual_alias_domains: proxy:mysql:/etc/postfix/sql/mysql_virtual_alias_maps.cf: table lookup problem
 +Aug 25 20:25:24 mx postfix/trivial-rewrite[3313]: warning: virtual_alias_domains lookup failure
 +Aug 25 20:25:24 mx postfix/submission/smtpd[3464]: NOQUEUE: reject: 451 4.3.0 <user@your-domain.com>: Temporary lookup failure;  proto=ESMTP
 +Aug 25 20:25:24 mx postfix/submission/smtpd[3464]: Temporary lookup failure
 +</code>
 +
 +It’s likely that your MariaDB/MySQL database stopped somehow. You can use the following command to check when your database server stopped.
 +
 +<code bash>sudo journalctl -eu mariadb</code>
 +or
 +
 +<code bash>sudo journalctl -eu mysql</code>
 +
 +A common cause for this situation is that your server is out-of-memory. Check if your server has enough memory.
 +
 +<code bash>htop</code>
 +or
 +
 +<code bash>free -m</code>
 +
 +===== Automatically Clean the Junk Folder and Trash Folder =====
 +
 +To delete emails in Junk folder for all users, you can run
 +
 +<code bash>sudo doveadm expunge -A mailbox Junk all</code>
 +
 +To delete emails in Trash folder, run
 +
 +<code bash>sudo doveadm expunge -A mailbox Trash all</code>
 +
 +I think it’s better to clean emails that have been in the Junk or Trash folder for more than 2 weeks, instead of cleaning all emails.
 +
 +<code bash>sudo doveadm expunge -A mailbox Junk savedbefore 2w</code>
 +
 +Then add a cron job to automate the job.
 +
 +<code bash>sudo crontab -e</code>
 +
 +Add the following line to clean Junk and Trash folder every day.
 +
 +<code>@daily doveadm expunge -A mailbox Junk savedbefore 2w;doveadm expunge -A mailbox Trash savedbefore 2w</code>
 +
 +You also need to allow the www-data user to read certificate files by adding the following line.
 +
 +<code>@daily setfacl -R -m u:www-data:rx /etc/letsencrypt/live/ /etc/letsencrypt/archive/</code>
 +
 +To receive report when a Cron job produces an error, you can add the following line above all Cron jobs.
 +
 +<code>MAILTO="you@your-domain.com"</code>
 +
 +Save and close the file. And you’re done.
 +
 +===== Change User Password in PostfixAdmin =====
 +
 +Users can log into PostfixAdmin at ''https://postfixadmin.example.com/users/login.php'', then change their passwords.
 +
 +===== Restricting Access to Sendmail =====
 +
 +By default, any local user can use the ''sendmail'' binary to submit outgoing emails. Now that your mail server is using virtual mailboxes, you might want to restrict access to the ''sendmail'' binary to trusted local users only, so a malicious user can’t use it to send a large volume of emails to damage your mail server’s reputation. Edit the Postfix main configuration file.
 +
 +<code bash>sudo nano /etc/postfix/main.cf</code>
 +
 +Add the following line to the end of this file, so only the root, www-data and vmail user can submit emails via sendmail. You can also add other usernames.
 +
 +<code>authorized_submit_users = root,www-data,vmail</code>
 +
 +Save and close the file. Then restart Postfix.
 +
 +<code bash>sudo systemctl restart postfix</code>
 +
 +====== How to Upgrade PostfixAdmin ======
 +
 +Sometimes there might be bugs in the current PostfixAdmin that can be fixed by upgrading to a new version. It’s very simple to upgrade PostfixAdmin. When a new version of PostfixAdmin comes out, then you need to
 +
 +  * Make a copy of the ''/var/www/postfixadmin/config.local.php'' file to your home directory.
 +  * Remove the PostfixAdmin web directory (''sudo rm /var/www/postfixadmin/ -r'')
 +  * Go through step 2, step 3, step 5, and step 10 again in this tutorial. When doing step 5, simply copy the ''config.local.php'' file from your home directory. In step 10, the PostfixAdmin database schema will be automatically updated when you visit the ''setup.php'' web page.
 +
 +I once had a login loop problem in my PostfixAdmin installation and it’s fixed by upgrading PostfixAdmin to the latest version.
 +
 +===== Next Step =====
 +
 +I hope this tutorial helped you install and use PostfixAdmin on Debian to create virtual mailboxes. In part 4, I will show you how to set up SPF and DKIM with Postfix to improve email deliverability and in a future tutorial, I’m going to show you how to host multiple domains with PostfixAdmin.
 +
 +If you want to access emails from a web browser, then I recommend Roundcube, which is a very popular and featured-rich open-source webmail client. As always, if you found this post useful, subscribe to our free newsletter to get more tips and tricks. Take care 🙂
 +
 +{{page>install-email-server-footer}}