postfix
установка postfix на сервер ubuntu
источник: Установка и настройка Postfix в Ubuntu 20.04
The Postfix Home Page
ключи: #postfix #email
только важные выдержки
install
Передаем переменную среды DEBIAN_PRIORITY=low в команду установки.
В связи с этим, процедура установки предложит вам настроить некоторые дополнительные опции.
установка postfix:
sudo apt update
sudo DEBIAN_PRIORITY=low apt install postfix
Процедура установки откроет серию интерактивных диалогов. Для целей данного обучающего модуля введите в диалогах следующие данные:
- General type of mail configuration?: Для данного параметра выберем пункт Internet Site, соответствующий потребностям нашей инфраструктуры.
- System mail name: это базовый домен, используемый для построения корректного адреса электронной почты, когда имеется только часть адреса с именем учетной записи. Допустим, имя хоста вашего сервера mail.example.com. Возможно вы захотите задать для системной почты имя example.com. В этом случае для имени пользователя user1 Postfix будет использовать адрес user1@example.com.
- Root and postmaster mail recipient: это учетная запись Linux, на которую будет перенаправляться почта, адресованная root@ и postmaster@. Используйте для этой цели свою основную учетную запись. В данном примере это имя пользователя sammy.
- Other destinations to accept mail for: определение получателей почты, которых будет принимать этот экземпляр Postfix. Если вам потребуется добавить любые другие домены, для которых этот сервер будет получать почту, добавьте их здесь. В противном случае значений по умолчанию будет достаточно.
- Force synchronous updates on mail queue?: поскольку вы вероятно используете журнальную файловую систему, выберите No.
- Local networks: это перечень локальных сетей, для которых ваш почтовый сервер настроен как реле пересылки сообщений. Значение по умолчанию подойдет для большинства случаев. Если вы пожелаете изменить его, постарайтесь максимально ограничить диапазон сетей.
- Mailbox size limit: используется для ограничения размера сообщений. Значение «0» отключает любые ограничения размера.
- Local address extension character: символ, используемый для отделения обычной части адреса от расширения (используется для создания динамических псевдонимов). Для этого обучающего модуля подойдет значение по умолчанию «+».
- Internet protocols to use: укажите, нужно ли ограничивать версии протокола IP, поддерживаемые Postfix. Для целей данного обучающего модуля выберите вариант «all».
Приведем настройки, использованные в этом руководстве:
- General type of mail configuration?: Internet Site
- System mail name: example.com (не mail.example.com)
- Root and postmaster mail recipient: имя пользователя основной учетной записи Linux (в наших примерах sammy)
- Other destinations to accept mail for: $myhostname, example.com, mail.example.com, localhost.example.com, localhost
- Force synchronous updates on mail queue?: No
- Local networks: 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
- Mailbox size limit: 0
- Local address extension character: +
- Internet protocols to use: all
если понадобится перенастроить:
sudo dpkg-reconfigure postfix
Изменение конфигурации:
Многие параметры конфигурации Postfix заданы в файле /etc/postfix/main.cf. Вместо того, чтобы редактировать этот файл напрямую, вы можете использовать команду Postfix postconf для запроса или установки параметров конфигурации.
структура каталогов в домашнем каталоге
sudo postconf -e 'home_mailbox= Maildir/'
sudo postconf -e 'masquerade_domains=homdy.ru'
расположение таблицы virtual_alias_maps, где произвольные учетные записи электронной почты сопоставляются с системными учетными записями Linux
sudo postconf -e 'virtual_alias_maps= hash:/etc/postfix/virtual'
создать сам файл и начать сопоставление учетных записей электронной почты с учетными записями пользователей в системе Linux.
sudo nano /etc/postfix/virtual
Например, если вы хотите принимать электронную почту на адреса contact@example.com и admin@example.com и доставлять ее пользователю Linux с именем sammy, файл можно настроить следующим образом:
/etc/postfix/virtual
contact@example.com root
admin@example.com root
contact@homdy.ru root
admin@homdy.ru root
support@homdy.ru root
Примените сопоставление:
sudo postmap /etc/postfix/virtual
Перезапустите процесс Postfix
sudo systemctl restart postfix
Вы можете разрешить подключение к службе с помощью следующей команды:
sudo ufw allow Postfix
test mail
echo "This is test email" | mail -s "test subject" support@homdy.ru
инициализация структуры Maildir >>
echo 'export MAIL=~/Maildir' | sudo tee -a /etc/bash.bashrc | sudo tee -a /etc/profile.d/mail.sh
test message by s-nail
cat ~/test_message | s-nail -s 'Test email subject line' -r contact@example.com user@email.com
-s: задает строку темы электронного сообщения
-r: изменение поля «From» письма. По умолчанию в этом поле указан текущий пользователь Linux. Опция -r позволяет заменить его корректным адресом, в том числе определенным в файле /etc/postfix/virtual. Например, в следующей команде используется адрес contact@example.com
просмотр отправленных сообщений:
$ s-nail
? file +sent
Forwarding System Mail
The /etc/aliases file contains a list of alternate names for email recipients.
nano /etc/aliases
/etc/aliases
# See man 5 aliases for format
postmaster: root
root: your_email_address
sudo newaliases
Enabling SMTP Encryption
apt install certbot
ufw allow 80
certbot certonly --nginx --rsa-key-size 4096 --agree-tos --preferred-challenges http -d your_domain
tree /etc/letsencrypt/
sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d postfixadmin.example.com
sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email support@homdy.ru -d e.mail.homdy.ru
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for pa.mail.homdy.ru
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/mail-pa
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/mail-pa
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://pa.mail.homdy.ru
You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=pa.mail.homdy.ru
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/pa.mail.homdy.ru/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/pa.mail.homdy.ru/privkey.pem
Your cert will expire on 2025-04-19. To obtain a new or tweaked
version of this certificate in the future, simply run certbot again
with the "certonly" option. 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
sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email support@homdy.ru -d pa.mail.homdy.ru
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for e.mail.homdy.ru
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/mail-pa
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/mail-pa
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://e.mail.homdy.ru
You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=e.mail.homdy.ru
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/e.mail.homdy.ru/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/e.mail.homdy.ru/privkey.pem
Your cert will expire on 2025-04-19. To obtain a new or tweaked
version of this certificate in the future, simply run certbot again
with the "certonly" option. 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/postfix/main.cf
# TLS parameters
smtpd_tls_cert_file=/etc/letsencrypt/live/your_domain/fullchain.pem
smtpd_tls_key_file=/etc/letsencrypt/live/your_domain/privkey.pem
systemctl restart postfix
How To Install and Configure Postfix as a Send-Only SMTP Server on Ubuntu 22.04
Тестирование почтового сервера Postfix на Ubuntu
Теперь попробуйте проверить, подключается ли ваш почтовый сервер к порту 25, используя следующую команду.
telnet gmail-smtp-in.l.google.com 25
Trying 74.125.200.27...
Connected to gmail-smtp-in.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP k12si849250plk.430 - gsmtp
Приведенное выше сообщение означает, что соединение успешно установлено. Введите quit, чтобы закрыть соединение.
Вы также можете использовать программу mail для отправки и чтения электронных писем, используя следующую команду.
apt-get install mailutils
echo "I'm sending this email using the amazing postman" | mail -s "Testing My Mail Server" home_work_mail@mail.ru
# ctrl+D for send
mail home_work_mail@mail.ru
Cc:
Subject: Testing My Mail Server
I'm sending this email using the amazing postman
mail username@gmail.com
Cc:
Subject: Testing My Postfix Mail Server
I'm sending this email using the postfix mail server from Ubuntu machine
change host name:
root@95-163-235-44:~# hostnamectl
Static hostname: homdy.ru
Transient hostname: 95-163-235-44.cloudvps.regruhosting.ru
Icon name: computer-vm
Chassis: vm
Machine ID: 54132cf7fac4423eaf755f37854a7c4e
Boot ID: 35dc0f28dcbf4b7cbbc18f7a4dc0accd
Virtualization: kvm
Operating System: Ubuntu 20.04.5 LTS
Kernel: Linux 5.4.0-132-generic
Architecture: x86-64
sudo hostnamectl set-hostname host.example.com
sudo hostnamectl set-hostname "Your Pretty HostName" --pretty
sudo hostnamectl set-hostname host.example.com --static
sudo hostnamectl set-hostname host.example.com --transient
sudo hostnamectl set-hostname homdy.ru --transient
Enabling SMTP Encryption
sertbot
sudo apt install certbot
sudo ufw allow 80
sudo certbot certonly --standalone --rsa-key-size 4096 --agree-tos --preferred-challenges http -d your_domain
sudo certbot certonly --standalone --rsa-key-size 4096 --agree-tos --preferred-challenges http -d homdy.ru
sudo certbot certonly --standalone --rsa-key-size 4096 --agree-tos --preferred-challenges http -d your_domain
certbot certonly --nginx --rsa-key-size 4096 --agree-tos --preferred-challenges http -d homdy.ru
How To Install and Configure Postfix as a Send-Only SMTP Server on Ubuntu 22.04 >>
If error: Problem binding to port 80: Could not bind to IPv4 or IPv6.
details information of prefix
# update an SSL certificate on digital ocean with the command
certbot renew
--apache Use the Apache plugin for authentication & installation
--standalone Run a standalone webserver for authentication
--nginx Use the Nginx plugin for authentication & installation
--webroot Place files in a server's webroot folder for authentication
--manual Obtain certificates interactively, or using shell script hooks
details information of prefix >>
проверить запись mx
# +short компактный вывод
dig +short homdy.ru mx
Что такое MX-запись — как её настроить и проверить >>
nano comands: ctrl+G
To select text, move the cursor to the beginning of the text and press Alt+a. This will set a selection mark. Move the cursor to the end of the text you want to select using the arrow keys. The selected text will be highlighted. If you wish to cancel the selection, press Ctrl+6.
Copy the selected text to the clipboard using the Alt+6 command. Ctrl+k will cut the selected text.
If you want to cut whole lines, move the cursor to the line and press Ctrl+k. You can cut multiple lines by hitting Ctrl+k several times.
To paste the text, move the cursor to where you want to put the text and press Ctrl+u.
some using gnu nano text editor
ctrl-g help
alt-a start select
ctrl-6 end select
alt-6 copy selected
ctrl-k cut selected
ctrl-u paste copied
ctrl-o save
ctrl-x exit
nano /etc/postfix/main.cf
mydestination = localhost.$mydomain, localhost, localhost.localdomain
...
inet_protocols = ipv4
...
smtpd_tls_cert_file = /etc/ssl/mail/public.pem
smtpd_tls_key_file = /etc/ssl/mail/private.key
myhostname = mx01.dmosk.ru
virtual_mailbox_base = /var/mail
virtual_alias_maps = proxy:mysql:/etc/postfix/mysql_virtual_alias_maps.cf
virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql_virtual_domains_maps.cf
virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf
virtual_minimum_uid = 1024
virtual_uid_maps = static:1024
virtual_gid_maps = static:1024
virtual_transport = dovecot
dovecot_destination_recipient_limit = 1
smtpd_sasl_auth_enable = yes
smtpd_sasl_exceptions_networks = $mynetworks
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtp_use_tls = yes
smtpd_use_tls = yes
smtpd_tls_auth_only = yes
smtpd_helo_required = yes
Полноценный почтовый сервер на Ubuntu Server
MYSQL
mysql -u root -p
CREATE DATABASE postfix DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
CREATE USER 'postfix'@'localhost' IDENTIFIED BY 'postfix123';
GRANT ALL ON postfix.* TO 'postfix'@'localhost';
quit
install postfix with pg, as way:
apt-get install postfix dovecot-core dovecot-imapd postgresql postfix-pgsql dovecot-lmtpd dovecot-pgsql
Открытие портов
sudo ufw allow 80
sudo ufw allow 25
iptables -I INPUT -p tcp --match multiport --dports 25,465,587 -j ACCEPT
iptables -I INPUT -p tcp --match multiport --dports 143,993 -j ACCEPT
iptables -I INPUT -p tcp --match multiport --dports 80,443 -j ACCEPT
iptables -I INPUT -p tcp --match multiport --dports 110,995 -j ACCEPT
netstat -nltp | grep dovecot
netstat -nltp
ps aux | grep dovecot
ss -tulw
netstat -tulpn
25 — стандартный SMTP;
143 — стандартный IMAP (назащищенный или через STARTTLS);
465 — защищенный SMTP через SSL/TLS;
587 — защищенный SMTP через STARTTLS;
993 — защищенный IMAP через SSL/TLS;
80 — HTTP для порталов Postfixadmin и Roundcube;
443 — защищенный HTTPS для порталов Postfixadmin и Roundcube;
110 — стандартный POP3 (назащищенный или через STARTTLS);
995 — защищенный POP3 через SSL/TLS.
Полноценный почтовый сервер на Ubuntu Server
connect:
# pop
995
starttls
nickname
hosting
# smtp
25
ssl/tls
nickname
hosting
error:
postfix/smtpd[2347284]:
warning: database /etc/postfix/virtual.db is older than source file /etc/postfix/virtual
# postmap /etc/postfix/transport
postmap /etc/postfix/virtual
systemctl restart postfix
Fix: Postfix: Database Older Than Source File
postgreas sql
apt-get install postfix-pgsql
nano /etc/postfix/main.cf
virtual_mailbox_domains = proxy:pgsql:/etc/postfix/pgsql/virtual_domains_maps.cf
virtual_mailbox_maps = proxy:pgsql:/etc/postfix/pgsql/virtual_mailbox_maps.cf
virtual_alias_maps = proxy:pgsql:/etc/postfix/pgsql/virtual_alias_maps.cf
relay_domains = $mydestination, proxy:pgsql:/etc/postfix/pgsql/relay_domains.cf
# 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.
virtual_transport = lmtp:unix:private/dovecot-lmtp
mkdir -p /etc/postfix/pgsql/
nano /etc/postfix/pgsql/virtual_domains_maps.cf
user = postfixadmin
password = postfixadmin_password
hosts = localhost
dbname = postfixadmin
#query = SELECT domain FROM domain WHERE domain='%s' AND active = true
#optional query to use when relaying for backup MX
query = SELECT domain FROM domain WHERE domain='%s' and backupmx = false and active = true
nano /etc/postfix/pgsql/virtual_mailbox_maps.cf
user = postfixadmin
password = postfixadmin_password
hosts = localhost
dbname = postfixadmin
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = true
nano /etc/postfix/pgsql/virtual_alias_maps.cf
user = postfixadmin
password = postfixadmin_password
hosts = localhost
dbname = postfixadmin
query = SELECT goto FROM alias WHERE address='%s' AND active = true
nano /etc/postfix/pgsql/relay_domains.cf
user = postfixadmin
password = postfixadmin_password
hosts = localhost
dbname = postfixadmin
query = SELECT domain FROM domain WHERE domain='%s' and backupmx = true
==============================
nano /etc/postfix/pgsql/virtual_domains_maps.cf
user = postfix
password = 'tgr5%&&5rfUIO)(imu98%T$66tvcfE*()%^HK)(JGH)'
hosts = localhost
dbname = postfix
#query = SELECT domain FROM domain WHERE domain='%s' AND active = true
#optional query to use when relaying for backup MX
query = SELECT domain FROM domain WHERE domain='%s' and backupmx = false and active = true
nano /etc/postfix/pgsql/virtual_mailbox_maps.cf
user = postfix
password = 'tgr5%&&5rfUIO)(imu98%T$66tvcfE*()%^HK)(JGH)'
hosts = localhost
dbname = postfix
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = true
nano /etc/postfix/pgsql/virtual_alias_maps.cf
user = postfix
password = 'tgr5%&&5rfUIO)(imu98%T$66tvcfE*()%^HK)(JGH)'
hosts = localhost
dbname = postfix
query = SELECT goto FROM alias WHERE address='%s' AND active = true
nano /etc/postfix/pgsql/relay_domains.cf
user = postfix
password = 'tgr5%&&5rfUIO)(imu98%T$66tvcfE*()%^HK)(JGH)'
hosts = localhost
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s' and backupmx = true
==============================
==============================
sudo chmod 0640 /etc/postfix/pgsql/*
sudo setfacl -R -m u:postfix:rx /etc/postfix/pgsql/
sudo postconf mydestination
# mydestination = $myhostname, linuxbabe.com, localhost.$mydomain, localhost
postconf -e "mydestination = \$myhostname, localhost.\$mydomain, localhost"
nano /etc/postfix/main.cf
virtual_mailbox_base = /var/vmail
virtual_minimum_uid = 2000
virtual_uid_maps = static:2000
virtual_gid_maps = static:2000
systemctl restart postfix
adduser vmail --system --group --uid 2000 --disabled-login --no-create-home
mkdir -p /var/vmail/
chown vmail:vmail /var/vmail/ -R
Step 12: Configure Postfix to Use PostgreSQL Database
Configure Dovecot to Use PostgreSQL Database
apt-get install dovecot-pgsql
nano /etc/dovecot/conf.d/10-mail.conf
# mail_location = maildir:~/Maildir
mail_home = /var/vmail/%d/%n/
nano /etc/dovecot/conf.d/10-auth.conf
# auth_username_format = %n
auth_username_format = %u
auth_default_realm = example.com
!include auth-sql.conf.ext
#!include auth-system.conf.ext
auth_debug = yes
auth_debug_passwords = yes
## /var/log/mail.log
nano /etc/dovecot/dovecot-sql.conf.ext
driver = pgsql
connect = host=localhost dbname=postfixadmin user=postfixadmin password=postfixadmin_assword
default_pass_scheme = ARGON2I
password_query = SELECT username AS user,password FROM mailbox WHERE username = '%u' AND active = true
user_query = SELECT maildir, 2000 AS uid, 2000 AS gid FROM mailbox WHERE username = '%u' AND active = true
iterate_query = SELECT username AS user FROM mailbox
systemctl restart dovecot
==============================
nano /etc/dovecot/dovecot-sql.conf.ext
driver = pgsql
connect = host=localhost dbname=postfix user=postfix password='tgr5%&&5rfUIO)(imu98%T$66tvcfE*()%^HK)(JGH)'
default_pass_scheme = ARGON2I
password_query = SELECT username AS user,password FROM mailbox WHERE username = '%u' AND active = true
user_query = SELECT maildir, 2000 AS uid, 2000 AS gid FROM mailbox WHERE username = '%u' AND active = true
iterate_query = SELECT username AS user FROM mailbox
systemctl restart dovecot
Part 3: Set Up PostfixAdmin Virtual Mailboxes on Debian Mail Server (PostgreSQL)
error:
postfix/smtpd[2982929]: fatal: no SASL authentication mechanisms
nano /etc/postfix/main.cf
check what process is listening
ss -lnpt
sudo apt install dovecot-lmtpd
sudo nano /etc/dovecot/dovecot.conf
protocols = imap lmtp
sudo nano /etc/dovecot/conf.d/10-master.conf
service lmtp {
unix_listener /var/spool/postfix/private/dovecot-lmtp {
mode = 0600
user = postfix
group = postfix
}
}
Part 2: Install Dovecot IMAP server on Debian & Enable TLS Encryption
How to Start Logging with Postfix
Block Email Spam with Postfix and SpamAssassin Content Filter