Инструменты пользователя

Инструменты сайта


mail_server

Различия

Показаны различия между двумя версиями страницы.

Ссылка на это сравнение

mail_server [2026/06/11 12:15] (текущий)
Строка 1: Строка 1:
 +====== Почтовый сервер  ======
 +
 +==== Введение ====
 +
 +Я так думаю, что Вы, мои предыдущие статьи про домашний сервер прочитали.
 +
 +Поэтому, я не буду расписывать, как его устанавливать.
 +
 +Просто, дам ссылки на эти первые статьи о домашнем сервере:
 +
 +[[http://www.ubuntu.liski.su/index.php?page=77]]
 +
 +[[http://www.ubuntu.liski.su/index.php?page=81]]
 +
 +В данной конфигурации, использовались материалы  следующей статьи:
 +
 +[[http://workaround.org/articles/ispmail-etch/]]
 +
 +За что ее авторам огромная благодарность!
 +
 +===== Установка необходимых пакетов =====
 +
 +Если, не активирован ROOT:
 +
 +<code>sudo su
 +sudo passwd root</code>
 +
 +Сделаем ссылочку на bash на sh:
 +
 +<code>ln -sf /bin/bash /bin/sh</code>
 +
 +Уберем apparmor (чего то, с ним пока не все ладится!)
 +
 +<code>/etc/init.d/apparmor stop
 +update-rc.d -f apparmor remove</code>
 +
 +Устанавливаем основные пакеты:
 +
 +<code>aptitude install postfix-mysql mysql-server dovecot-pop3d dovecot-imapd openssl
 +aptitude install phpmyadmin squirrelmail
 +aptitude install postfix-mysql 
 +aptitude install mysql-server-5.0
 +aptitude install dovecot-pop3d
 +aptitude install dovecot-imapd</code>
 +
 +Чтобы бороться со спамом и вирусами (AMaViS для сканирования входящих сообщений на наличие вирусов, спама и нежелательных вложений)
 +
 +<code>aptitude install amavisd-new libclass-dbi-mysql-perl
 +aptitude install spamassassin clamav-daemon cpio arj zoo nomarch lzop cabextract pax</code>
 +
 +Другие необходимые пакеты:
 +
 +<code>aptitude install lha unrar
 +aptitude install openssl
 +aptitude install squirrelmail
 +aptitude install phpmyadmin libapache2-mod-php5 php5-mysql
 +aptitude install telnet
 +aptitude install mutt
 +aptitude install ssh openssh-server</code>
 +
 +Те же пакеты, для установки одной строкой (без AMaViS)
 +
 +<code>aptitude install postfix-mysql mysql-server dovecot-pop3d dovecot-imapd openssl phpmyadmin squirrelmail postfix-mysql mysql-server-5.0 dovecot-pop3d dovecot-imapd lha unrar openssl libapache2-mod-php5 php5-mysql telnet mutt ssh openssh-server</code>
 +
 +===== Шаг 1:  Конфигурируем Сеть =====
 +
 +Редактируем файл **/etc/network/interfaces**, в моем примере, я буду использовать IP адрес 192.168.0.100:
 +
 +<code>gedit /etc/network/interfaces</code>
 +
 +<file># This file describes the network interfaces available on your system
 +# and how to activate them. For more information, see interfaces(5).
 +
 +# The loopback network interface
 +auto lo
 +iface lo inet loopback
 +
 +# The primary network interface
 +auto eth0
 +iface eth0 inet static
 + address 192.168.0.100
 + netmask 255.255.255.0
 + network 192.168.0.0
 + broadcast 192.168.0.255
 + gateway 192.168.0.1</file>
 +
 +Перезапустим сеть:
 +
 +<code>/etc/init.d/networking restart</code>
 +
 +Теперь отредактируем файл **/etc/hosts**. Правим и проверяем (для примера используется домен- example.com имя сервера mailserver, т.е. полное имя носта, будет  mailserver.example.com):
 +
 +<code>gedit /etc/hosts</code>
 +
 +<file>127.0.0.1     mailserver.example.com  localhost.localdomain  localhost
 +192.168.0.100       mailserver.example.com    mailserver
 +
 +# The following lines are desirable for IPv6 capable hosts
 +::1 ip6-localhost ip6-loopback
 +fe00::0 ip6-localnet
 +ff00::0 ip6-mcastprefix
 +ff02::1 ip6-allnodes
 +ff02::2 ip6-allrouters
 +ff02::3 ip6-allhosts</file>
 +
 +Выполним команду:
 +
 +<code>echo mailserver.example.com > /etc/hostname
 +/etc/init.d/hostname.sh start</code>
 +
 +Проверим, запустив:
 +
 +<code>hostname
 +hostname -f</code>
 +
 +Ответ должен быть: **mailserver.example.com**
 +
 +
 +
 +===== Шаг 2: Создаем базу данных и пользователя с правами администратора. =====
 +
 +Основные данные используемой для данной конфигурации базы данных:
 +
 +<file># Информация для соединения с нашим MySQL сервером (пароль администратора для нашей базы данных в MySQL)
 +user = mailuser
 +password = mailuser2009
 +hosts = 127.0.0.1
 +# Название базы данных в нашей конфигурации.
 +dbname = mailserver
 +# Шаблон SQL запроса.
 +query = SELECT destination FROM virtual_aliases WHERE source='%s'</file>
 +
 +
 +Теперь мы ее создадим, для этого запустим "Терминал", и в командной строке введем следующую команду:
 +
 +<code>mysqladmin -u root -p create mailserver</code>
 +
 +Зайдем в оболочку MySQL и откроем вновь созданную базу **mailserver**:
 +
 +<code>mysql -u root -p
 +USE mailserver;</code>
 +
 +Создадим пользователя mailuser и дадим ему все права на нашу базу (mailserver)
 +
 +<file>
 +GRANT SELECT, INSERT, UPDATE, DELETE ON mailserver.* TO 'mailuser'@'localhost' IDENTIFIED BY 'mailuser2009';
 +GRANT SELECT, INSERT, UPDATE, DELETE ON mailserver.* TO 'mailuser'@'localhost.localdomain' IDENTIFIED BY 'mailuser2009';
 +FLUSH PRIVILEGES;</file> 
 +
 +===== Шаг 3: Создаем таблицы базы данных =====
 +
 +Открываем базу данных mailserver^
 +
 +<code>mysql -p mailserver</code>
 +
 +<code>mysql> USE mailserver</code>
 +
 +<file>Database changed
 +mysql></file>
 +
 +Создаем таблицы (virtual_domains,virtual_user, virtual_aliases):
 +
 +<file>
 +CREATE TABLE `virtual_domains` (
 +id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
 +name VARCHAR(50) NOT NULL
 +) ENGINE = InnoDB;</file>
 +
 +<file>
 +CREATE TABLE `virtual_users` (
 +id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
 +domain_id INT(11) NOT NULL,
 +user VARCHAR(40) NOT NULL,
 +password VARCHAR(32) NOT NULL,
 +CONSTRAINT UNIQUE_EMAIL UNIQUE (domain_id,user),
 +FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
 +) ENGINE = InnoDB;</file>
 +
 +<file>
 +CREATE TABLE `virtual_aliases` (
 +id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
 +domain_id INT(11) NOT NULL,
 +source VARCHAR(40) NOT NULL,
 +destination VARCHAR(80) NOT NULL,
 +FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
 +) ENGINE = InnoDB;</file>
 +
 +Создаем и сразу вводим содержание в файл **/etc/postfix/mysql-virtual-mailbox-domains.cf**:
 +
 +<code>gedit /etc/postfix/mysql-virtual-mailbox-domains.cf</code>
 +
 +В появившееся пустое окно вводим следующие строки:
 +    
 +<file>user = mailuser
 +password = mailuser2009
 +hosts = 127.0.0.1
 +dbname = mailserver
 +query = SELECT 1 FROM virtual_domains WHERE name='%s'</file>
 +
 +Выполним команду для конфигурирования файла /etc/postfix/main.cfg:
 +
 +<code>postconf -e virtual_mailbox_domains=mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf</code>
 +
 +Откроем базу данных **mailserver** для занесения в созданные таблицы первичных данных:
 +
 +<code>mysql -p mailserver</code>
 +
 +Увидим строку приглашения и введем данные для таблицы virtual_domains:
 +
 +^id ^name^
 +|1  |example.com|
 +|2  |liski.net|
 +
 +<code>mysql>
 +USE mailserver</code>
 +
 +<file>
 +INSERT INTO virtual_domains (id, name) VALUES (1, 'example.com');
 +INSERT INTO virtual_domains (id, name) VALUES (2, 'liski.net');</file>
 +
 +<code>exit</code>
 +
 +проверим в Терминале, введя по очереди две строки:
 +
 +<code>
 +postmap -q example.com mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
 +postmap -q liski.net mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf</code>
 +
 +Если вы увидели ответ на каждую команду цифру '1', то значит все правильно.
 +
 +Создадим пользователя и группу vmail:
 +
 +<code>
 +groupadd -g 5000 vmail
 +useradd -g vmail -u 5000 vmail -d /home/vmail -m</code>
 +
 +Внесем сведения о них в фаил /etc/postfix/main.cfg:
 +
 +<code>
 +postconf -e virtual_uid_maps=static:5000
 +postconf -e virtual_gid_maps=static:5000</code>
 +
 +Точно так же, введем данные в таблицу virtual_users:
 +
 +<code>mysql -p mailserver
 +
 +INSERT INTO virtual_users (id, domain_id, user, password)
 +VALUES (1, 1, 'victor', MD5('12345'));
 +
 +INSERT INTO virtual_users (id, domain_id, user, password)
 +VALUES (2, 1, 'alex', MD5('12345'));</code>
 +
 +Проверим, все ли мы сделали правильно, сдесь же в базе введем сл. команду:
 +
 +<code>
 +SELECT CONCAT(virtual_users.user, '@', virtual_domains.name) AS email
 +FROM virtual_users
 +LEFT JOIN virtual_domains ON virtual_users.domain_id=virtual_domains.id;</code>
 +
 +Вывод увидим в виде таблицы, представленной ниже:
 +
 +<file>+--------------------+
 +| email              |
 ++--------------------+
 +| alex@example.com   
 +| victor@example.com | 
 ++--------------------+
 +2 rows in set (0.00 sec)</file>
 +
 +Еще раз:
 +
 +<code>
 +SELECT CONCAT(virtual_users.user, '@', virtual_domains.name) AS email,
 +virtual_users.password
 +FROM virtual_users
 +LEFT JOIN virtual_domains ON virtual_users.domain_id=virtual_domains.id;</code>
 +
 +Увидим следующую таблицу:
 +
 +<file>+--------------------+----------------------------------+
 +| email              | password                         |
 ++--------------------+----------------------------------+
 +| victor@example.com | 827ccb0eea8a706c4c34a16891f84e7b | 
 +| alex@example.com   | 827ccb0eea8a706c4c34a16891f84e7b | 
 ++--------------------+----------------------------------+
 +2 rows in set (0.00 sec)</file>
 +
 +Создадим таблицу view_users (если вы успели выйти из базы данных, то повторите команду:
 +
 +<code>mysql -p mailserver
 +
 +mysql>
 +USE mailserver
 +
 +</code>
 +
 +<code>CREATE VIEW view_users AS
 +SELECT CONCAT(virtual_users.user, '@', virtual_domains.name) AS email,
 +virtual_users.password
 +FROM virtual_users
 +LEFT JOIN virtual_domains ON virtual_users.domain_id=virtual_domains.id;</code>
 +
 +проверка:
 +
 +<code>mysql> SELECT * FROM view_users;</code>
 +
 +Последуетследующий вывод:
 +
 +<file>+--------------------+----------------------------------+
 +| email              | password                         |
 ++--------------------+----------------------------------+
 +| victor@example.com | 827ccb0eea8a706c4c34a16891f84e7b | 
 +| alex@example.com   | 827ccb0eea8a706c4c34a16891f84e7b | 
 ++--------------------+----------------------------------+
 +2 rows in set (0.00 sec)
 +
 +mysql></file>
 +
 +Выходим из оболочки базы данных, с помощью команды quit:
 +
 +<code>quit</code>
 +
 +И создаем файл /**etc/postfix/mysql-virtual-mailbox-maps.cf**:
 +
 +<code>gedit /etc/postfix/mysql-virtual-mailbox-maps.cf</code>
 +
 +Вставляем в пустое окно следующий текст:
 +
 +<file>user = mailuser
 +password = mailuser2009
 +hosts = 127.0.0.1
 +dbname = mailserver
 +query = SELECT 1 FROM view_users WHERE email='%s'</file>
 +
 +Сделаем постконфигурацию postfix:
 +
 +<code>postconf -e virtual_mailbox_maps=mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf</code>
 +
 +проверка в Терминале:
 +
 +<code>postmap -q victor@example.com mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
 +postmap -q alex@example.com mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf</code>
 +
 +должны увидеть цифры "1" и еще раз "1".
 +
 +Заполним таблицу virtual_aliases (вновь повторяем те же команды, чтобы зайти в Mysql):
 +
 +<code>mysql -p mailserver</code>
 +
 +Вносим следующие данные:
 +
 +^^
 +|1 |1 |victor |victor@example.com|
 +|2 |1 |victor |victor@gmail.com|
 +
 +<file>
 +INSERT INTO virtual_aliases (id, domain_id, source, destination)
 +VALUES (1, 1, 'victor', 'victor@example.com'),
 +       (2, 1, 'victor', 'victor@gmail.com');</file>
 +
 +<code>mysql></code>
 +
 +По такой же схеме создаем и проверяем таблицу view_aliases:
 +
 +<file>
 +CREATE VIEW view_aliases AS
 +SELECT CONCAT(virtual_aliases.source, '@', virtual_domains.name) AS email,
 +       destination
 +FROM virtual_aliases
 +LEFT JOIN virtual_domains ON virtual_aliases.domain_id=virtual_domains.id;</file>
 +
 +проверка:
 +
 +<code>mysql> SELECT * FROM view_aliases;</code>
 +
 +<file>+--------------------+---------------------+
 +| email              | destination         |
 ++--------------------+---------------------+
 +| victor@example.com | victor@example.com 
 +| victor@example.com | victor@gmail.com | 
 ++--------------------+---------------------+
 +2 rows in set (0.00 sec)
 +
 +mysql></file> 
 +Выходим из MySQL
 +
 +<code>quit</code>
 +
 +И создаем файл /etc/postfix/mysql-virtual-alias-maps.cf:
 +
 +<code>gedit /etc/postfix/mysql-virtual-alias-maps.cf</code>
 +
 +<file>user = mailuser
 +password = mailuser2009
 +hosts = 127.0.0.1
 +dbname = mailserver
 +query = SELECT destination FROM view_aliases WHERE email='%s'</file>
 +
 +проверим:
 +
 +<code>postmap -q victor@example.com mysql:/etc/postfix/mysql-virtual-alias-maps.cf</code>
 +
 +увидим:
 +
 +<file>victor@example.com,victor@gmail.com
 +
 +root@example:/home/victor#</file> 
 +
 +Создаем файл /etc/postfix/mysql-email2email.cf:
 +
 +<code>gedit /etc/postfix/mysql-email2email.cf</code>
 +
 +<file>user = mailuser
 +password = mailuser2009
 +hosts = 127.0.0.1
 +dbname = mailserver
 +query = SELECT email FROM view_users WHERE email='%s'</file>
 +
 +проверка:
 +
 +<code>postmap -q victor@example.com mysql:/etc/postfix/mysql-email2email.cf</code>
 +
 +увидим:
 +
 +<file>victor@example.com
 +root@example:/home/victor#</file> 
 +
 +Now you need to tell Postfix that these two mappings should be searched by adding this line to your main.cf:
 +
 +<code>postconf -e virtual_alias_maps=mysql:/etc/postfix/mysql-virtual-alias-maps.cf,mysql:/etc/postfix/mysql-email2email.cf</code>
 +
 +<code>chgrp postfix /etc/postfix/mysql-*.cf
 +chmod u=rw,g=r,o= /etc/postfix/mysql-*.cf</code>
 +
 +===== Шаг 5: Доставка писем через Dovecot LDA =====
 +
 +
 +<code>gedit /etc/postfix/master.cf</code>
 +
 +<file>dovecot   unix  -                               pipe
 +    flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -d ${recipient}</file>
 +
 +:!: Перед второй строкой должно быть 2 пробела, по другому posfix не понимает!
 +
 +Перезагружаем и проверяем postfix/
 +
 +<code>postfix reload
 +postfix check</code>
 +
 +<code>postconf -e virtual_transport=dovecot
 +postconf -e dovecot_destination_recipient_limit=1</code>
 +
 +===== Шаг 6: Настраиваем Dovecot =====
 +
 +Let us configure Dovecot which provides both a POP3 and an IMAP service. The configuration files for Dovecot is found under /etc/dovecot. Start with the...
 +
 +<code>
 +gedit /etc/dovecot/dovecot.conf</code>
 +
 +Находим и проверяем строчку с протоколами, она должна выглядеть следующим образом:
 +
 +<file>protocols = imap imaps pop3 pop3s</file>
 +
 +so that Dovecot starts the IMAP and POP3 services and also its equivalents that work over an encrypted SSL (secure socket layer) connection.
 +
 +If users start to complain that they cannot fetch their emails consider setting:
 +
 +<file>disable_plaintext_auth = no</file>
 +
 +This will allow plaintext passwords over an unsecured (non-SSL) connection. By default it is set to 'yes' for security reasons. Setting it to 'no' will mean less security but may help the "less fortunate".
 +
 +A more important setting is:
 +
 +<file>mail_location = maildir:/home/vmail/%d/%n/Maildir</file>
 +
 +which will tell that the users' mailboxes are always found at /home/vmail/DOMAIN/USER and that it should be in maildir format.
 +
 +<note>Previous versions of this tutorial recommended to use mail_location = maildir:/home/vmail/%d/%n instead (without the trailing Maildir part). It is now recommended you add the extra directory so that additional control files in the virtual mailbox directory do not accidentally get confused with mail folders. Otherwise it may happen that your users see e.g. filter control files as mail folders. So if you have an existing directory structure you have to create a Maildir folder right there and move all mail folders (cur, new, tmp and all folders starting with a dot) there.</note>
 +
 +If you already have virtual mailboxes on your system because you followed the previous tutorials for Sarge or Woody you may want to define the IMAP namespace explicitly so that the users find their folder where they have always been:
 +
 +<file>namespace private {
 +    separator = .
 +    prefix = INBOX.
 +    inbox = yes
 +}</file>
 +
 +Next look for a section called "auth default". First define the allowed authentication mechanisms:
 +
 +<file>mechanisms = plain login</file>
 +
 +Then inside that same section you need to change:
 +
 +<file>passdb sql {
 +    args = /etc/dovecot/dovecot-sql.conf
 +}</file>
 +
 +which tells Dovecot that the passwords are stored in an SQL database and:
 +
 +<file>userdb static {
 +    args = uid=5000 gid=5000 home=/home/vmail/%d/%n allow_all_users=yes
 +}</file>
 +
 +to tell Dovecot where the mailboxes are located. This is similar to the mail_location setting.
 +
 +You will want to comment out the section called passdb pam that deals with system users. Otherwise Dovecot will also look for system users when someone fetches emails which leads to warnings in your log file.
 +
 +Now look for another section called socket listen. Here you define socket files that are used to interact with Dovecot's authentication mechanism. Make the section read:
 +
 +<file>socket listen {
 +    master {
 +        path = /var/run/dovecot/auth-master
 +        mode = 0600
 +        user = vmail
 +    }
 +
 +    client {
 +        path = /var/spool/postfix/private/auth
 +        mode = 0660
 +        user = postfix
 +        group = postfix
 +    }
 +}</file>
 +
 +The master section is needed to give Dovecot's delivery agent (the program that saves a new mail to the user's mailbox) access to the userdb information. The client section creates a socket inside the "chroot" directory of Postfix. chroot means that parts of Postfix are jailed into /var/spool/postfix and can only access files beneath that directory. It is a good security measure so that even if Postfix had bugs and were attacked the attacker would not be able to access /etc/passwd for example.
 +
 +And finally the protocol lda section needs to be customized. The LDA (local delivery agent) is more capable than Postfix' built-in virtual delivery agent. It allows for quotas and Sieve (ships with the dovecot-common package) filtering. Let the section be:
 +
 +<file>protocol lda {
 +    log_path = /home/vmail/dovecot-deliver.log
 +    auth_socket_path = /var/run/dovecot/auth-master
 +    postmaster_address = postmaster@example.com
 +    mail_plugins = cmusieve
 +    global_script_path = /home/vmail/globalsieverc
 +}</file>
 +
 +Please change the above postmaster email address to a valid address where the administrator can be reached.
 +
 +Edit **/etc/dovecot/dovecot-sql.conf** and change these settings:
 +
 +<code>gedit /etc/dovecot/dovecot-sql.conf</code>
 +
 +<file>driver = mysql
 +connect = host=127.0.0.1 dbname=mailserver user=mailuser password=mailuser2009
 +default_pass_scheme = PLAIN-MD5
 +password_query = SELECT email as user, password FROM view_users WHERE email='%u';</file>
 +
 +Перезапускаем Dovecot:
 +
 +<code>/etc/init.d/dovecot restart</code>
 +
 +Upon the first restart of Dovecot it will also generate Diffie-Hellman parameters and fix persmissions of /var/run/dovecot and /var/run/dovecot/login. That is perfectly normal.
 +
 +Before you send a first test email you will need to fix file system permissions for the /etc/dovecot/dovecot.conf file so that the vmail user can access the Dovecot configuration. The reason is that Postfix starts the delivery agent with vmail permissions:
 +
 +<code>chgrp vmail /etc/dovecot/dovecot.conf
 +chmod g+r /etc/dovecot/dovecot.conf</code>
 +
 +===== Проверка работы Dovecot =====
 +
 +Проверяем правильность работы, смотрим mail.log, в конце файла должны увидеть следующие строки:
 +
 +<code>gedit /var/log/mail.log</code>
 +
 +<file>Jan 14 14:23:27 mailserver dovecot: Dovecot v1.1.4 starting up
 +Jan 14 14:23:28 mailserver dovecot: auth-worker(default): mysql: Connected to 127.0.0.1 (mailserver)</file>
 +
 +===== Шаг 7: Тестируем нашу почту,через TELNET =====
 +
 +Поднимаем SMTP сесию через telnet.
 +
 +В "Терминале" пишем команду и нажимаем клавишу <key>Enter</key>:
 +
 +<code>telnet localhost smtp</code>
 +
 +Сервер должен ответить:
 +
 +<file>Trying 127.0.0.1...
 +Connected to mailserver.example.com.
 +Escape character is '^]'.
 +220 mailserver.example.com ESMTP Postfix (Ubuntu)</file>
 +
 +Пишем:
 +
 +<code>ehlo example.com</code>
 +
 +Видим:
 +
 +<file>250-mailserver.example.com
 +250-PIPELINING
 +250-SIZE 10240000
 +250-VRFY
 +250-ETRN
 +250-STARTTLS
 +250-ENHANCEDSTATUSCODES
 +250-8BITMIME
 +250 DSN</file>
 +
 +Пишем:
 +
 +<code>mail from:<boss@example.com></code>
 +
 +Видим:
 +
 +<file>250 2.1.0 Ok</file>
 +
 +Пишем:
 +
 +<code>rcpt to:<victor@example.com></code>
 +
 +Видим:
 +
 +<file>250 2.1.5 Ok</file>
 +
 +Пишем:
 +
 +<code>data</code>
 +
 +Видим:
 +
 +<file>354 End data with <CR><LF>.<CR><LF></file>
 +
 +Пишем ("."- точка обязательно):
 +
 +<code>Привет от боса!
 +.</code>
 +
 +<file>250 2.0.0 Ok: queued as 5859920C231</file>
 +
 +<code>quit</code>
 +
 +Видим:
 +
 +<file>221 2.0.0 Bye
 +Connection closed by foreign host.
 +root@mailserver:/home/victor#</file>
 +
 +Проверим логи.
 +
 +Вновь вернемся к лог файлу **/var/log/mail.log** . You should see something similar to:
 +
 +можно так:
 +
 +<code>gedit var/log/mail.log</code>
 +
 +В конце файла должны увидеть следующие строки:
 +
 +<file>Jan 14 16:00:29 mailserver postfix/smtpd[8134]: connect from mailserver.example.com[127.0.0.1]
 +Jan 14 16:00:59 mailserver postfix/smtpd[8134]: 0F5821417D7: client=mailserver.example.com[127.0.0.1]
 +Jan 14 16:01:19 mailserver postfix/cleanup[8139]: 0F5821417D7: message-id=<20090114130059.0F5821417D7@mailserver>
 +Jan 14 16:01:19 mailserver postfix/qmgr[7068]: 0F5821417D7: from=<boss@example.com>, size=366, nrcpt=2 (queue active)
 +Jan 14 16:01:19 mailserver postfix/pipe[8142]: 0F5821417D7: to=<victor@example.com>, relay=dovecot, delay=28, delays=28/0.03/0/0.12, dsn=2.0.0, status=sent (delivered via dovecot service)
 +Jan 14 16:01:20 mailserver postfix/smtp[8141]: 0F5821417D7: to=<victor@gmail.com>, orig_to=<victor@example.com>, relay=gmail-smtp-in.l.google.com[209.85.220.179]:25, delay=29, delays=28/0.02/0.41/0.92, dsn=2.0.0, status=sent (250 2.0.0 OK 1231938080 4si27652369fxm.2)
 +Jan 14 16:01:20 mailserver postfix/qmgr[7068]: 0F5821417D7: removed
 +Jan 14 16:01:29 mailserver postfix/smtpd[8134]: disconnect from mailserver.example.com[127.0.0.1]</file>
 +
 +
 +Проверим наличие почтового ящика, введем в терминале команду: 
 +
 +<code>cd /home/vmail/example.com/victor</code>
 +<code>find</code>
 +
 +<code>root@mail:/home/victor# cd /home/vmail/example.com/victor
 +root@mail:/home/vmail/example.com/victor# find</code>
 +
 +Теперь мы должны увидеть все папки нашего почтового ящика:
 +
 +<file>.
 +./Maildir
 +./Maildir/cur
 +./Maildir/tmp
 +./Maildir/new
 +./Maildir/new/1231926651.M703647P9420.mailserver.example.com,W=459
 +./Maildir/dovecot-uidlist
 +./Maildir/dovecot.index.cache
 +./Maildir/dovecot.index.log
 +root@mailserver:/home/vmail/example.com/victor#</file>Checking the user's maildir
 +
 +Там же находится и отправленное письмо, прочитаем его с помощью команды mutt:
 +
 +There sits the email. Try to read the mail with the "mutt" program:
 +
 +<code>mutt -f /home/vmail/example.com/victor/Maildir/</code>
 +
 +В появившемся окне mutt, увидим наше письмо:
 +
 +^q:Quit  d:Del  u:Undel  s:Save  m:Mail  r:Reply  g:Group  ?:Help^
 +^   1 N   May 18 steve@example.c (0.1K)                          ^
 +
 +Нажмем <key>ENTER</key> для того , чтобы прочитать письмо (email):
 +
 +<file>From: boss@example.com
 +To: undisclosed-recipients: ;
 +
 +Привет от босса.</file>
 +
 +Таким образом, письмо прибыло на акаунт Виктор (Victor`s).
 +
 +:!: Нажмите клавишу <key>q</key>, чтобы выйти из **mutt**.
 +
 +
 +===== Step 8: Test fetching emails with IMAP and POP3 =====
 +
 +
 +John will surely prefer to read his mail in a comfortable mail program. So he needs a way to get access to his mailbox. Two protocols come to play here:
 +    * POP (Post Office Protocol) is a simple protocol that lets you fetch email from a single mailbox. It is usually used to get all emails and then delete them on the server.
 +    * IMAP (Internet Messaging Application Protocol) is also used to fetch email but you can maintain different mailboxes. The inbox is where your incoming emails are stored. But users can move emails to different directories. IMAP is useful when you want to access your email from different locations without losing mail because you fetched it from another location.
 +
 +==== Проверяем работу POP3 ====
 +
 +Давайте попробуем создать POP3 соединение и получить электронную почту (email) для Victora, введем команду:
 +
 +<code>telnet localhost pop3</code>
 +
 +На что сервер отвечает:
 +
 +<file>Trying 127.0.0.1...
 +Connected to localhost.
 +Escape character is '^]'.
 ++OK Dovecot ready.</file>
 +
 +Логинимся как Victor:
 +
 +<code>user victor@example.com</code>
 +
 +Видим ответ от сервера:
 +
 +<file>+OK</file>
 +
 +Передаем пароль:
 +
 +<code>pass summersun</code>
 +
 +Если пароль правильный, то сервер напишет:
 +
 +<file>+OK Logged in.</file>
 +
 +Просмотрим почту для John' с помощью команды list:
 +
 +<code>list</code>
 +
 +Dovecot скажет вам, что есть одно письмо в почтовом ящике:
 +
 +<file>+OK 1 messages:
 +1 474
 +.
 +
 +Fetch that email number 1:
 +
 +retr 1
 +
 +Dovecot sends you the email:
 +
 ++OK 474 octets
 +Return-Path: <steve@example.com>
 +X-Original-To: john@example.com
 +Delivered-To: john@example.com
 +Received: from example.com (localhost [127.0.0.1])
 +    by ... (Postfix) with ESMTP id 692DF379C7
 +    for <john@example.com>; Fri, 18 May 2007 22:59:31 +0200 (CEST)
 +Message-Id: <...>
 +Date: Fri, 18 May 2007 22:59:31 +0200 (CEST)
 +From: steve@example.com
 +To: undisclosed-recipients:;
 +
 +Hi John,
 +
 +just wanted to drop you a note.
 +.
 +</file>
 +
 +Закроем соединение с POP3 сервером:
 +
 +<code>quit</code>
 +
 +Сервер ответит:
 +
 +<file>
 ++OK Logging out.
 +Connection closed by foreign host.</file>
 +
 +==== Проверим соединение через IMAP ====
 +
 +Instead of going through the following procedure (IMAP is rather complicated) you may as well just use mutt to create an IMAP connection:
 +
 +<code>mutt -f imap://victor@example.com@localhost</code>
 +
 +
 +Alternatively you can open up a raw IMAP connection to the server and enter the IMAP commands yourself:
 +
 +<code>telnet localhost imap2</code>
 +
 +You should get a connection:
 +
 +<file>Trying 127.0.0.1...
 +
 +Connected to localhost.
 +Escape character is '^]'.
 +* OK Dovecot ready.</file>
 +
 +IMAP commands always start with a number and reply to that command with the same number. So the following commands must be entered with the number at the beginning of each line. Login with username and password:
 +
 +<code>1 login john@example.com summersun</code>
 +
 +Dovecot logs you in:
 +
 +<file>1 OK Logged in.</file>
 +
 +Ask Dovecot for a list of John's mail folders:
 +
 +<code>2 list "" "*"</code>
 +
 +Here comes the list:
 +
 +<file>* LIST (\HasNoChildren) "." "INBOX"</file>
 +
 +<code>2 OK List completed.</code>
 +
 +Select your inbox:
 +
 +<code>3 select "INBOX"</code>
 +
 +Dovecot gives you all kinds of information about that folder:
 +
 +<file>* FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
 +* OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen \Draft \*)] Flags permitted.
 +* 1 EXISTS
 +* 0 RECENT
 +* OK [UIDVALIDITY 1180039205] UIDs valid
 +* OK [UIDNEXT 3] Predicted next UID
 +3 OK [READ-WRITE] Select completed.</file>
 +
 +You see that one email exists. Fetch it:
 +
 +<code>4 fetch 1 all</code>
 +
 +IMAP will just give you basic information on the email:
 +
 +<file>* 1 FETCH (FLAGS (\Seen) INTERNALDATE .........
 +4 OK Fetch completed.</file>
 +
 +To read the actual mail body you need to fetch it explicitly:
 +
 +<code>5 fetch 1 body[]</code>
 +
 +Here it comes:
 +
 +<file>* 1 FETCH (BODY[] {474}
 +Return-Path: <steve@example.com>
 +X-Original-To: john@example.com
 +Delivered-To: john@example.com
 +Received: from example.com (localhost [127.0.0.1])
 +        by ... (Postfix) with ESMTP id 692DF379C7
 +        for <john@example.com>; Fri, 18 May 2007 22:59:31 +0200 (CEST)
 +Message-Id: <...>
 +Date: Fri, 18 May 2007 22:59:31 +0200 (CEST)
 +From: steve@example.com
 +To: undisclosed-recipients:;
 +
 +Hi John,
 +
 +just wanted to drop you a note.
 +)
 +5 OK Fetch completed.</file>
 +
 +Disconnect from the server:
 +
 +<code>6 logout</code>
 +
 +Dovecot logs you out:
 +
 +<file>* BYE Logging out
 +6 OK Logout completed.
 +Connection closed by foreign host.</file>
 +
 +POP3 and IMAP appear to work. You could now use any email program like Kmail, Evolution or Thunderbird/Icedove and set up a POP3 or IMAP email account. The quickest way to check encrypted connections is using mutt again:
 +
 +<code>mutt -f imaps://john@example.com@localhost</code>
 +
 +If you use other mail programs note that the username will be the email address 'john@example.com' and the password is 'summersun'. You can try these kinds of connections:
 +
 +    * POP3
 +    * IMAP
 +    * POP3 with TLS/SSL enabled
 +    * IMAP with TLS/SSL enabled
 +
 +When using TLS/SSL you will get a warning that the certificate of the server cannot be trusted. Dovecot ships with a sample certificate so that you can test your setup and use TLS/SSL to fetch emails securely. Unfortunately the so called "postinst" script (that is called after the package 'dovecot-common' is installed) does not seem to create the certificate correctly. The common name lacks the domain part. (I have reported this issue under bug number #425917 but this will probably not be fixed in Etch.) So it is advised that you create your own certificate with the proper server name:
 +
 +<code>openssl req -new -x509 -days 3650 -nodes -out /etc/ssl/certs/dovecot.pem \
 +    -keyout /etc/ssl/private/dovecot.pem</code>
 +
 +The certificate and key will be created while you get asked a few questions:
 +
 +<file>Generating a 1024 bit RSA private key
 +.........++++++
 +............................++++++
 +writing new private key to '/etc/ssl/certs/dovecot.pem'
 +-----
 +You are about to be asked to enter information that will be incorporated
 +into your certificate request.
 +What you are about to enter is what is called a Distinguished Name or a DN.
 +There are quite a few fields but you can leave some blank
 +For some fields there will be a default value,
 +If you enter '.', the field will be left blank.
 +-----
 +Country Name (2 letter code) [AU]:RU
 +State or Province Name (full name) [Some-State]:Liski
 +Locality Name (eg, city) []:Liski
 +Organization Name (eg, company) [Internet Widgits Pty Ltd]:liski.net
 +Organizational Unit Name (eg, section) []:
 +Common Name (eg, YOUR name) []:mailtest.liski.net
 +Email Address []:postmaster@liski.net</file>
 +
 +Of course you should fill in your own information here. The most important setting is the Common Name which must contain the fully-qualified name of your mail server. Oh, and this certificate will be valid for 10 years (3650 days) - adjust that period as you want.
 +
 +Do not forget to set the permissions on the private key so that no unauthorized people can read it:
 +
 +<code>chmod o= /etc/ssl/private/dovecot.pem</code>
 +
 +===== ссылка на администрирование сервером =====
 +
 +В мае я ее заставил работать!!!
 +
 +http://www.grs-service.ch/pub/grs_mminstallation.html
 +
 +===== Обсуждение статьи: =====
 +
 +Обсуждаем статью в разделе форума:
 +
 +[[http://www.ubuntu.liski.su/index.php?topic=341.0]]
  
mail_server.txt · Последнее изменение: 2026/06/11 12:15 (внешнее изменение)