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

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


mail_server

Почтовый сервер

Введение

Я так думаю, что Вы, мои предыдущие статьи про домашний сервер прочитали.

Поэтому, я не буду расписывать, как его устанавливать.

Просто, дам ссылки на эти первые статьи о домашнем сервере:

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:

sudo su
sudo passwd root

Сделаем ссылочку на bash на sh:

ln -sf /bin/bash /bin/sh

Уберем apparmor (чего то, с ним пока не все ладится!)

/etc/init.d/apparmor stop
update-rc.d -f apparmor remove

Устанавливаем основные пакеты:

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

Чтобы бороться со спамом и вирусами (AMaViS для сканирования входящих сообщений на наличие вирусов, спама и нежелательных вложений)

aptitude install amavisd-new libclass-dbi-mysql-perl
aptitude install spamassassin clamav-daemon cpio arj zoo nomarch lzop cabextract pax

Другие необходимые пакеты:

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

Те же пакеты, для установки одной строкой (без AMaViS)

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

Шаг 1: Конфигурируем Сеть

Редактируем файл /etc/network/interfaces, в моем примере, я буду использовать IP адрес 192.168.0.100:

gedit /etc/network/interfaces
# 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

Перезапустим сеть:

/etc/init.d/networking restart

Теперь отредактируем файл /etc/hosts. Правим и проверяем (для примера используется домен- example.com имя сервера mailserver, т.е. полное имя носта, будет mailserver.example.com):

gedit /etc/hosts
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

Выполним команду:

echo mailserver.example.com > /etc/hostname
/etc/init.d/hostname.sh start

Проверим, запустив:

hostname
hostname -f

Ответ должен быть: mailserver.example.com

Шаг 2: Создаем базу данных и пользователя с правами администратора.

Основные данные используемой для данной конфигурации базы данных:

# Информация для соединения с нашим MySQL сервером (пароль администратора для нашей базы данных в MySQL)
user = mailuser
password = mailuser2009
hosts = 127.0.0.1
# Название базы данных в нашей конфигурации.
dbname = mailserver
# Шаблон SQL запроса.
query = SELECT destination FROM virtual_aliases WHERE source='%s'

Теперь мы ее создадим, для этого запустим «Терминал», и в командной строке введем следующую команду:

mysqladmin -u root -p create mailserver

Зайдем в оболочку MySQL и откроем вновь созданную базу mailserver:

mysql -u root -p
USE mailserver;

Создадим пользователя mailuser и дадим ему все права на нашу базу (mailserver)

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;

Шаг 3: Создаем таблицы базы данных

Открываем базу данных mailserver^

mysql -p mailserver
mysql> USE mailserver
Database changed
mysql>

Создаем таблицы (virtual_domains,virtual_user, virtual_aliases):

CREATE TABLE `virtual_domains` (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL
) ENGINE = InnoDB;
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;
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;

Создаем и сразу вводим содержание в файл /etc/postfix/mysql-virtual-mailbox-domains.cf:

gedit /etc/postfix/mysql-virtual-mailbox-domains.cf

В появившееся пустое окно вводим следующие строки:

user = mailuser
password = mailuser2009
hosts = 127.0.0.1
dbname = mailserver
query = SELECT 1 FROM virtual_domains WHERE name='%s'

Выполним команду для конфигурирования файла /etc/postfix/main.cfg:

postconf -e virtual_mailbox_domains=mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf

Откроем базу данных mailserver для занесения в созданные таблицы первичных данных:

mysql -p mailserver

Увидим строку приглашения и введем данные для таблицы virtual_domains:

id name
1 example.com
2 liski.net
mysql>
USE mailserver
INSERT INTO virtual_domains (id, name) VALUES (1, 'example.com');
INSERT INTO virtual_domains (id, name) VALUES (2, 'liski.net');
exit

проверим в Терминале, введя по очереди две строки:

postmap -q example.com mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
postmap -q liski.net mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf

Если вы увидели ответ на каждую команду цифру '1', то значит все правильно.

Создадим пользователя и группу vmail:

groupadd -g 5000 vmail
useradd -g vmail -u 5000 vmail -d /home/vmail -m

Внесем сведения о них в фаил /etc/postfix/main.cfg:

postconf -e virtual_uid_maps=static:5000
postconf -e virtual_gid_maps=static:5000

Точно так же, введем данные в таблицу virtual_users:

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'));

Проверим, все ли мы сделали правильно, сдесь же в базе введем сл. команду:

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;

Вывод увидим в виде таблицы, представленной ниже:

+--------------------+
| email              |
+--------------------+
| alex@example.com   | 
| victor@example.com | 
+--------------------+
2 rows in set (0.00 sec)

Еще раз:

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;

Увидим следующую таблицу:

