E-Mail/Server/Setup
E-Mail-Server-Setup mit Postfix, Dovecot und MySQL
Beschreibung
Konfiguration eines E-Mail-Servers mit Postfix, Dovecot und MySQL
- Einrichten eines Linux-Servers mit geeigneten Sicherheitsmaßnahmen
- DNS konfigurieren
- Datenbank einrichten
- Postfix installieren und einrichten
- Dovecot installieren und einrichten
- Testen des E-Mail-Server
- Weitere Domänen und E-Mail-Adressen hinzuzufügen
DNS konfigurieren
Wenn Sie bereit sind, das DNS zu aktualisieren und mit dem Senden von E-Mails an den Server zu beginnen, bearbeiten Sie die DNS-Einträge der Domäne, um Ihren E-Mail-Server zu definieren:
- Fügen Sie einen DNS-Eintrag für Ihren E-Mail-Server hinzu
- Dies kann entweder ein A-Eintrag sein, der auf die IP-Adresse Ihres Servers verweist, oder ein CNAME-Eintrag, der auf einen Domänennamen verweist.
- Unabhängig davon, welcher Eintrag gewählt wird, setzen Sie den Hostnamen/Namen auf Mail.
- MX-Record
Setzen Sie den Hostnamen/Namen auf @, den Mailserver auf mail.example.com (ersetzen Sie example.com durch Ihren Domainnamen) und die Priorität auf 10.
- Beispielausgabe
@ MX 10 mail.example.com. mail A 192.0.2.0
- Vergewissern Sie sich, dass der MX-Eintrag für alle Domänen und Subdomänen geändert wird, die E-Mails empfangen könnten.
- Wenn Sie eine neue Domäne einrichten, können Sie diese Schritte vor der Konfiguration des Mailservers durchführen.
Aktualisieren der Hosts-Datei
Stellen Sie sicher, dass
- die Hosts-Datei eine Zeile für die öffentliche IP-Adresse enthält
- mit dem Fully Qualified Domain Name (FQDN) verbunden ist
Im folgenden Beispiel ist 192.0.2.0 die öffentliche IP-Adresse, mail ist der lokale Hostname, und mail.example.com ist der FQDN
- /etc/hosts
127.0.0.1 localhost.localdomain localhost 192.0.2.0 mail.example.com mail
Install SSL Certificate
You will need to install an SSL certificate on your mail server prior to completing the Dovecot configuration steps. The SSL certificate will authenticate the identity of the mail server to users and encrypt the transmitted data between the user’s mail client and the mail server.
While you can generate an SSL certificate through any certificate authority, we recommend using Certbot to quickly and easily generate a free certificate. Follow these Certbot instructions, selecting your Linux distribution and web server software (or “None” if this server is only functioning as a mail server). Once installed, run Certbot with the certonly option and type in the FQDN name of your mail server (such as mail.example.com):
# certbot certonly --standalone
You can also reference the Install an SSL Certificate with Certbot guide. Make a note of the file paths for the certificate and private key. You will need the path to each during the Dovecot configuration steps.
Install Packages
- Log in via SSH
$ ssh username@<IP-Adresse>
- Update your system
# apt-get update # apt-get upgrade
- Install the packages
# apt-get install postfix postfix-mysql dovecot-core dovecot-imapd dovecot-pop3d dovecot-lmtpd dovecot-mysql mysql-server
This will install the mysql-server package, which isn’t available by default on some newer versions of Debian. If you receive a message stating that the package is not available, install mariadb-server instead. MariaDB is a drop-in MySQL replacement.
You will not be prompted to enter a password for the root MySQL user for recent versions of MySQL. This is because on Debian and Ubuntu, MySQL now uses either the unix_socket or auth_socket authorization plugin by default. This authorization scheme allows you to log in to the database’s root user as long as you are connecting from the Linux root user on localhost. When prompted, select Internet Site as the type of mail server the Postfix installer should configure. In the next screen, the System Mail Name should be set to the domain you’d like to send and receive email through.
"Choose “Internet Site” for Postfix." "Set the system mail name for Postfix."
Database
Data for the mail server’s users (email addresses), domains, and aliases are stored in a MySQL (or MariaDB) database. Both Dovecot and Postfix interact with this data.
- Follow the steps below to create the database and add tables for virtual users, domains and aliases
- Use the mysql_secure_installation tool to configure additional security options. This tool will ask if you want to set a new password for the MySQL root user, but you can skip that step:
# mysql_secure_installation
Answer Y at the following prompts:
- Remove anonymous users?
- Disallow root login remotely?
- Remove test database and access to it?
- Reload privilege tables now?
- Log in to MySQL as a root user
# mysql -u root -p
- Create a new database
CREATE DATABASE mailserver;
- Create the MySQL user and grant the new user permissions over the database.
Replace password with a secure password for mailuser
CREATE USER 'mailuser'@'127.0.0.1' IDENTIFIED BY 'password'; GRANT SELECT ON mailserver.* TO 'mailuser'@'127.0.0.1'; # Run FLUSH to reload the MySQL database and apply the change: FLUSH PRIVILEGES;
- Switch to the new mailserver database
USE mailserver;
- Create a table for the domains that will receive mail
CREATE TABLE `virtual_domains` ( `id` int(11) NOT NULL auto_increment, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- Create a table for all of the email addresses and passwords
CREATE TABLE `virtual_users` ( `id` int(11) NOT NULL auto_increment, `domain_id` int(11) NOT NULL, `password` varchar(106) NOT NULL, `email` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`), FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- Create a table for the email aliases
CREATE TABLE `virtual_aliases` ( `id` int(11) NOT NULL auto_increment, `domain_id` int(11) NOT NULL, `source` varchar(100) NOT NULL, `destination` varchar(100) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Adding a Domain within MySQL
- Verify that you are still logged into the MySQL shell. If not, run
# mysql -u root -p to access MySQL.
- Add the domains to the virtual_domains table. Replace the values for example.com and hostname with your own settings
INSERT INTO mailserver.virtual_domains (name) VALUES ('example.com');
- Verify the alias was added correctly by running a SELECT query on the virtual_domains table. Make a note of the corresponding id next to the domain as this will be used when adding emails and aliases.
SELECT * FROM mailserver.virtual_domains;
If needed, repeat this process to add another domain.
Adding an Email Address within MySQL
- If you are still logged in to MySQL, return to your main Linux shell by typing exit and hitting enter.
- Generate a hash using the SHA512-CRYPT encryption scheme by running the command below, replacing password with the password you’d like to use for the email user.
# doveadm pw -s SHA512-CRYPT -p "password" -r 5000
The output will look similar to {SHA512-CRYPT}$6$hvEwQ.... Copy this output, ignoring the first 14 characters of {SHA512-CRYPT}. Since the SHA512-CRYPT scheme was used, the password should start with $6$.
- Log back into MySQL as the root user:
# mysql -u root -p
- Add the email address and password hash to the virtual_users table. The domain_id value (currently set to '1') references the virtual_domain table’s id value. If you added more than one domain, replace this value to correspond with the desired domain. Replace user@example.com with the email address that you wish to configure on the mail server. Replace hash with password hash generated in a previous step.
INSERT INTO mailserver.virtual_users (domain_id, password , email) VALUES ('1', 'hash', 'user@example.com');
- Verify the email was added correctly by running a SELECT query on the virtual_users table.
SELECT * FROM mailserver.virtual_users;
- If needed, repeat this process to add another email address.
Alternatively, the password hash can be generated directly within the MySQL INSERT statement above by replacing 'hash' (deleting the single quote characters as well) with one of the following:* Using the ENCRYPT() function: ENCRYPT('password', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), replacing password with the plain text password desired for the email user. This function has been removed from MySQL 5.8 and above.
- Using the SHA2() function: TO_BASE64(UNHEX(SHA2('password', 512))), replacing password with the plain text password desired for the email user. This function generates the hash in a slightly different scheme. When configuring the Dovecot MYSQL settings (/etc/dovecot/dovecot-sql.conf.ext) in this guide, set default_pass_scheme to SHA512 instead of SHA512-CRYPT.
Adding an Alias within MySQL
An email alias forwards all emails it receives to another email address. While not required, you can follow the steps below to add an email alias.# Verify that you are still logged into the MySQL shell. If not, run # mysql -u root -p to access MySQL.
- Add the alias to the virtual_aliases table. The domain_id value (currently set to '1') references the virtual_domain table’s id value. If you added more than one domain, replace this value to correspond with the desired domain. Replace alias@example.com with the desired alias. Replace user@example.com with the email address that you wish to forward email to.
INSERT INTO mailserver.virtual_aliases (domain_id, source, destination) VALUES ('1', 'alias@example.com', 'user@example.com');
- Verify the alias was added correctly by running a SELECT query on the virtual_aliases table.
SELECT * FROM mailserver.virtual_aliases;
- If needed, repeat this process to add another email alias.
Postfix MTA Email Server
Postfix is a Mail Transfer Agent (MTA) that relays mail between your Server and the internet. It is highly configurable, allowing for great flexibility. This guide maintains many of Posfix’s default configuration values.
How Do Postfix And Dovecot Work Together?
Postfix and Dovecot work together to help make email servers function as intended (sending and receiving email) and accessible to whichever email client the end user wishes to use. While Postfix manages email delivery and receipt, Dovecot allows email clients to connect to these emails when we want to read them.
Configuration File Settings for Postfix Email Server
The main.cf file is the primary configuration file used by Postfix.# If you are still logged in to MySQL, return to your main Linux shell by typing exit and hitting enter.
- Make a copy of the default Postfix configuration file in case you need to revert to the default configuration:
# cp /etc/postfix/main.cf /etc/postfix/main.cf.orig
- Edit the /etc/postfix/main.cf file, replacing any occurrences of example.com with your domain name and verifying that the paths to the SSL certificate and private key are correct. Here is an example file that can be used:
- File: /etc/postfix/main.cf
# See /usr/share/postfix/main.cf.dist for a commented, more complete version
# 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 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 2 on # fresh installs. compatibility_level = 2 # TLS parameters smtpd_tls_cert_file=/etc/letsencrypt/live/example.com/fullchain.pem smtpd_tls_key_file=/etc/letsencrypt/live/example.com/privkey.pem smtpd_use_tls=yes smtpd_tls_auth_only = yes smtp_tls_security_level = may smtpd_tls_security_level = may smtpd_sasl_security_options = noanonymous, noplaintext smtpd_sasl_tls_security_options = noanonymous # Authentication smtpd_sasl_type = dovecot smtpd_sasl_path = private/auth smtpd_sasl_auth_enable = yes # See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for # information on enabling SSL in the smtp client. # Restrictions smtpd_helo_restrictions == permit_mynetworks, permit_sasl_authenticated, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname smtpd_recipient_restrictions == permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_unlisted_recipient, reject_unauth_destination smtpd_sender_restrictions == permit_mynetworks, permit_sasl_authenticated, reject_non_fqdn_sender, reject_unknown_sender_domain smtpd_relay_restrictions == permit_mynetworks, permit_sasl_authenticated, defer_unauth_destination # See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for # information on enabling SSL in the smtp client. myhostname = example.com alias_maps = hash:/etc/aliases alias_database = hash:/etc/aliases mydomain = example.com myorigin = $mydomain mydestination = localhost 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 # Handing off local delivery to Dovecot's LMTP, and telling it where to store mail virtual_transport = lmtp:unix:private/dovecot-lmtp # Virtual domains, users, and aliases virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf, mysql:/etc/postfix/mysql-virtual-email2email.cf # Even more Restrictions and MTA params disable_vrfy_command = yes strict_rfc821_envelopes = yes #smtpd_etrn_restrictions = reject #smtpd_reject_unlisted_sender = yes #smtpd_reject_unlisted_recipient = yes smtpd_delay_reject = yes smtpd_helo_required = yes smtp_always_send_ehlo = yes #smtpd_hard_error_limit = 1 smtpd_timeout = 30s smtp_helo_timeout = 15s smtp_rcpt_timeout = 15s smtpd_recipient_limit = 40 minimal_backoff_time = 180s maximal_backoff_time = 3h # Reply Rejection Codes invalid_hostname_reject_code = 550 non_fqdn_reject_code = 550 unknown_address_reject_code = 550 unknown_client_reject_code = 550 unknown_hostname_reject_code = 550 unverified_recipient_reject_code = 550 unverified_sender_reject_code = 550
Create the file for virtual_mailbox_domains. Replace the value for password with your database user’s password. If you used a different name for your database user and dbname replace those with your own values:* File: /etc/postfix/mysql-virtual-mailbox-domains.cf
# systemctl restart postfix Testing PostfixWe can test the Postfix configuration by using the postmap command, which can query Postfix’s lookup tables.# Enter the following command to ensure that Postfix can query the virtual_domains table. Replace example.com with the first name value. The command should return 1 if it is successful: # postmap -q example.com mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
# postmap -q email1@example.com mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
# postmap -q alias@example.com mysql:/etc/postfix/mysql-virtual-alias-maps.cf Master Program Settings
Make a copy of the /etc/postfix/master.cf file: # cp /etc/postfix/master.cf /etc/postfix/master.cf.orig
# File: /etc/postfix/master.cf # # Postfix master process configuration file. For details on the format # of the file, see the master(5) manual page (command: "man 5 master" or # on-line: http://www.postfix.org/master.5.html). # # Do not forget to execute "postfix reload" after editing this file. # # ========================================================================== # service type private unpriv chroot wakeup maxproc command + args # (yes) (yes) (yes) (never) (100) # ========================================================================== smtp inet n - n - - smtpd #smtp inet n - - - 1 postscreen #smtpd pass - - - - - smtpd #dnsblog unix - - - - 0 dnsblog #tlsproxy unix - - - - 0 tlsproxy submission inet n - y - - smtpd -o syslog_name=postfix/submission -o smtpd_tls_security_level=encrypt -o smtpd_sasl_auth_enable=yes -o smtpd_sasl_type=dovecot -o smtpd_sasl_path=private/auth -o smtpd_reject_unlisted_recipient=no -o smtpd_client_restrictions=permit_sasl_authenticated,reject -o milter_macro_daemon_name=ORIGINATING smtps inet n - - - - smtpd -o syslog_name=postfix/smtps -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes -o smtpd_sasl_type=dovecot -o smtpd_sasl_path=private/auth -o smtpd_client_restrictions=permit_sasl_authenticated,reject -o milter_macro_daemon_name=ORIGINATING [...]
of the /etc/postfix directory to restrict permissions to allow only its owner and the corresponding group # chmod -R o-rwx /etc/postfix
# systemctl restart postfix DovecotDovecot is a POP3 and IMAP server, which provides email clients with access to emails on the server. It also acts as the Local Delivery Agent (LDA), which takes email from Postfix (or other MTA / mail server software) and stores them. When Dovecot was installed in previous steps, additional Dovecot modules (including dovecot-antispam, dovecot-solr, dovecot-ldap, and dovecot-sieve) were also installed. These modules help Dovecot with a range of functions like spam filtering, user directory management, enabling a full text search, and mail filtering. Configuring DovecotIn this section, we’ll edit Dovecot’s configuration files to use IMAP (and POP3), add our domain details, and configure user authentication. This will also cover configuring Dovecot to force users to use SSL when they connect so that their passwords are never sent to the server in plain text.# Copy all of the configuration files so you can easily revert back to them if needed: # cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf.orig # cp /etc/dovecot/conf.d/10-mail.conf /etc/dovecot/conf.d/10-mail.conf.orig # cp /etc/dovecot/conf.d/10-auth.conf /etc/dovecot/conf.d/10-auth.conf.orig # cp /etc/dovecot/dovecot-sql.conf.ext /etc/dovecot/dovecot-sql.conf.ext.orig # cp /etc/dovecot/conf.d/10-master.conf /etc/dovecot/conf.d/10-master.conf.orig # cp /etc/dovecot/conf.d/10-ssl.conf /etc/dovecot/conf.d/10-ssl.conf.orig
# mkdir -p /var/mail/vhosts/example.com This directory will serve as storage for mail sent to your domain.* Create the vmail group with ID 5000. Add a new user vmail to the vmail group. This system user will read mail from the server. # groupadd -g 5000 vmail # useradd -g vmail -u 5000 vmail -d /var/mail* Change the owner of the /var/mail/ folder and its contents to belong to vmail: # chown -R vmail:vmail /var/mail* Edit the user authentication file, located in /etc/dovecot/conf.d/10-auth.conf. Uncomment the following variables and replace with the file excerpt’s example values:
Note For reference, view a complete 10-auth.conffile.* Edit the /etc/dovecot/conf.d/auth-sql.conf.ext file with authentication and storage information. Ensure your file contains the following lines. Make sure the passdb section is uncommented, that the userdb section that uses the static driver is uncommented and updated with the right argument. Then comment out the userdb section that uses the sql driver:
The password_query variable uses email addresses listed in the virtual_users table as the username credential for an email account. To use an alias as the username:# Add the alias as the source and destination email address to the virtual_aliases table.
Note For reference, view a complete dovecot-sql.conf.extfile.* Change the owner and group of the /etc/dovecot/ directory to vmail and dovecot: # chown -R vmail:dovecot /etc/dovecot* Change the permissions on the /etc/dovecot/ directory to be recursively read, write, and execute for the owner of the directory: # chmod -R o-rwx /etc/dovecot* Edit the service settings file /etc/dovecot/conf.d/10-master.conf: Note When editing the file, be careful not to remove any opening or closing curly braces. If there’s a syntax error, Dovecot will crash silently. You can check /var/log/upstart/dovecot.log to debug the error. Here is an example of a complete 10-master.conf file. Disable unencrypted IMAP and POP3 by setting the protocols' ports to 0. Uncomment the port and ssl variables: File: /etc/dovecot/conf.d/10-master.conf
Find the service lmtp section of the file and use the configuration shown below: File: /etc/dovecot/conf.d/10-master.conf
Locate service auth and configure it as shown below: File: /etc/dovecot/conf.d/10-master.conf
In the service auth-worker section, uncomment the user line and set it to vmail:* File: /etc/dovecot/conf.d/10-master.conf
Save the changes to the /etc/dovecot/conf.d/10-master.conf file.* Edit /etc/dovecot/conf.d/10-ssl.conf file to require SSL and to add the location of your domain’s SSL certificate and key. Replace example.com with your domain:
# systemctl restart dovecot Testing the Email Server with Mailutils
# apt-get install mailutils
echo "Email body text" | # mail -s "Email subject line" recipient@gmail.com -aFrom:email1@example.com
# mail -f /var/mail/vhosts/example.com/email1 When prompted, enter the number corresponding to the email you would like to view: "/var/mail/vhosts/example.com/": 9 messages 5 new 4 unread U 1 John Doe Wed Jun 27 16:00 57/2788 Test email 1 U 2 John Doe Wed Jun 27 16:02 56/2761 Test email 2 U 3 John Doe Wed Jun 27 16:35 15/594 Test email 3 U 4 John Doe Wed Jun 27 16:42 71/3535 Test email 4 >N 5 John Doe Mon Jul 2 10:55 13/599 Subject of the Email ? The email message header and body should display. Consider adding spam and virus filtering and a webmail client. See Troubleshooting problems with Postfix, Dovecot, and MySQL for debugging steps. Configuring an Email ClientYou can set up an email client to connect to your mail server. Many clients detect server settings automatically. Manual configuration requires the following parameters:
Note The Thunderbird email client will sometimes have trouble automatically detecting account settings when using Dovecot. After it fails to detect the appropriate account settings, you can set up your email account manually. Add in the appropriate information for each setting, using the above values, leaving no setting on Auto or Autodetect. Once you have entered all the information about your mail server and account, press Done rather Re-Test and Thunderbird should accept the settings and retrieve your mail. Managing Spam With SpamAssassin: Stop spam on Postfix, Dovecot, And MySQLApache SpamAssassin is a free and open source platform that allows us to find and filter out spam email. This software is commonly used in tandem with Postfix and Dovecot.# Install SpamAssassin: # apt-get install spamassassin spamc
# adduser spamd --disabled-login
Here is a detailed documentation of SpamAssassin’s configuration file that you can refer to while working through these next steps.* Configure the Postfix email server to check each email with a score > 5.0, mark it as SPAM, and send it directly to the junk folder. Add or adjust the following lines inside /etc/spamassassin/local.cf to setup your anti-spam rules:
# systemctl start spamassassin # systemctl enable spamassassin If not using systemd (as is the case with Debian 7 and earlier), edit the /etc/default/spamassassin configuration file instead. Set the ENABLED parameter to 1.
# systemctl restart postfix KonfigurationDateienSicherheitSiehe auchLinksProjekt-HomepageWeblinks
EinzelnachweiseTestfragenTestfrage 1 Antwort1
Testfrage 2 Antwort2
Testfrage 3 Antwort3
Testfrage 4 Antwort4
Testfrage 5 Antwort5
|