- Установка и настройка SMTP-сервера Postfix в Ubuntu 20.04
- Требования
- 1: Установка Postfix
- 2: Настройка Postfix
- 3: Тестирование SMTP-сервера
- 4: Пересылка почты
- 5: Настройка SMTP-шифрования
- Заключение
- Install, Secure, Access and Configure Linux Mail Server (Postfix)
- Linux SMTP server
- Mail service components
- Setup Email server
- Configure Linux mail server
- myhostname
- mydomain
- myorigin
- mydestination
- mail_spool_directory
- mynetworks
- smtpd_banner
- inet_protocols
- Checking the mail queue
- Test Linux mail server
- Secure mailboxes from spam using SpamAssassin
- Securing SMTP connection
- Using Let’s Encrypt certificates
- POP3 and IMAP protocol basics
- Installing Dovecot
- Configure Dovecot
- Secure Dovecot
Установка и настройка SMTP-сервера Postfix в Ubuntu 20.04
Postfix – это агент пересылки сообщений (Mail Transfer Agent, или MTA), приложение для обмена электронной почтой. Это руководство поможет вам установить и настроить Postfix только для отправки сообщений локальных приложений. Такая настройка полезна в ситуациях, когда вам нужно регулярно отправлять уведомления ваших приложений по электронной почте или просто обрабатывать большой исходящий трафик, который не поддерживают сторонние провайдеры электронной почты. Кроме того, это позволяет получить легкую альтернативу полноценному SMTP-серверу с сохранением требуемой функциональности.
В этом руководстве мы установим и настроим Postfix как SMTP-сервер исходящей почты. Также мы расскажем, как запрашивать бесплатные сертификаты TLS от Let’s Encrypt и шифровать исходящие электронные письма с их помощью.
Требования
- Сервер Ubuntu 20.04, настроенный по этому мануалу (включая пользователя с доступом к sudo).
- Валидный домен (в мануале используется условный домен your_domain).
- DNS- запись А для домена your_domain, указывающая на IP-адрес вашего сервера.
Примечание: Имя хоста сервера должно соответствовать этому домену или поддомену. Чтобы проверить имя хоста своего сервера, введите команду hostname. Вывод должен совпадать с именем сервера, которое он получил при создании.
1: Установка Postfix
Чтобы установить Postfix, а вместе с ним и ряд вспомогательных программ, необходимых для настройки почты, просто установите пакет mailutils.
Обновите индекс пакетов:
sudo apt update
А затем установите mailtuils:
sudo apt install mailutils
В конце установки будет предложено выбрать тип настройки.
Please select the mail configuration type that best meets your needs.
[…] General type of mail configuration:
No configuration
Internet site
Internet with smarthost
Satellite system
Local only
Рекомендуется выбрать стандартную опцию Internet site. Для этого нажмите Tab и Enter. Если вы видите только описательный текст, нажмите Tab, чтобы выбрать OK, а затем нажмите Enter.
Если диалоговое окно не запустилось автоматически, откройте его вручную:
sudo dpkg-reconfigure postfix
После этого программа предложит выбрать имя почты, которое определяется параметром System mail name.
The ‘mail name’ is the domain name used to ‘qualify’ _ALL_ mail addresses without a domain name.
[…] System mail name:
Поле System mail name должно совпадать с именем сервера, которое вы выбрали при его создании. Укажите имя, а затем нажмите Tab и Enter.
2: Настройка Postfix
Теперь нужно настроить Postfix для отправки и получения сообщений с localhost – то есть с локального хоста, на котором установлен почтовый сервер.
Для этого Postfix должен прослушивать интерфейс loopback – это виртуальный сетевой интерфейс, который используется сервером для внутреннего взаимодействия. Откройте конфигурационный файл Postfix в текстовом редакторе:
sudo nano /etc/postfix/main.cf
Найдите там эти строки:
. . .
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
. . .
Измените значение строки inet_interfaces на loopback-only.
. . .
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = loopback-only
. . .
После этого нужно отредактировать директиву mydestination. Она определяет список доменов, почта которых должна быть доставлена через локальный агент доставки почты local_transport. По умолчанию список выглядит так:
. . .
mydestination = $myhostname, your_domain, localhost.com, , localhost
. . .
Вместо стандартного списка нужно использовать этот:
. . .
mydestination = localhost.$mydomain, localhost, $myhostname
. . .
Если вместо домена вы используете поддомен и хотите, чтобы почта выглядела так, будто она была отправлена с главного домена, добавьте в конец файла main.cf такую строку:
Дополнительный параметр masquerade_domains указывает, для каких доменов нужно удалять часть поддомена в адресе электронной почты.
Сохраните и закройте файл.
Примечание: Если вы разместили несколько доменов в рамках одного сервера, остальные домены можно добавить в настройки Postfix с помощью директивы mydestination.
sudo systemctl restart postfix
3: Тестирование SMTP-сервера
Теперь нужно проверить, может ли Postfix отправлять сообщения на внешний электронный адрес. Для этого используется команда mail, которая также входит в пакет mailutils.
Чтобы отправить тестовое сообщение, введите команду:
echo «This is the body of the email» | mail -s «This is the subject line» your_email_address
Примечание: Вы можете указать другую тему и тело сообщения. Вместо your_email_address используйте валидный адрес электронной почты.
Проверьте почтовый ящик, на который было отправлено сообщение. Если сообщение не появилось, проверьте спам. На данный момент все письма отправляются в незашифрованном виде, потому многие провайдеры будут помечать их как спам. Позже мы настроим шифрование, чтобы устранить эту проблему.
Если вы получили сообщение об ошибке от команды mail или не получили тестовое сообщение на указанный адрес, хотя прошло много времени, убедитесь, что не допустили ошибок в конфигурациях Postfix и что имя вашего сервера и имя хоста направлены на ваш домен.
Обратите внимание, в этой конфигурации адрес в поле From для отправляемых вами тестовых электронных писем будет иметь вид your_user_name@your_domain, где your_user_name – это пользователь сервера, от имени которого вы запускали команду.
4: Пересылка почты
Теперь нам нужно настроить пересылку почты (или форвардинг), чтобы сервер мог предавать сообщения, отправленные пользователю root, на ваш персональный внешний адрес.
Чтобы Postfix отправлял сообщения, сгенерированные системой, на ваш почтовый адрес, отредактируйте файл /etc/aliases.
sudo nano /etc/aliases
Стандартный файл выглядит так:
# See man 5 aliases for format
postmaster: root
Пока что тут есть всего одна директива, которая пересылает все системные письма на root. Чтобы сообщения перенаправлялись на ваш адрес электронной почты, добавьте в конец файла эту строку:
Замените your_email_address своим адресом электронной почты. Сохраните и закройте файл. Чтобы изменения вступили в силу, введите команду:
Эта команда составит базу алиасов, которые использует команда mail.
Теперь проверьте работу пересылки, отправив сообщение пользователю root:
echo «This is the body of the email» | mail -s «This is the subject line» root
Это сообщение должно появиться в вашем почтовом ящике (если его нет, проверьте спам).
Итак, вы настроили перенаправление сообщений на ваш адрес. Теперь давайте настроим шифрование, чтобы защитить ваши сообщения от несанкционированного доступа при их передаче.
5: Настройка SMTP-шифрования
Теперь вы можете включить шифрование SMTP, запросив бесплатный TLS сертификат для вашего домена у сервиса Let’s Encrypt (используя клиент Certbot) и настроив Postfix для его поддержки при отправке сообщений.
Ubuntu включает Certbot в стандартный репозиторий пакетов. Чтобы установить его, введите следующую команду:
sudo apt install certbot
Чтобы подтвердить установку, нажмите Y и Enter.
При начальной настройке сервера вы установили брандмауэр UFW. Вам нужно открыть в нем HTTP-порт 80, чтобы можно было выполнить проверку домена. Запустите следующую команду, чтобы открыть этот порт:
sudo ufw allow 80
Вывод будет выглядеть так:
Rule added
Rule added (v6)
Теперь, когда порт открыт, запустите Certbot, чтобы получить сертификат:
sudo certbot certonly —standalone —rsa-key-size 4096 —agree-tos —preferred-challenges http -d your_domain
Эта команда запросит сертификаты с размером ключа RSA 4096 бит, запустит временный автономный веб-сервер (–standalone) для их проверки и выполнит проверку через порт 80 (–preferred-challenge http). Не забудьте заменить your_domain своим доменом перед запуском команды и введите свой адрес электронной почты при появлении запроса.
Вы получите такой вывод:
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator standalone, Installer None
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for `your_domain`
Waiting for verification.
Cleaning up challenges
IMPORTANT NOTES:
— Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/your_domain/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/your_domain/privkey.pem
Your cert will expire on 2020-07-11. To obtain a new or tweaked
version of this certificate in the future, simply run certbot
again. To non-interactively renew *all* of your certificates, run
«certbot renew»
— 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
Как написано в примечаниях в выводе, ваш сертификат и файл закрытого ключа были сохранены в /etc/letsencrypt/live/your_domain.
Теперь, когда у вас есть сертификат, откройте файл main.cf в редакторе:
sudo nano /etc/postfix/main.cf
Найдите такой раздел:
# 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_security_level=may
smtp_tls_CApath=/etc/ssl/certs
smtp_tls_security_level=may
smtp_tls_session_cache_database = btree:$
Обновите в нем параметры TLS для Postfix (вместо your_domain укажите ваш домен).
# TLS parameters
smtpd_tls_cert_file=/etc/letsencrypt/live/your_domain/fullchain.pem
smtpd_tls_key_file=/etc/letsencrypt/live/your_domain/privkey.pem
smtpd_tls_security_level=may
smtp_tls_CApath=/etc/ssl/certs
smtp_tls_security_level=may
smtp_tls_session_cache_database = btree:$
Сохраните и закройте файл.
Чтоб применить новые настройки, перезапустите Postfix.
sudo systemctl restart postfix
Попробуйте снова отправить письмо:
echo «This is the body of an encrypted email» | mail -s «This is the subject line» your_email_address
Затем проверьте почтовый ящик, на который вы отправили свое тестовое сообщение. Вероятнее всего, оно появится там сразу же, поскольку оно зашифровано (незашифрованные сообщения гораздо чаще помечаются как спам).
Вы можете проверить техническую информацию о сообщении электронной почты на вашем клиенте, чтобы увидеть, что оно действительно зашифровано.
Заключение
Теперь у вас есть сервер исходящей почты Postfix. Шифрование всех исходящих сообщений – это хороший способ сделать ваши сообщения непохожими на спам. Для среды разработки этой меры должно быть достаточно.
Однако если вы собираетесь отправлять электронные письма потенциальным пользователям сайта (например, письма с подтверждением регистрации), вам следует настроить записи SPF, чтобы повысить вероятность того, что сообщения, отправленные с вашего сервера, будут нормально восприняты.
Источник
Install, Secure, Access and Configure Linux Mail Server (Postfix)
If you want to send or receive an email, you should have a mail server. In this post, we will discuss the Linux mail server and how the SMTP (Simple Mail Transfer Protocol) works as well as other mail-related protocols, like Post Office Protocol (POP) and Internet Message Access Protocol (IMAP) and the relationship between them.
Table of Contents
Linux SMTP server
SMTP defines how to send mail from one host to another; it is also system independent, which means the sender and receiver can have different operating systems.
SMTP requires only that a server can send straight ASCII text to another server, you can do this by connecting to the server on port 25, which is the standard SMTP port.
Most Linux distros today come with two of the most common implementations of SMTP, which are sendmail and Postfix.
Sendmail is a famous and free mail server, but it has a little complex design and less secure.
The Postfix took mail server implementation one step further; they developed it with security in mind.
Mail service components
The mail service on any mail server has three components:
Mail user agent (MUA): this component that the user sees and interacts with like Thunderbird and Microsoft Outlook, these user agents are responsible for reading mail and allowing you to compose mail.
Mail transport agent (MTA): this component is responsible for getting the mail from one site to another like Sendmail and Postfix.
Mail delivery agent (MDA): this component is responsible for distributing received messages on the local machine to the appropriate user mailbox like postfix-maildrop and Procmail.
Setup Email server
We chose the Postfix mail server, which is very popular and common among system administrators today.
Postfix is the default mail server on most modern Linux distros.
First, check if it is installed on your system or not:
If not installed, you can install Postfix mail server on Red Hat based distros like this:
Then start the postfix service and enable it on system startup:
On Debian based distros like Ubuntu, you can install it like this:
It will ask you to select the type of configuration of the Postfix mail server during the installation process.
Among the four choices No configuration, Internet site, Internet with smarthost, Satellite system, and Local only, we will choose No configuration option.
Configure Linux mail server
After installing the Postfix mail server, you will need to configure it; you can find most of its configuration files under the /etc/postfix/ directory.
You can find the main configuration for Postfix mail server in /etc/postfix/main.cf file.
This file contains a lot of options like:
myhostname
You can use this option for specifying the hostname of the mail server. This is the Internet hostname, which Postfix will receive emails on it.
The hostnames could be like mail.example.com, smtp.example.com.
mydomain
This option is the mail domain that you will be servicing, like example.com
The syntax is like this:
myorigin
All emails sent from this mail server will look as though it came from this option. You can set this to $mydomain value.
You can use any option value, just precede it with a $ like $mydomain.
mydestination
This option lists the domains that the Postfix server uses for incoming emails.
It can take values like this:
mail_spool_directory
There are two modes of delivery that Postfix mail server can use:
- Directly to a user’s mailbox.
- To a central spool directory, this way, the mail will be in /var/spool/mail with a file for each user.
mynetworks
This option allows you to configure what servers can relay through your Postfix server.
This option should take local addresses like local mail scripts on your server only.
Otherwise, spammers can utilize your mail server to relay their messages and your mail server blacklisted and as a result, you will not be able to receive many emails.
This option has the following syntax:
smtpd_banner
This variable sets the message the server will send when the client after a successful connection.
It is better to change the banner to something that gives no clue the server you are using.
inet_protocols
This option specifies the IP protocol version used for server connections.
If you change the configuration files for the Postfix mail server, you need to reload the service:
When you type any configuration, you may make a mistake, you can check for errors using the following command:
This tool will help you find exactly the line and the error so you can fix it.
Checking the mail queue
Sometimes the mail queues are filled up with messages. This happens due to many reasons, like network failure or any reason that can delay mail delivery.
To check the mail queue on your Linux mail server, use the following command:
This command shows the Postfix mail queue.
If your queue is filled up and the message takes several hours to process, then you should flush the mail queue.
Now, if you check your mail queue, you should find it empty.
Test Linux mail server
After configuring the Postfix mail server correctly, you should test your mail server.
The first step is to use a local mail user agent like mailx or mail, which is a symlink to mailx.
Try to send a mail to someone else on the same server, if this works, then send to a remote site.
Then try to receive a mail from a remote site.
If you have any problems, check the logs. The log file on Red Hat based distros in /var/log/maillog file and on Debian based distros in /var/log/mail.log file or as defined in the rsyslogd configuration.
I recommend you to review the Linux Syslog Server for a detailed explanation about logs and how to configure the rsyslogd.
If you still have problems, try checking your DNS settings and check your MX records using Linux network commands.
Secure mailboxes from spam using SpamAssassin
One of the ways to fight spam is to scan the mailboxes by some tool, searching for certain patterns associated with spam.
One of the best solutions is SpamAssassin, which is open-source.
You can install it like this:
Then start the service and enable it at startup:
Once you’ve installed it, you can check the configuration in
SpamAssassin determines if an email is spam or not based on the result of the different scripts scores.
If the message has a higher score, that means a higher possibility of the mail being spam.
In the configuration file, the parameter required_hits 5 indicates that SpamAssassin will mark an email as spam if its score is five or higher.
The report_safe option takes the values 0, 1, or 2. If set to 0, it means email marked as spam is sent as it is, only modifying the headers to show that it is spam.
If it takes the value 1 or 2, SpamAssassin generates a new report message, and it sends the message to the recipient.
The value 1 means the spam message is coded as content message/rfc822, while if the value is 2, that means the message is coded as text/plain content.
The text/plain is safer since some mail clients execute message/rfc822 and could infect the client computer.
Now we need to integrate it into Postfix. The simplest way to do this is probably by using procmail.
We’ll have to create a file, named
, and add the following content:
Then we edit Postfix configuration file /etc/postfix/main.cf and change
Finally, restart Postfix and SpamAssassin services:
However, SpamAssassin sometimes does not recognize spam messages that led to mailboxes filled with spam messages.
Fortunately, you can filter messages before they enter the Postfix server using Realtime Blackhole Lists (RBLs). That will decrease the load on your mail server and keep your mail server clean.
Open the configuration file of Postfix server /etc/postfix/main.cf and change smtpd_recipient_restrictions option and add the following options like this:
Then restart your postfix server:
The above RBLs are the common ones; you can find more lists on the web and try them.
Securing SMTP connection
It is better to transfer your SMTP traffic over TLS to protect it from Man In The Middle (MITM) attack.
First, we need to generate the certificate and the key using openssl command:
Then add the following option to Postfix configuration file /etc/postfix/main.cf:
Finally, restart your postfix service:
Now, you have to choose the TLS on your client when connecting to the server.
You will receive a warning when you send a mail the first time after changing the setting because the certificate is not signed.
Using Let’s Encrypt certificates
Let’s Encrypt is a free SSL certificate provider that enables you to encrypt your traffic.
Instead of using self-signed certificates that annoy your users about trusting them, you can use this good solution.
First, install letsencrypt:
Or if you are using Debian based distro, you can use the following command:
Then run letsencrypt like this:
You should replace yourdomain.com with your actual domain.
After answering the prompted questions about the contact email, the email server domain, and the license, everything should be OK now.
The certificates will be in:
One last thing you have to do, which is making postfix use those certificates, you can use the following commands:
Don’t forget to replace yourdomain.com with your actual domain.
Finally, restart your postfix server:
POP3 and IMAP protocol basics
So far we’ve seen how SMTP mail server sends and receives emails without problems, but consider the following situations:
- Users need local copies of email for offline viewing.
- mbox file format is not supported. The mbox format is used by many mail user agents like mailx and mutt.
- Users cannot stay connected to a fast network to grab a local copy to read offline.
- Some mail servers don’t give access to the shared mail spool directories for security reasons.
To handle these cases, you should use the mail access protocols.
The most common two popular mail access protocols are Post Office Protocol (POP) and Internet Message Access Protocol (IMAP).
The idea behind POP is very simple: A central Linux mail server remains online all the time and receives and store emails for all users. All received emails are queued on the server until a user grabs them.
When a user wants to send an email, the email client relays it through the central Linux mail server via SMTP normally.
Note that the SMTP server and the POP server can be on the same system without any problem. Most servers do this today.
Features like keeping a master copy of a user’s email on the server were missing, which led to the development of IMAP.
By using IMAP, your Linux mail server will support three modes of access:
- The online mode is similar to having direct file system access to the Linux mail server.
- The offline mode is similar to how POP works, where the client is disconnected from the network except when grabbing an email. In this mode, the server normally does not retain a copy of the email.
- The disconnected mode works by allowing users to keep cached copies of their emails, and the server retains a copy of the email.
There are several implementations for IMAP and POP; the most popular one is the Dovecot server, which provides both protocols.
The POP3, POP3S, IMAP, and IMAPS listen on ports 110, 995, 143, and 993 respectively.
Installing Dovecot
Most Linux distros come with Dovecot preinstalled. However, you can install Dovecot in Red Hat based distros like this:
Debian based distros provide the IMAP and POP3 functionality in two separate packages, you can install them like this:
It will ask you to create self-signed certificates for using IMAP and POP3 over SSL/TLS. Select yes and enter the hostname for your system when prompted.
Then you can run the service and enable it at startup like this:
Configure Dovecot
The main configuration file for Dovecot is
Some Linux distros put the configuration under
directory and use the include directive to include the settings in the files.
You can use the following list of the parameters to configure Dovecot:
protocols: the protocols you want to support.
lmtp means local mail transfer protocol.
listen: IP addresses to listen on.
The asterisk means all ipv4 interfaces and :: means all ipv6 interfaces
userdb: user database for authenticating users.
passdb: password database for authenticating users.
mail_location: this entry in /etc/dovecot/conf.d/10-mail.conf file:
Secure Dovecot
Dovecot comes with generic SSL certificates and key files. Look at this file:
When a user tries to connect to dovecot server, it will show a warning because the certificates are not signed, you can purchase a certificate from a certificate authority if you want.
Or if you go with Let’s Encrypt certificates, you can point to them instead:
Don’t forget to open dovecot server ports in your iptables firewall by adding iptables rules for ports 110, 995, 143, 993, 25.
Or if you are using firewalld, you can do the following:
And again, for troubleshooting, you check the log files /var/log/messages, /var/log/maillog, and /var/log/mail.log files.
Linux mail server is one of the easiest servers to work with, especially the Postfix mail server.
I hope you find the post useful and interesting. Keep coming back.
Источник