+--------------------+----------------------------------+
| email              | password                         |
+--------------------+----------------------------------+
| victor@example.com | 827ccb0eea8a706c4c34a16891f84e7b | 
| alex@example.com   | 827ccb0eea8a706c4c34a16891f84e7b | 
+--------------------+----------------------------------+
2 rows in set (0.00 sec)

Создадим таблицу view_users (если вы успели выйти из базы данных, то повторите команду:

mysql -p mailserver

mysql>
USE mailserver
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;

проверка:

mysql> SELECT * FROM view_users;

Последуетследующий вывод:

+--------------------+----------------------------------+
| email              | password                         |
+--------------------+----------------------------------+
| victor@example.com | 827ccb0eea8a706c4c34a16891f84e7b | 
| alex@example.com   | 827ccb0eea8a706c4c34a16891f84e7b | 
+--------------------+----------------------------------+
2 rows in set (0.00 sec)

mysql>

Выходим из оболочки базы данных, с помощью команды quit:

quit

И создаем файл /etc/postfix/mysql-virtual-mailbox-maps.cf:

gedit /etc/postfix/mysql-virtual-mailbox-maps.cf

Вставляем в пустое окно следующий текст:

user = mailuser
password = mailuser2009
hosts = 127.0.0.1
dbname = mailserver
query = SELECT 1 FROM view_users WHERE email='%s'

Сделаем постконфигурацию postfix:

postconf -e virtual_mailbox_maps=mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf

проверка в Терминале:

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

должны увидеть цифры «1» и еще раз «1».

Заполним таблицу virtual_aliases (вновь повторяем те же команды, чтобы зайти в Mysql):

mysql -p mailserver

Вносим следующие данные:

1 1 victor victor@example.com
2 1 victor victor@gmail.com
INSERT INTO virtual_aliases (id, domain_id, source, destination)
VALUES (1, 1, 'victor', 'victor@example.com'),
       (2, 1, 'victor', 'victor@gmail.com');
mysql>

По такой же схеме создаем и проверяем таблицу view_aliases:

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;

проверка:

mysql> SELECT * FROM view_aliases;
+--------------------+---------------------+
| email              | destination         |
+--------------------+---------------------+
| victor@example.com | victor@example.com  | 
| victor@example.com | victor@gmail.com | 
+--------------------+---------------------+
2 rows in set (0.00 sec)

mysql>

Выходим из MySQL

quit

И создаем файл /etc/postfix/mysql-virtual-alias-maps.cf:

gedit /etc/postfix/mysql-virtual-alias-maps.cf
user = mailuser
password = mailuser2009
hosts = 127.0.0.1
dbname = mailserver
query = SELECT destination FROM view_aliases WHERE email='%s'

проверим:

postmap -q victor@example.com mysql:/etc/postfix/mysql-virtual-alias-maps.cf

увидим:

victor@example.com,victor@gmail.com

root@example:/home/victor#

Создаем файл /etc/postfix/mysql-email2email.cf:

gedit /etc/postfix/mysql-email2email.cf
user = mailuser
password = mailuser2009
hosts = 127.0.0.1
dbname = mailserver
query = SELECT email FROM view_users WHERE email='%s'

проверка:

postmap -q victor@example.com mysql:/etc/postfix/mysql-email2email.cf

увидим:

victor@example.com
root@example:/home/victor#

Now you need to tell Postfix that these two mappings should be searched by adding this line to your main.cf:

postconf -e virtual_alias_maps=mysql:/etc/postfix/mysql-virtual-alias-maps.cf,mysql:/etc/postfix/mysql-email2email.cf
chgrp postfix /etc/postfix/mysql-*.cf
chmod u=rw,g=r,o= /etc/postfix/mysql-*.cf

Шаг 5: Доставка писем через Dovecot LDA

gedit /etc/postfix/master.cf
dovecot   unix  -       n       n       -       -       pipe
    flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -d ${recipient}

:!: Перед второй строкой должно быть 2 пробела, по другому posfix не понимает!

Перезагружаем и проверяем postfix/

postfix reload
postfix check
postconf -e virtual_transport=dovecot
postconf -e dovecot_destination_recipient_limit=1

Шаг 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…

gedit /etc/dovecot/dovecot.conf

Находим и проверяем строчку с протоколами, она должна выглядеть следующим образом:

protocols = imap imaps pop3 pop3s

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:

disable_plaintext_auth = no

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:

mail_location = maildir:/home/vmail/%d/%n/Maildir

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:

namespace private {
    separator = .
    prefix = INBOX.
    inbox = yes
}

Next look for a section called «auth default». First define the allowed authentication mechanisms:

mechanisms = plain login

Then inside that same section you need to change:

passdb sql {
    args = /etc/dovecot/dovecot-sql.conf
}

which tells Dovecot that the passwords are stored in an SQL database and:

userdb static {
    args = uid=5000 gid=5000 home=/home/vmail/%d/%n allow_all_users=yes
}

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:

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
    }
}

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:

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
}

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:

