Перенаправление всей почты на внешнюю учетную запись, которая может пригодиться для среды разработки
Я буду пересылать всю почту на mail@example.org, используя сервер mail.example.org, пользователя mail и токен аутентификации mail_token.
Обновим систему
$ sudo apt update
Убедитесь, что пакет debconf установлен.
$ sudo apt install debconf
Оставим параметры postfix по умолчанию.
$ cat << EOF | sudo debconf-set-selections postfix postfix/mailname string bullseye postfix postfix/main_mailer_type select No configuration EOF
Установите почтовый сервер postfix, libsasl2-модули поддержки sasl и утилиты mailutils.
$ apt install postfix mailutils libsasl2-modules
Определите домен по умолчанию для почтовых утилит.
$ cat <<EOF | sudo tee /etc/mailutils.conf
address {
email-domain example.org;
};
EOF
В качестве альтернативы можно задать адрес электронной почты.
$ mail --config-help
# Configuration file structure for mail utility.
# For use in global configuration file (/etc/mailutils.conf), enclose it in
# `program mail { ... };
# For more information, use `info mail'.
tls-file-checks {
# Configure safety checks for SSL key file. Argument is a list or sequence
# of check names optionally prefixed with '+' to enable or '-' to disable the
# corresponding check. Valid check names are:
#
# none disable all checks
# all enable all checks
# gwrfil forbid group writable files
# awrfil forbid world writable files
# grdfil forbid group readable files
# ardfil forbid world writable files
# linkwrdir forbid symbolic links in group or world writable
# directories
# gwrdir forbid files in group writable directories
# awrdir forbid files in world writable directories
key-file <arg: list>;
# Configure safety checks for SSL certificate. See above for a description
# of <arg>.
cert-file <arg: list>;
# Configure safety checks for SSL certificate authority file. See above for
# a description of <arg>.
ca-file <arg: list>;
};
address {
# Set the current user email address (default is loginname@defaultdomain).
email-addr <email: address>;
# Set e-mail domain for unqualified user names (default is this host)
email-domain <domain: string>;
};
mailbox {
# Use specified URL as a mailspool directory.
mail-spool <url: string>;
# Create mailbox URL using <pattern>.
mailbox-pattern <pattern: string>;
# Default mailbox type.
mailbox-type <protocol: string>;
# Default user mail folder
folder <dir: string>;
# Accuracy level of mailbox format autodetection. Argument is either a
# decimal number or any of the following constants:
# auto - set accuracy level from the environment variable
# MU_AUTODETECT_ACCURACY (default)
# fast - do only a rough estimation of the mailbox format: fastest,
# but possibly inaccurate
# minimal - good balance between speed and accuracy
autodetect-accuracy <n: number>;
};
locking {
# Default locker flags (E=external, R=retry, T=time, P=pid).
flags <arg: string>;
# Set timeout for acquiring the lock.
retry-timeout <arg: interval>;
# Set the maximum number of times to retry acquiring the lock.
retry-count <arg: integer>;
# Expire locks older than this amount of time.
expire-timeout <arg: interval>;
# Use external locker program.
external-locker <prog: string>;
};
# Include contents of the given file. If a directory is given, include
# contents of the file <file>/<program>, where <program> is the name of the
# program. This latter form is allowed only in the site-wide configuration
# file.
include <file-or-directory: string>;
Проверьте синтаксис конфигурации.
$ mail --config-lint
mail: opening configuration file /etc/mailutils.conf mail: parsing file `/etc/mailutils.conf' mail: finished parsing file `/etc/mailutils.conf' mail: opening configuration file /home/milosz/.mail mail: configuration file /home/milosz/.mail doesn't exist
Сохраните пароль:
$ cat <<EOF | sudo tee /etc/postfix/sasl_passwd [mail.example.org]:587 mail@example.org:mail_token EOF
Создайте таблицу поиска:
$ sudo postmap /etc/postfix/sasl_passwd
Защитите пароль:
$ sudo chmod 600 /etc/postfix/sasl_passwd $ sudo chmod 600 /etc/postfix/sasl_passwd.db
Создайте правила для изменения адреса назначения.
$ cat <<EOF | sudo tee /etc/postfix/header_checks /^To:.*@example.org/ REDIRECT mail@example.org /^To:.*@/ DISCARD EOF
$ sudo postmap /etc/postfix/header_checks
Создайте конфигурацию postfix.
$ cat <<EOF | sudo tee /etc/postfix/main.cf myorigin = \$myhostname mynetworks = mydestination = inet_interfaces = loopback-only compatibility_level = 2 header_checks = regexp:/etc/postfix/header_checks relayhost = [mail.example.org]:587 smtp_use_tls = yes smtp_sasl_auth_enable = yes smtp_sasl_security_options = noanonymous smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt EOF
Убедитесь, что служба smtpd не прослушивается.
$ cat /etc/postfix/master.cf
[...] # ========================================================================== # service type private unpriv chroot wakeup maxproc command + args # (yes) (yes) (no) (never) (100) # ========================================================================== #smtp inet n - y - - smtpd #smtp inet n - y - 1 postscreen #smtpd pass - - y - - smtpd #dnsblog unix - - y - 0 dnsblog #tlsproxy unix - - y - 0 tlsproxy [...]
Перезапустите службу postfix.
$ sudo systemctl restart postfix
Отправьте почту другому локальному пользователю – она будет доставлена на mail@example.org.
$ whoami | mail --subject "$(hostname -f): who am i" root
Jun 15 09:27:24 bullseye postfix/pickup[24069]: A8C56C011B: uid=1000 from=<milosz@example.org> Jun 15 09:27:24 bullseye postfix/cleanup[24634]: A8C56C011B: redirect: header To: <root@example.org> from local; from=<milosz@example.org>: tech@example.org Jun 15 09:27:24 bullseye postfix/cleanup[24634]: A8C56C011B: message-id=<20210615092724.A8C56C011B@bullseye.localdomain> Jun 15 09:27:24 bullseye postfix/qmgr[22577]: A8C56C011B: from=<milosz@example.org>, size=369, nrcpt=1 (queue active) Jun 15 09:27:25 bullseye postfix/smtp[24636]: A8C56C011B: to=<mail@example.org>, orig_to=<root@example.org>, relay=mail.example.org[172.16.0.16]:587, delay=1.2, delays=0.02/0/0.84/0.36, dsn=2.0.0, status=sent (250 2.0.0 Ok: queued as BCC92240009) Jun 15 09:27:25 bullseye postfix/qmgr[22577]: A8C56C011B: removed
Отправьте почту на другой адрес в домене example.org – она будет доставлена на mail@example.org.
$ whoami | mail --subject "$(hostname -f): who am i" milosz@example.org
Jun 15 09:28:52 bullseye postfix/pickup[24069]: E3D8EC011B: uid=1000 from=<milosz@example.org> Jun 15 09:28:52 bullseye postfix/cleanup[24634]: E3D8EC011B: redirect: header To: <milosz@example.org> from local; from=<example@example.org>: tech@example.org Jun 15 09:28:52 bullseye postfix/cleanup[24634]: E3D8EC011B: message-id=<20210615092852.E3D8EC011B@bullseye.localdomain> Jun 15 09:28:52 bullseye postfix/qmgr[22577]: E3D8EC011B: from=<milosz@example.org>, size=371, nrcpt=1 (queue active) Jun 15 09:28:54 bullseye postfix/smtp[24636]: E3D8EC011B: to=<mail@example.org>, orig_to=<milosz@example.org>, relay=mail.example.org[172.16.0.16]:587, delay=1.4, delays=0.01/0/1/0.38, dsn=2.0.0, status=sent (250 2.0.0 Ok: queued as 3173060016) Jun 15 09:28:54 bullseye postfix/qmgr[22577]: E3D8EC011B: removed
Отправляйте почту на другой адрес в другом домене – она будет отброшена.
Send mail to another address in a different domain – it will be discarded.
$ whoami | mail --subject "who am i" nonexistent@example.com
Jun 15 09:28:23 bullseye postfix/pickup[24069]: 580DEC011B: uid=1000 from=<milosz@example.org> Jun 15 09:28:23 bullseye postfix/cleanup[24634]: 580DEC011B: discard: header To: <nonexistent@example.com> from local; from=<milosz@example.org>
Это решение не является пуленепробиваемым, но оно справляется со своей задачей.
- 🖼 Настройка Postfix для использования Gmail в качестве почтового ретранслятора
- Как удалить файлы Root Mails (Mailbox)
![]()