gedit /etc/dovecot/dovecot-sql.conf
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';

Перезапускаем Dovecot:

/etc/init.d/dovecot restart

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:

chgrp vmail /etc/dovecot/dovecot.conf
chmod g+r /etc/dovecot/dovecot.conf

Проверка работы Dovecot

Проверяем правильность работы, смотрим mail.log, в конце файла должны увидеть следующие строки:

gedit /var/log/mail.log
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)

Шаг 7: Тестируем нашу почту,через TELNET

Поднимаем SMTP сесию через telnet.

В «Терминале» пишем команду и нажимаем клавишу <key>Enter</key>:

telnet localhost smtp

Сервер должен ответить:

Trying 127.0.0.1...
Connected to mailserver.example.com.
Escape character is '^]'.
220 mailserver.example.com ESMTP Postfix (Ubuntu)

Пишем:

ehlo example.com

Видим:

250-mailserver.example.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN

Пишем:

mail from:<boss@example.com>

Видим:

250 2.1.0 Ok

Пишем:

rcpt to:<victor@example.com>

Видим:

250 2.1.5 Ok

Пишем:

data

Видим:

354 End data with <CR><LF>.<CR><LF>

Пишем («.»- точка обязательно):

Привет от боса!
.
250 2.0.0 Ok: queued as 5859920C231
quit

Видим:

221 2.0.0 Bye
Connection closed by foreign host.
root@mailserver:/home/victor#

Проверим логи.

Вновь вернемся к лог файлу /var/log/mail.log . You should see something similar to:

можно так:

gedit var/log/mail.log

В конце файла должны увидеть следующие строки:

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]

Проверим наличие почтового ящика, введем в терминале команду:

cd /home/vmail/example.com/victor
find
root@mail:/home/victor# cd /home/vmail/example.com/victor
root@mail:/home/vmail/example.com/victor# find

Теперь мы должны увидеть все папки нашего почтового ящика:

.
./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#

Checking the user's maildir

Там же находится и отправленное письмо, прочитаем его с помощью команды mutt:

There sits the email. Try to read the mail with the «mutt» program:

mutt -f /home/vmail/example.com/victor/Maildir/

В появившемся окне 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):

From: boss@example.com
To: undisclosed-recipients: ;

Привет от босса.

Таким образом, письмо прибыло на акаунт Виктор (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, введем команду:

telnet localhost pop3

На что сервер отвечает:

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
+OK Dovecot ready.

Логинимся как Victor:

user victor@example.com

Видим ответ от сервера:

+OK

Передаем пароль:

pass summersun

Если пароль правильный, то сервер напишет:

+OK Logged in.

Просмотрим почту для John's с помощью команды list:

list

Dovecot скажет вам, что есть одно письмо в почтовом ящике:

+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.
.

Закроем соединение с POP3 сервером:

quit

Сервер ответит:

+OK Logging out.
Connection closed by foreign host.

Проверим соединение через IMAP

Instead of going through the following procedure (IMAP is rather complicated) you may as well just use mutt to create an IMAP connection:

mutt -f imap://victor@example.com@localhost

Alternatively you can open up a raw IMAP connection to the server and enter the IMAP commands yourself:

telnet localhost imap2

You should get a connection:

Trying 127.0.0.1...

Connected to localhost.
Escape character is '^]'.
* OK Dovecot ready.

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:

1 login john@example.com summersun

Dovecot logs you in:

1 OK Logged in.

Ask Dovecot for a list of John's mail folders:

2 list "" "*"

Here comes the list:

* LIST (\HasNoChildren) "." "INBOX"
2 OK List completed.

Select your inbox:

3 select "INBOX"

Dovecot gives you all kinds of information about that folder:

* 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.

You see that one email exists. Fetch it:

4 fetch 1 all

IMAP will just give you basic information on the email:

* 1 FETCH (FLAGS (\Seen) INTERNALDATE .........
4 OK Fetch completed.

To read the actual mail body you need to fetch it explicitly:

5 fetch 1 body[]

Here it comes:

* 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.

Disconnect from the server:

6 logout

Dovecot logs you out:

* BYE Logging out
6 OK Logout completed.
Connection closed by foreign host.

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:

mutt -f imaps://john@example.com@localhost

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:

openssl req -new -x509 -days 3650 -nodes -out /etc/ssl/certs/dovecot.pem \
    -keyout /etc/ssl/private/dovecot.pem

The certificate and key will be created while you get asked a few questions:

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

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:

chmod o= /etc/ssl/private/dovecot.pem

ссылка на администрирование сервером

В мае я ее заставил работать!!!

http://www.grs-service.ch/pub/grs_mminstallation.html

Обсуждение статьи:

Обсуждаем статью в разделе форума:

http://www.ubuntu.liski.su/index.php?topic=341.0

mail_server.txt · Последнее изменение: 2022/02/17 18:55 (внешнее изменение)