Почтовый сервер в связке Postfix, Dovecot — различия между версиями

Материал из megapuper
Перейти к: навигация, поиск
Строка 149: Строка 149:
 
создаём базу и даём права пользователю
 
создаём базу и даём права пользователю
 
  > create database postfix character set utf8 collate utf8_general_ci;
 
  > create database postfix character set utf8 collate utf8_general_ci;
  > grant all on postfix.* to postfix@127.0.0.1 identified by '<font color=blue>пароль</font>';
+
  > grant all on postfix.* to postfix@127.0.0.1 identified by '<font color=blue>ПАРОЛЬ</font>';
  
  
Строка 781: Строка 781:
 
   
 
   
 
  user = postfix
 
  user = postfix
  password = пароль
+
  password = ПАРОЛЬ
 
  hosts = 127.0.0.1
 
  hosts = 127.0.0.1
 
  dbname = postfix
 
  dbname = postfix
Строка 789: Строка 789:
 
   
 
   
 
  user = postfix
 
  user = postfix
  password = пароль
+
  password = ПАРОЛЬ
 
  hosts = 127.0.0.1
 
  hosts = 127.0.0.1
 
  dbname = postfix
 
  dbname = postfix
Строка 797: Строка 797:
 
   
 
   
 
  user = postfix
 
  user = postfix
  password = пароль
+
  password = ПАРОЛЬ
 
  hosts = 127.0.0.1
 
  hosts = 127.0.0.1
 
  dbname = postfix
 
  dbname = postfix
Строка 805: Строка 805:
 
   
 
   
 
  user = postfix
 
  user = postfix
  password = пароль
+
  password = ПАРОЛЬ
 
  hosts = 127.0.0.1
 
  hosts = 127.0.0.1
 
  dbname = postfix
 
  dbname = postfix
Строка 815: Строка 815:
 
   
 
   
 
  user = postfix
 
  user = postfix
  password = пароль
+
  password = ПАРОЛЬ
 
  hosts = 127.0.0.1
 
  hosts = 127.0.0.1
 
  dbname = postfix
 
  dbname = postfix
Строка 823: Строка 823:
 
   
 
   
 
  user = postfix
 
  user = postfix
  password = пароль
+
  password = ПАРОЛЬ
 
  hosts = 127.0.0.1
 
  hosts = 127.0.0.1
 
  dbname = postfix
 
  dbname = postfix
Строка 848: Строка 848:
  
 
Устанавливаем поддержку языка Sieve в Dovecot(включает в себя настройку скриптов пользователями)
 
Устанавливаем поддержку языка Sieve в Dovecot(включает в себя настройку скриптов пользователями)
  # pkg install dovecot-pigeonhole
+
  # cd /usr/ports/mail/dovecot2-pigeonhole
 +
# make install clean
 +
 
 +
 
 +
Создаём сопутствуюшие папки
 +
# mkdir /var/log/dovecot
 +
# mkdir -p /var/lib/dovecot/sieve/global/
 +
# mkdir -p /var/lib/dovecot/sieve/private/
 +
 
  
 +
Выставляем права
 +
# chown -R mail:wheel /var/lib/dovecot/sieve/private/
 +
# chmod -R 700 /var/lib/dovecot/sieve/private/
  
Настраиваем конфиги dovecot
+
Правим конфиги dovecot
 
  [/usr/local/etc/dovecot/dovecot.conf]
 
  [/usr/local/etc/dovecot/dovecot.conf]
 
   
 
   
 
  # Enable installed protocols
 
  # Enable installed protocols
#!include_try /usr/share/dovecot/protocols.d/*.protocol
 
 
  protocols = imap lmtp sieve
 
  protocols = imap lmtp sieve
 
+
dict {
 +
#quota = mysql:/etc/dovecot/dovecot-dict-sql.conf.ext
 +
#expire = sqlite:/etc/dovecot/dovecot-dict-sql.conf.ext
 +
}
 
  !include conf.d/*.conf
 
  !include conf.d/*.conf
 +
 +
 +
[/usr/local/etc/dovecot/dovecot-sql.conf.ext]
 +
 +
driver = mysql
 +
connect = host=127.0.0.1 dbname=postfix user=postfix password=ПАРОЛЬ
 +
default_pass_scheme = PLAIN
 +
#default_pass_scheme = PLAIN-MD5
 +
#  %u = entire user@domain
 +
#  %n = user part of user@domain
 +
#  %d = domain part of user@domain
 +
 +
#одной строкой без переносов
 +
password_query = SELECT username as user, password, '%u' AS userdb_master_user, CONCAT('/var/spool/mail/', maildir) AS userdb_home, 1000 AS userdb_uid, 1000 AS userdb_gid, CONCAT('*:storage=', quota, 'B')
 +
as userdb_quota_rule FROM mailbox WHERE username = '%u' AND active = '1'
 +
 +
#одной строкой без переносов
 +
user_query = SELECT CONCAT('/var/spool/mail/', maildir) AS home, 1000 AS uid, 1000 AS gid, CONCAT('*:storage=', quota, 'B') as quota_rule FROM mailbox WHERE username = '%u' AND active ='1'
 +
 +
 +
[/usr/local/etc/dovecot/dovecot-sql-master.conf.ext]
 +
 +
driver = mysql
 +
#default_pass_scheme = PLAIN-MD5
 +
default_pass_scheme = PLAIN
 +
connect = host=127.0.0.1 dbname=postfix user=postfix password=ПАРОЛЬ
 +
password_query = SELECT username AS user, password FROM admin WHERE username = '%u' AND active = '1'
  
  
Строка 865: Строка 905:
 
  # Connect only after start SSL/TLS
 
  # Connect only after start SSL/TLS
 
  # If not local network only !
 
  # If not local network only !
  disable_plaintext_auth = yes
+
  disable_plaintext_auth = no
 
  auth_cache_size = 1M
 
  auth_cache_size = 1M
 
  auth_cache_negative_ttl = 0
 
  auth_cache_negative_ttl = 0
Строка 888: Строка 928:
 
   }
 
   }
 
   inet_listener {
 
   inet_listener {
     #port =  
+
     #port =
 
   }
 
   }
 
  }
 
  }
Строка 896: Строка 936:
 
   #executable = imap-login director
 
   #executable = imap-login director
 
  }
 
  }
 +
 
  #service pop3-login {
 
  #service pop3-login {
 
   #executable = pop3-login director
 
   #executable = pop3-login director
 
  #}
 
  #}
 +
 
  # Enable director for LMTP proxying:
 
  # Enable director for LMTP proxying:
 
  protocol lmtp {
 
  protocol lmtp {
Строка 912: Строка 954:
 
  info_log_path = /var/log/dovecot/dovecot-info.log
 
  info_log_path = /var/log/dovecot/dovecot-info.log
 
  debug_log_path = /var/log/dovecot/dovecot-debug.log
 
  debug_log_path = /var/log/dovecot/dovecot-debug.log
  auth_verbose = no
+
  auth_verbose = yes
  auth_verbose_passwords = no
+
  auth_verbose_passwords = yes
 
  auth_debug = no
 
  auth_debug = no
 
  auth_debug_passwords = no
 
  auth_debug_passwords = no
  mail_debug = no
+
  mail_debug = yes
 
  verbose_ssl = no
 
  verbose_ssl = no
 +
 
  #plugin {
 
  #plugin {
 
  #}
 
  #}
Строка 924: Строка 967:
 
  #login_log_format = %$: %s
 
  #login_log_format = %$: %s
 
  #mail_log_prefix = "%s(%u): "
 
  #mail_log_prefix = "%s(%u): "
  # Format to use for logging mail deliveries. You can use variables:
+
  # Format to use for logging mail deliveries. You can use variables:
 
  #  %$ - Delivery status message (e.g. "saved to INBOX")
 
  #  %$ - Delivery status message (e.g. "saved to INBOX")
 
  #  %m - Message-ID
 
  #  %m - Message-ID
Строка 934: Строка 977:
  
  
Подготовим каталоги
 
# mkdir /var/lib/dovecot/virtual
 
# mkdir /var/lib/dovecot/virtual/Folder
 
# chown -R vmail:vmail /var/lib/dovecot/virtual
 
# chmod -R 700 /var/lib/dovecot/virtual
 
 
 
Создаём Файл с фильтрами для виртуального каталога(для каталога Folder)
 
[/var/lib/dovecot/virtual/Folder/dovecot-virtual]
 
 
virtual/Folder
 
  inthread refs x-mailbox INBOX
 
 
 
Продолжаем с конфигами
 
 
  [/usr/local/etc/dovecot/conf.d/10-mail.conf]
 
  [/usr/local/etc/dovecot/conf.d/10-mail.conf]
 
   
 
   
 
  mail_location = maildir:/var/spool/mail/%d/%n:INBOX=/var/spool/mail/%d/%n
 
  mail_location = maildir:/var/spool/mail/%d/%n:INBOX=/var/spool/mail/%d/%n
namespace virt {
 
# type = private
 
  prefix = virtual/
 
  separator = /
 
  location = virtual:/var/lib/dovecot/virtual:INDEX=/var/spool/mail/%d/%n/virtual_index:CONTROL=/var/spool/mail/%d/%n/virtual_index
 
  inbox = no
 
  hidden = yes
 
  list = yes
 
  subscriptions = yes
 
  #mailbox Folder1 {
 
  #  auto=subscribe
 
  #}
 
}
 
 
   
 
   
  namespace allusers {
+
  namespace inbox {
  type = public
 
  separator = /
 
  prefix = "allmail/%d/"
 
  location = maildir:/var/spool/mail/%d:LAYOUT=fs:INDEX=/var/spool/mail/%d/%n/allmail_index
 
  inbox = no
 
  hidden = yes
 
  list = yes
 
  subscriptions = no
 
}
 
 
namespace system_users {
 
 
   type = private
 
   type = private
 
   separator = /
 
   separator = /
   prefix = "system_users/"
+
   prefix =
   location = mbox:/var/mail/:INDEX=/var/spool/mail/system_users_index
+
   inbox = yes
    inbox = no
+
   hidden = no
   hidden = yes
 
 
   list = yes
 
   list = yes
 
   subscriptions = yes
 
   subscriptions = yes
 
  }
 
  }
 
   
 
   
namespace inbox {
+
  mail_uid = 1000
  type = private
+
  mail_gid = 1000
  separator = /
 
  prefix =
 
  inbox = yes
 
  hidden = no
 
  list = yes                                                                     
 
  subscriptions = yes
 
}
 
 
  mail_uid = 5000
 
  mail_gid = 5000
 
  
  
 
  [/usr/local/etc/dovecot/conf.d/10-master.conf]
 
  [/usr/local/etc/dovecot/conf.d/10-master.conf]
 
   
 
   
#default_process_limit = 100
 
#default_client_limit = 1000
 
#default_vsz_limit = 256M
 
#default_login_user = dovenull
 
#default_internal_user = dovecot
 
 
  service imap-login {
 
  service imap-login {
  inet_listener imap {
+
  inet_listener imap {
 
   address = *
 
   address = *
 
   port = 143
 
   port = 143
 
   #ssl = yes
 
   #ssl = yes
 
   }
 
   }
+
  inet_listener imaps {
inet_listener imaps {
 
 
   #port = 993
 
   #port = 993
  port = 0
 
 
   #ssl = yes
 
   #ssl = yes
 
   }
 
   }
 
   
 
   
#service_count = 1
 
  #process_min_avail = 0
 
  #vsz_limit = $default_vsz_limit
 
 
  }
 
  }
 
   
 
   
 
  #service pop3-login {
 
  #service pop3-login {
  #inet_listener pop3 {
+
  #inet_listener pop3 {
 
   #port = 110
 
   #port = 110
 
   #}
 
   #}
  #inet_listener pop3s {
+
  #inet_listener pop3s {
 
   #port = 995
 
   #port = 995
 
   #ssl = yes
 
   #ssl = yes
Строка 1038: Строка 1021:
 
   
 
   
 
  service lmtp {
 
  service lmtp {
  unix_listener lmtp {
+
  unix_listener lmtp {
  path = /var/spool/postfix/private/dovecot-lmtp
+
  path = /var/spool/postfix/private/dovecot-lmtp
  group = postfix
+
  group = postfix
  mode = 0660
+
  mode = 0660
  user = postfix
+
  user = postfix
  ##mode = 0666
+
  #mode = 0666
 
   }
 
   }
+
  executable = lmtp -L
#unix_listener /var/spool/postfix/private/dovecot-lmtp {
 
#  group = postfix
 
#  mode = 0660
 
#  user = postfix
 
# }
 
# process_min_avail = 5
 
  executable = lmtp -L
 
 
  }
 
  }
 
   
 
   
 
  service imap {
 
  service imap {
  #vsz_limit = $default_vsz_limit
+
  #vsz_limit = $default_vsz_limit
  # Max. number of IMAP processes (connections)
+
  # Max. number of IMAP processes (connections)
  #process_limit = 1024
+
  #process_limit = 1024
  #executable = imap
+
  #executable = imap
 
  }
 
  }
+
 
 
  #service pop3 {
 
  #service pop3 {
 
   # Max. number of POP3 processes (connections)
 
   # Max. number of POP3 processes (connections)
Строка 1068: Строка 1044:
 
   
 
   
 
  service auth {
 
  service auth {
  unix_listener auth {
+
  unix_listener auth {
 
   path = /var/spool/postfix/private/auth
 
   path = /var/spool/postfix/private/auth
 
   mode = 0660
 
   mode = 0660
Строка 1078: Строка 1054:
 
   
 
   
 
  service auth-worker {
 
  service auth-worker {
  user = $default_internal_user
+
  user = $default_internal_user
 
  }
 
  }
 
#Detail Process title in ps
 
#verbose_proctitle = yes
 
#service dict {
 
  #unix_listener dict {
 
  #}
 
#}
 
  
  
Строка 1092: Строка 1061:
 
   
 
   
 
  postmaster_address = postmaster@megapuper.ru
 
  postmaster_address = postmaster@megapuper.ru
  hostname = megapuper.ru
+
  hostname = mail.megapuper.ru
#quota_full_tempfail = no
 
#sendmail_path = /usr/sbin/sendmail
 
#submission_host =
 
 
  #rejection_subject = Rejected: %s
 
  #rejection_subject = Rejected: %s
 
  #  %n = CRLF, %r = reason, %s = original subject, %t = recipient
 
  #  %n = CRLF, %r = reason, %s = original subject, %t = recipient
 
  rejection_reason = Your message to <%t> was automatically rejected:%n%r
 
  rejection_reason = Your message to <%t> was automatically rejected:%n%r
#recipient_delimiter = +
 
#lda_original_recipient_header =
 
#lda_mailbox_autocreate = no
 
#lda_mailbox_autosubscribe = no
 
 
   
 
   
 
  protocol lda {
 
  protocol lda {
   mail_plugins = sieve virtual
+
   mail_plugins = sieve
log_path = /var/log/dovecot/mail-dovecot-lda-errors.log
+
  log_path = /var/log/dovecot/mail-dovecot-lda-errors.log
info_log_path = /var/log/dovecot/mail-dovecot-lda.log
+
  info_log_path = /var/log/dovecot/mail-dovecot-lda.log
#  auth_socket_path = /var/run/dovecot/auth-master
 
#  auth_socket_path = auth-userdb
 
#  global_script_path = /var/lib/dovecot/sieve/global/globalsieverc
 
 
  }
 
  }
  
Строка 1117: Строка 1076:
 
   
 
   
 
  protocol imap {
 
  protocol imap {
  mail_plugins = $mail_plugins imap_acl imap_quota mail_log notify acl quota virtual
+
  mail_plugins = $mail_plugins imap_acl imap_quota mail_log notify acl quota
  #ssl_cert = </etc/dovecot/ssl.cert.pem
+
  #ssl_cert = </usr/local/etc/dovecot/ssl.cert.pem
  #ssl_key = </etc/dovecot/ssl.key.pem
+
  #ssl_key = </usr/local/etc/dovecot/ssl.key.pem
  info_log_path = /var/log/dovecot-imap.log
+
  info_log_path = /var/log/dovecot/dovecot-imap.log
  #imap_max_line_length = 64k
+
  #mail_max_userip_connections = 10
  #mail_max_userip_connections = 10
+
  # IMAP logout format string:
  # IMAP logout format string:
+
  # %i - total number of bytes read from client
  # %i - total number of bytes read from client
+
  # %o - total number of bytes sent to client
  # %o - total number of bytes sent to client
+
  #imap_logout_format = bytes=%i/%o
  #imap_logout_format = bytes=%i/%o
+
  #imap_capability =
  #imap_capability =
+
  #imap_idle_notify_interval = 2 mins
  #imap_idle_notify_interval = 2 mins
+
  #imap_id_send =
  #imap_id_send =
+
  #imap_id_log =
  #imap_id_log =
 
  # Workarounds for various client bugs:
 
  # delay-newmail:
 
  # tb-extra-mailbox-sep:
 
  # tb-lsub-flags:
 
  # The list is space-separated.
 
  #imap_client_workarounds =
 
 
  }
 
  }
 +
  
  
 
  [/usr/local/etc/dovecot/conf.d/20-lmtp.conf]
 
  [/usr/local/etc/dovecot/conf.d/20-lmtp.conf]
 
   
 
   
#lmtp_proxy = no
 
#lmtp_save_to_detail_mailbox = no
 
 
  protocol lmtp {
 
  protocol lmtp {
  mail_plugins = $mail_plugins quota sieve virtual
+
  mail_plugins = $mail_plugins quota sieve
  postmaster_address = postmaster@megapuper.ru
+
  postmaster_address = postmaster@megapuper.ru
  #info_log_path = /var/log/dovecot/dovecot-lmtp.log
+
  info_log_path = /var/log/dovecot/dovecot-lmtp.log
 
  }
 
  }
  
Строка 1154: Строка 1105:
 
   
 
   
 
  service managesieve-login {
 
  service managesieve-login {
  inet_listener sieve {
+
  inet_listener sieve {
    address = 127.0.0.1
+
  address = 127.0.0.1
    port = 4190
+
  port = 4190
  }
+
}
 
   service_count = 1
 
   service_count = 1
  #process_min_avail = 0
 
 
   vsz_limit = 64M
 
   vsz_limit = 64M
 
  }
 
  }
  #service managesieve {
+
  #mail_plugins = virtual
  # Max. number of ManageSieve processes (connections)
+
  #protocol sieve {
  #process_count = 1024
 
#}
 
mail_plugins = virtual
 
  protocol sieve {
 
 
   #managesieve_max_line_length = 65536
 
   #managesieve_max_line_length = 65536
 
   #mail_max_userip_connections = 10
 
   #mail_max_userip_connections = 10
Строка 1179: Строка 1125:
 
   #managesieve_notify_capability =
 
   #managesieve_notify_capability =
 
   #managesieve_max_compile_errors = 5
 
   #managesieve_max_compile_errors = 5
  }
+
  #}
 
 
 
 
[/usr/local/etc/dovecot/conf.d/90-acl.conf]
 
 
plugin {
 
  #acl = vfile:/usr/local/etc/dovecot/acl/%d:cache_secs=300
 
  acl = vfile:/usr/local/etc/dovecot/acl/%d
 
}
 
plugin {
 
  #acl_shared_dict = file:/var/lib/dovecot/shared-mailboxes
 
}
 
 
 
 
 
Примеры ACL<br/>
 
Следующая настройка запрещает пользователю всё, кроме чтения/просмотра/удаления, но разрешает сохранение для LDA<br/>
 
 
 
В каталоге с именем домена указываем ACL для папки ".Sent".
 
[/usr/local/etc/dovecot/acl/megapuper.ru/Sent]
 
 
owner lrwstpe
 
 
 
Аналогично можно настроить остальные папки (подробности - в заметке по ссылке чуть выше)<br/>
 
Закрываем доступ для всех кроме LDA к файлу ".dovecot.lda-dupes", который может быть виден в MUA как фантомная папка "lda-dupes":
 
# mkdir /usr/local/etc/dovecot/acl/megapuper.ru/dovecot/
 
ВАЖНО! - точка воспринимается как маркер вложенной папки.
 
 
 
[/etc/dovecot/acl/megapuper.ru/dovecot/lda-dupes]
 
 
anyone rp
 
 
 
 
 
[/usr/local/etc/dovecot/conf.d/90-plugin.conf]
 
 
plugin {
 
# mail_plugins = $mail_plugins mail_log notify acl quota
 
# For Plugin mail_log:
 
  mail_log_events = copy
 
  mail_log_fields = uid box msgid size
 
}
 
  
  
Строка 1234: Строка 1141:
 
   #quota_warning2 = storage=80%% quota-warning 80 %u
 
   #quota_warning2 = storage=80%% quota-warning 80 %u
 
  }
 
  }
 
#service quota-warning {
 
#  executable = script /usr/local/bin/quota-warning.sh
 
#  user = dovecot
 
#  unix_listener quota-warning {
 
#    user = mail
 
#  }
 
#}
 
 
   
 
   
 
  plugin {
 
  plugin {
Строка 1256: Строка 1155:
 
   #quota2_rule = *:storage=1048576
 
   #quota2_rule = *:storage=1048576
 
  }
 
  }
 
 
'''Sieve'''
 
 
Все глобальные скрипты и конфигурационные файлы будут находится в соответствующих папках в: /var/lib/dovecot/sieve/global/<br/>
 
Все персональные настройки и файлы будут находится либо в папках пользователей, либо в каталоге: /var/lib/dovecot/sieve/private/ - в соответствующих папках.
 
# mkdir /var/lib/dovecot/sieve/
 
# mkdir /var/lib/dovecot/sieve/global/
 
# mkdir /var/lib/dovecot/sieve/private/
 
# chown -R root:wheel /var/lib/dovecot/sieve/
 
# chown -R root:wheel /var/lib/dovecot/sieve/global/
 
# chown -R root:wheel /var/lib/dovecot/sieve/private/
 
# chmod -R 755 /var/lib/dovecot/sieve/
 
# chmod -R 755 /var/lib/dovecot/sieve/global/
 
# chmod -R 700 /var/lib/dovecot/sieve/private/
 
 
  
 
  [/usr/local/etc/dovecot/conf.d/90-sieve.conf]
 
  [/usr/local/etc/dovecot/conf.d/90-sieve.conf]
 
   
 
   
 
  plugin {
 
  plugin {
sieve_user_log = /var/lib/dovecot/sieve/private/%d/%n/.main.peronal.log
+
  sieve_user_log = /var/lib/dovecot/sieve/private/%d/%n/.main.peronal.log
  sieve = /var/lib/dovecot/sieve/private/%d/%n/.main.personal.sieve
+
  sieve = /var/lib/dovecot/sieve/private/%d/%n/.main.personal.sieve
  #sieve_default = /var/lib/dovecot/sieve/default.sieve
+
  #sieve_default = /var/lib/dovecot/sieve/default.sieve
  sieve_dir = /var/lib/dovecot/sieve/private/%d/%n/
+
  sieve_dir = /var/lib/dovecot/sieve/private/%d/%n/
  sieve_global_dir = /var/lib/dovecot/sieve/global/
+
  sieve_global_dir = /var/lib/dovecot/sieve/global/
  #sieve_before2 =
+
  #sieve_before2 =
  sieve_before = /var/lib/dovecot/sieve/global/incoming_deduplicate.sieve
+
  sieve_before = /var/lib/dovecot/sieve/global/incoming_deduplicate.sieve
  #sieve_after =
+
  #sieve_after =
  #sieve_after2 =
+
  #sieve_after2 =
  sieve_extensions = +editheader
+
  sieve_extensions = +editheader
  sieve_global_extensions = +vnd.dovecot.duplicate
+
  sieve_global_extensions = +vnd.dovecot.duplicate
  sieve_duplicate_period = 1d
+
  sieve_duplicate_period = 1d
  #sieve_plugins =
+
  #sieve_plugins =
  recipient_delimiter = +
+
  recipient_delimiter = +
  #sieve_max_script_size = 1M
+
  #sieve_max_script_size = 1M
  #sieve_max_actions = 32
+
  #sieve_max_actions = 32
  #sieve_max_redirects = 4
+
  #sieve_max_redirects = 4
  #sieve_quota_max_scripts = 0
+
  #sieve_quota_max_scripts = 0
  #sieve_quota_max_storage = 0
+
  #sieve_quota_max_storage = 0
 
  }
 
  }
  
Строка 1300: Строка 1183:
 
  [/usr/local/etc/dovecot/conf.d/auth-sql.conf.ext]
 
  [/usr/local/etc/dovecot/conf.d/auth-sql.conf.ext]
 
   
 
   
#passdb {
 
  # driver = passwd-file
 
  # args = username_format=%u /var/spool/mail/auth.d/%d/passwd
 
#}
 
 
# Master-user:
 
 
  auth_master_user_separator = *
 
  auth_master_user_separator = *
 
  #auth_debug = yes
 
  #auth_debug = yes
Строка 1314: Строка 1191:
 
   pass = yes
 
   pass = yes
 
  }
 
  }
 
 
  passdb {
 
  passdb {
 
   driver = sql
 
   driver = sql
 
   args = /usr/local/etc/dovecot/dovecot-sql.conf.ext
 
   args = /usr/local/etc/dovecot/dovecot-sql.conf.ext
  #default_fields = userdb_gid=5000 userdb_uid=5000
+
  #default_fields = userdb_gid=1000 userdb_uid=1000
 
  }
 
  }
 
 
  userdb {
 
  userdb {
 
   driver = prefetch
 
   driver = prefetch
 
  }
 
  }
 
 
[/usr/local/etc/dovecot/dovecot-sql.conf.ext]
 
driver = mysql
 
connect = host=127.0.0.1 dbname=postfix user=postfix password=пароль
 
default_pass_scheme = PLAIN
 
#default_pass_scheme = PLAIN-MD5
 
#  %u = entire user@domain
 
#  %n = user part of user@domain
 
#  %d = domain part of user@domain
 
 
 
password_query = SELECT username as user, password, '%u' AS userdb_master_user, CONCAT('/var/spool/vmail/', maildir) AS userdb_home, 5000 AS userdb_uid, 5000 AS userdb_gid, CONCAT('*:storage=', quota, \
 
'B') as userdb_quota_rule FROM mailbox WHERE username = '%u' AND active = '1'
 
 
user_query = SELECT CONCAT('/var/spool/vmail/', maildir) AS home, 5000 AS uid, 5000 AS gid, CONCAT('*:storage=', quota, 'B') as quota_rule FROM mailbox WHERE username = '%u' AND active = '1'
 
 
 
 
  userdb {
 
  userdb {
 
   driver = sql
 
   driver = sql
 
   args = /usr/local/etc/dovecot/dovecot-sql.conf.ext
 
   args = /usr/local/etc/dovecot/dovecot-sql.conf.ext
   #default_fields = uid=5000 gid=5000
+
   #default_fields = uid=1000 gid=1000
 
  }
 
  }
 
<font color=red>'''ВАЖНО! password_query = ..., user_query = ... - должны быть ОДНОЙ строкой (без переносов)!'''</font>
 
 
 
[/usr/local/etc/dovecot/dovecot-sql-master.conf.ext]
 
 
driver = mysql
 
#default_pass_scheme = PLAIN-MD5
 
default_pass_scheme = PLAIN
 
connect = host=127.0.0.1 dbname=postfix user=postfix password=пароль
 
password_query = SELECT username AS user, password FROM admin WHERE username = '%u' AND active = '1'
 
 
 
Отключим неиспользуемые конфиги:
 
# mv /usr/local/etc/dovecot/conf.d/auth-checkpassword.conf.ext /usr/local/etc/dovecot/conf.d/auth-checkpassword.conf.ext_
 
# mv /usr/local/etc/dovecot/conf.d/auth-deny.conf.ext /usr/local/etc/dovecot/conf.d/auth-deny.conf.ext_
 
# mv /usr/local/etc/dovecot/conf.d/auth-ldap.conf.ext /usr/local/etc/dovecot/conf.d/auth-ldap.conf.ext_
 
# mv /usr/local/etc/dovecot/conf.d/auth-master.conf.ext /usr/local/etc/dovecot/conf.d/auth-master.conf.ext_
 
# mv /usr/local/etc/dovecot/conf.d/auth-passwdfile.conf.ext /usr/local/etc/dovecot/conf.d/auth-passwdfile.conf.ext_
 
# mv /usr/local/etc/dovecot/conf.d/auth-static.conf.ext /usr/local/etc/dovecot/conf.d/auth-static.conf.ext_
 
# mv /usr/local/etc/dovecot/conf.d/auth-system.conf.ext /usr/local/etc/dovecot/conf.d/auth-system.conf.ext_
 
# mv /usr/local/etc/dovecot/conf.d/auth-vpopmail.conf.ext /usr/local/etc/dovecot/conf.d/auth-vpopmail.conf.ext_
 
  
  

Версия 17:04, 6 октября 2015

При установке будем ориентироваться на этот мануал: http://dummyluck.com/page/pochtovyi_server_nastroika_opisanie
Настройку будем производить для сервера с одним доменом. Система FreeBSD 10.2


1. Подготовка
прописываем хостнейм /etc/rc.conf
hostname="servmp.megapuper.ru"


делаем изменения в хостах /etc/hosts

127.0.0.1         localhost
109.172.52.114	  megapuper.ru
109.172.52.114    mail.megapuper.ru


создаём пользователя и добавляем его в группу mail

# pw useradd mail -g mail -s /sbin/nologin -u 1000
# pw groupmod mail -m mail

сразу отключаем sendmail
/etc/rc.conf

sendmail_enable="NO"
sendmail_submit_enable="NO"
sendmail_outbound_enable="NO"
sendmail_msp_queue_enable="NO"

/etc/periodic.conf

daily_clean_hoststat_enable="NO"
daily_status_mail_rejects_enable="NO"
daily_status_include_submit_mailq="NO"
daily_submit_queuerun="NO"


2. Установка Nginx, MySQL, PHP, PHP-extension. Этот web-сервер будет использоваться для PostfixAdmin

Здесь коротко, ибо уже тыщу раз ставилось)


Nginx cтавим из пакетов

# pkg install nginx


основной конфиг /usr/local/etc/nginx/nginx.conf

user www;
worker_processes  2;
pid        /var/run/nginx.pid;
events {
worker_connections  1024;
}

http {
     access_log    /var/log/nginx/access.log;
     error_log     /var/log/nginx/error.log;

     include       /usr/local/etc/nginx/mime.types;
     default_type  application/octet-stream;

     sendfile on;
     tcp_nopush on;
     tcp_nodelay on;
     keepalive_timeout  65;
     client_max_body_size 5m;
     server_names_hash_bucket_size 64;
     types_hash_max_size 2048;
     types_hash_bucket_size 64;
     include /usr/local/etc/nginx/conf.d/*.conf;
}


конфиг виртуального хоста /usr/local/etc/nginx/conf/postfix.conf

server {
        listen 80;
        server_name postfix.megapuper.ru;

root /usr/local/www/postfix;
        index index.php index.html index.htm;

        access_log /var/log/nginx/postfix.access.log;
        error_log  /var/log/nginx/postfix.error.log;

location / {
#        try_files $uri $uri/ /index.php?$uri&$args;
        }

location ~ \.php$ {
    fastcgi_pass   127.0.0.1:10000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
    fastcgi_intercept_errors on;
    include fastcgi_params;
        }
    }


PHP и нужные PHP-extension тоже ставим из пакетов

# pkg install php55
# pkg install php55-* (пригодятся php55-ctype php55-dom php55-gd php55-hash php55-iconv php55-imap php55-json php55-mbstring php55-mcrypt php55-mysql php55-mysqli php55-session php55-xml)


конфиг php-fpm /usr/local/etc/php-fpm.conf

[global]
error_log = /var/log/php/php-fpm.log
pid = /var/run/php-fpm.pid
log_level = notice
include=/usr/local/etc/php/*.conf


конфиг для виртуального хоста /usr/local/etc/php/postfix.conf

[postfix]
prefix = /usr/local/www/$pool
listen = 127.0.0.1:10000
listen.allowed_clients = 127.0.0.1
listen.owner = www
listen.group = www
listen.mode = 0660
user = www
group = www
pm = dynamic
pm.max_children = 4
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
pm.max_requests = 100
;pm.status_path = /status/php-fpm/$pool
request_terminate_timeout = 0
request_slowlog_timeout = 1m
slowlog = /var/log/php/$pool.slow.log
catch_workers_output = yes


MySQL тоже из пакетов

# pkg install mysql56-server


простенький конфиг /etc/my.cnf

[mysqld]
bind-address=127.0.0.1

В конфигах, где используется подключение к базе указываем хост 127.0.0.1

После этого имеем готовый web-сервер можно переходить к установке PostfixAdmin


3. Установка PostfixAdmin

Скачиваем последнюю версию отсюда http://sourceforge.net/projects/postfixadmin/ и заливаем на web-сервер


создаём базу и даём права пользователю

> create database postfix character set utf8 collate utf8_general_ci;
> grant all on postfix.* to postfix@127.0.0.1 identified by 'ПАРОЛЬ';


Папка для логов

# mkdir /var/log/postfixadmin
# chown www:www /var/log/postfixadmin

Правим основной конфиг PostfixAdmin config.inc.php
Spoiler


Выставляем права

# chown -R www:www /usr/local/www/postfix


Теперь заходим на http://postfixadmin/setup.php и видим, что запустилась установка
Если все условия установки выполнены, то в базе создадутся необходимые таблицы и будет предложено создать суперадмина.

В поле Setup password вводим пароль из config.inc.php: $CONF['setup_password'] = 'пароль_установки';
Заполняем остальные поля, и после нажатия кнопки Создать сгенерится хэш.

Этот хеш надо вставить в config.inc.php вместо пароля установки: $CONF['setup_password'] = 'хеш';
Повторяем процедуру заведения суперадмина используя пароль_установки

После создания суперадмина временно оставляем PostfixAdmin(так как без postfix и dovecot ящики создаваться не будут)

Закрываем страницу установки

$CONF['configured'] = false;


6. Установка Postfix

Postfix ставим из портов, т.к. пакет ставится без поддержки mysql

# cd /usr/ports/mail/postfix
# make install clean
[X] MYSQL, PCRE, SASL2, TLS
CYRUS-SASL [X] MYSQL, CRAM, DIGEST, LOGIN, PLAIN

По окончании установки активируем postfix

Would you like to activate Postfix in /etc/mail/mailer.conf [n]? y

Заведём нужные aliases /etc/aliases

www:    postmaster@megapuper.ru

Инициализируем базу алиасов

# newaliases


Рихтуем основные конфиги postfix
первый /usr/local/etс/postfix/main.cf
Spoiler


второй конфиг/usr/local/etс/postfix/master.cfоставляем дефолтным
Spoiler


Создаём таблицы данных формата "hash" и базы с помощью команды postmap
Необходимо создать файлы и базы со списками, которые были подключены в конфиге выше, даже если они будут пустыми

# touch aliases_lmtp
# touch aliases_smtp_output
# postmap aliases_lmtp
# postmap aliases_smtp_output


Создаём файлы, хранящие SQL-запросы, проверяя имена таблиц и полей (в очередной версии PostfixAdmin они могут измениться)

[/usr/local/etc/postfix/maps/mysql_virtual_maps.cf]

user = postfix
password = ПАРОЛЬ
hosts = 127.0.0.1
dbname = postfix
query = SELECT username FROM mailbox WHERE username='%s' AND active = '1'
[/usr/local/etc/postfix/maps/mysql_virtual_domains.cf]

user = postfix
password = ПАРОЛЬ
hosts = 127.0.0.1
dbname = postfix
query = SELECT domain FROM domain WHERE domain = '%s' AND backupmx = '0' AND active = '1'
[/usr/local/etc/postfix/maps/mysql_virtual_alias_maps.cf]

user = postfix
password = ПАРОЛЬ
hosts = 127.0.0.1
dbname = postfix
query = SELECT goto FROM alias WHERE address='%s' AND active = '1'
[/usr/local/etc/postfix/maps/mysql_virtual_alias_domain_maps.cf]

user = postfix
password = ПАРОЛЬ
hosts = 127.0.0.1
dbname = postfix
query = SELECT CONCAT('%u', '@', target_domain) FROM alias_domain WHERE alias_domain = '%d' AND active = 1


Следующие два необязательны, если не будем делать сохранение копий всех писем

[/usr/local/etc/postfix/maps/mysql_bcc_domain_maps.cf]

user = postfix
password = ПАРОЛЬ
hosts = 127.0.0.1
dbname = postfix
query = SELECT 'bccsnd+bccflag@megapuper.ru' FROM domain WHERE domain='%d' AND active = '1'
[/usr/local/etc/postfix/maps/mysql_bcc_mailbox_maps.cf]

user = postfix
password = ПАРОЛЬ
hosts = 127.0.0.1
dbname = postfix
query = SELECT CONCAT('%u', '+bccflag', '@', '%d') FROM mailbox WHERE username='%s' AND active = '1'


Выставляем права на конфиги

# chgrp postfix /usr/local/etc/postfix/*.cf
# chgrp postfix /usr/local/etc/postfix/maps/*.cf
# chmod u=rw,g=r,o= /usr/local/etc/postfix/*.cf
# chmod u=rw,g=r,o= /usr/local/etc/postfix/maps/*.cf


Рестартим postfix

# /usr/local/etc/rc.d/postfix restart


7. Установка Dovecot
Dovecot ставим из портов

# cd /usr/ports/mail/dovecot2/
# make install clean
[X] MYSQL


Устанавливаем поддержку языка Sieve в Dovecot(включает в себя настройку скриптов пользователями)

# cd /usr/ports/mail/dovecot2-pigeonhole
# make install clean


Создаём сопутствуюшие папки

# mkdir /var/log/dovecot
# mkdir -p /var/lib/dovecot/sieve/global/
# mkdir -p /var/lib/dovecot/sieve/private/


Выставляем права

# chown -R mail:wheel /var/lib/dovecot/sieve/private/
# chmod -R 700 /var/lib/dovecot/sieve/private/

Правим конфиги dovecot

[/usr/local/etc/dovecot/dovecot.conf]

# Enable installed protocols
protocols = imap lmtp sieve
dict {
#quota = mysql:/etc/dovecot/dovecot-dict-sql.conf.ext
#expire = sqlite:/etc/dovecot/dovecot-dict-sql.conf.ext
}
!include conf.d/*.conf


[/usr/local/etc/dovecot/dovecot-sql.conf.ext]

driver = mysql
connect = host=127.0.0.1 dbname=postfix user=postfix password=ПАРОЛЬ
default_pass_scheme = PLAIN
#default_pass_scheme = PLAIN-MD5
#   %u = entire user@domain
#   %n = user part of user@domain
#   %d = domain part of user@domain

#одной строкой без переносов
password_query = SELECT username as user, password, '%u' AS userdb_master_user, CONCAT('/var/spool/mail/', maildir) AS userdb_home, 1000 AS userdb_uid, 1000 AS userdb_gid, CONCAT('*:storage=', quota, 'B')
as userdb_quota_rule FROM mailbox WHERE username = '%u' AND active = '1'

#одной строкой без переносов
user_query = SELECT CONCAT('/var/spool/mail/', maildir) AS home, 1000 AS uid, 1000 AS gid, CONCAT('*:storage=', quota, 'B') as quota_rule FROM mailbox WHERE username = '%u' AND active ='1'


[/usr/local/etc/dovecot/dovecot-sql-master.conf.ext]

driver = mysql
#default_pass_scheme = PLAIN-MD5
default_pass_scheme = PLAIN
connect = host=127.0.0.1 dbname=postfix user=postfix password=ПАРОЛЬ
password_query = SELECT username AS user, password FROM admin WHERE username = '%u' AND active = '1'


[/usr/local/etc/dovecot/conf.d/10-auth.conf]

# Connect only after start SSL/TLS
# If not local network only !
disable_plaintext_auth = no
auth_cache_size = 1M
auth_cache_negative_ttl = 0
auth_username_chars = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890.-_@
auth_master_user_separator = *
auth_mechanisms = plain

!include auth-sql.conf.ext


[/usr/local/etc/dovecot/conf.d/10-director.conf]

service director {
  unix_listener login/director {
    #mode = 0666
  }
  fifo_listener login/proxy-notify {
    #mode = 0666
  }
  unix_listener director-userdb {
    #mode = 0600
  }
  inet_listener {
    #port =
  }
}
# Enable director for the wanted login services by telling them to
# connect to director socket instead of the default login socket:
service imap-login {
  #executable = imap-login director
}

#service pop3-login {
  #executable = pop3-login director
#}

# Enable director for LMTP proxying:
protocol lmtp {
  #auth_socket_path = director-userdb
}


[/usr/local/etc/dovecot/conf.d/10-logging.conf]

# Log file to use for error messages. "syslog" logs to syslog,
# /dev/stderr logs to stderr.
log_path = /var/log/dovecot/dovecot.log
info_log_path = /var/log/dovecot/dovecot-info.log
debug_log_path = /var/log/dovecot/dovecot-debug.log
auth_verbose = yes
auth_verbose_passwords = yes
auth_debug = no
auth_debug_passwords = no
mail_debug = yes
verbose_ssl = no

#plugin {
#}
#log_timestamp = "%b %d %H:%M:%S "
#login_log_format_elements = user=<%u> method=%m rip=%r lip=%l mpid=%e %c
#login_log_format = %$: %s
#mail_log_prefix = "%s(%u): "
#  Format to use for logging mail deliveries. You can use variables:
#  %$ - Delivery status message (e.g. "saved to INBOX")
#  %m - Message-ID
#  %s - Subject
#  %f - From address
#  %p - Physical size
#  %w - Virtual size
#deliver_log_format = msgid=%m: %$


[/usr/local/etc/dovecot/conf.d/10-mail.conf]

mail_location = maildir:/var/spool/mail/%d/%n:INBOX=/var/spool/mail/%d/%n

namespace inbox {
  type = private
  separator = /
  prefix =
  inbox = yes
  hidden = no
  list = yes
  subscriptions = yes
}

mail_uid = 1000
mail_gid = 1000


[/usr/local/etc/dovecot/conf.d/10-master.conf]

service imap-login {
 inet_listener imap {
  address = *
  port = 143
  #ssl = yes
 }
 inet_listener imaps {
  #port = 993
  #ssl = yes
 }

}

#service pop3-login {
  #inet_listener pop3 {
  #port = 110
  #}
  #inet_listener pop3s {
  #port = 995
  #ssl = yes
 #}
#}

service lmtp {
  unix_listener lmtp {
  path = /var/spool/postfix/private/dovecot-lmtp
  group = postfix
  mode = 0660
  user = postfix
  #mode = 0666
 }
 executable = lmtp -L
}

service imap {
  #vsz_limit = $default_vsz_limit
  # Max. number of IMAP processes (connections)
  #process_limit = 1024
  #executable = imap
}
#service pop3 {
 # Max. number of POP3 processes (connections)
 #process_limit = 1024
#}

service auth {
  unix_listener auth {
  path = /var/spool/postfix/private/auth
  mode = 0660
  user = postfix
  group = postfix
 }
 user = $default_internal_user
}

service auth-worker {
  user = $default_internal_user
}


[/usr/loca/etc/dovecot/conf.d/15-lda.conf]

postmaster_address = postmaster@megapuper.ru
hostname = mail.megapuper.ru
#rejection_subject = Rejected: %s
#  %n = CRLF, %r = reason, %s = original subject, %t = recipient
rejection_reason = Your message to <%t> was automatically rejected:%n%r

protocol lda {
  mail_plugins = sieve
  log_path = /var/log/dovecot/mail-dovecot-lda-errors.log
  info_log_path = /var/log/dovecot/mail-dovecot-lda.log
}


[/usr/local/etc/dovecot/conf.d/20-imap.conf]

protocol imap {
 mail_plugins = $mail_plugins imap_acl imap_quota mail_log notify acl quota
 #ssl_cert = </usr/local/etc/dovecot/ssl.cert.pem
 #ssl_key = </usr/local/etc/dovecot/ssl.key.pem
 info_log_path = /var/log/dovecot/dovecot-imap.log
 #mail_max_userip_connections = 10
 # IMAP logout format string:
 # %i - total number of bytes read from client
 # %o - total number of bytes sent to client
 #imap_logout_format = bytes=%i/%o
 #imap_capability =
 #imap_idle_notify_interval = 2 mins
 #imap_id_send =
 #imap_id_log =
}


[/usr/local/etc/dovecot/conf.d/20-lmtp.conf]

protocol lmtp {
 mail_plugins = $mail_plugins quota sieve
 postmaster_address = postmaster@megapuper.ru
 info_log_path = /var/log/dovecot/dovecot-lmtp.log
}


[/usr/local/etc/dovecot/conf.d/20-managesieve.conf]

service managesieve-login {
  inet_listener sieve {
  address = 127.0.0.1
  port = 4190
}
 service_count = 1
 vsz_limit = 64M
}
#mail_plugins = virtual
#protocol sieve {
 #managesieve_max_line_length = 65536
 #mail_max_userip_connections = 10
 #mail_plugins = virtual
 # MANAGESIEVE logout format string:
 #  %i - total number of bytes read from client
 #  %o - total number of bytes sent to client
 #managesieve_logout_format = bytes=%i/%o
 #managesieve_implementation_string = Dovecot Pigeonhole
 #managesieve_sieve_capability =
 #managesieve_notify_capability =
 #managesieve_max_compile_errors = 5
#}


[/usr/local/etc/dovecot/conf.d/90-quota.conf]

plugin {
  quota = dict:user::file:/var/spool/mail/%d/%n/dovecot-quota
  quota_rule = *:storage=1GB
  quota_rule2 = Trash:storage=+10%%
}

# Note that % needs to be escaped as %%, otherwise "% " expands to empty.
plugin {
  #quota_warning = storage=95%% quota-warning 95 %u
  #quota_warning2 = storage=80%% quota-warning 80 %u
}

plugin {
  #quota = dirsize:User quota
  #quota = maildir:User quota
  #quota = dict:User quota::proxy::quota
  #quota = fs:User quota
}

plugin {
  #quota = dict:user::proxy::quota
  #quota2 = dict:domain:%d:proxy::quota_domain
  #quota_rule = *:storage=102400
  #quota2_rule = *:storage=1048576
}
[/usr/local/etc/dovecot/conf.d/90-sieve.conf]

plugin {
 sieve_user_log = /var/lib/dovecot/sieve/private/%d/%n/.main.peronal.log
 sieve = /var/lib/dovecot/sieve/private/%d/%n/.main.personal.sieve
 #sieve_default = /var/lib/dovecot/sieve/default.sieve
 sieve_dir = /var/lib/dovecot/sieve/private/%d/%n/
 sieve_global_dir = /var/lib/dovecot/sieve/global/
 #sieve_before2 =
 sieve_before = /var/lib/dovecot/sieve/global/incoming_deduplicate.sieve
 #sieve_after =
 #sieve_after2 =
 sieve_extensions = +editheader
 sieve_global_extensions = +vnd.dovecot.duplicate
 sieve_duplicate_period = 1d
 #sieve_plugins =
 recipient_delimiter = +
 #sieve_max_script_size = 1M
 #sieve_max_actions = 32
 #sieve_max_redirects = 4
 #sieve_quota_max_scripts = 0
 #sieve_quota_max_storage = 0
}


[/usr/local/etc/dovecot/conf.d/auth-sql.conf.ext]

auth_master_user_separator = *
#auth_debug = yes
passdb {
  driver = sql
  args = /usr/local/etc/dovecot/dovecot-sql-master.conf.ext
  master = yes
  pass = yes
}
passdb {
  driver = sql
  args = /usr/local/etc/dovecot/dovecot-sql.conf.ext
  #default_fields = userdb_gid=1000 userdb_uid=1000
}
userdb {
  driver = prefetch
}
userdb {
  driver = sql
  args = /usr/local/etc/dovecot/dovecot-sql.conf.ext
  #default_fields = uid=1000 gid=1000
}


Меняем права и владельца конфигов:

# chgrp vmail /usr/local/etc/dovecot/*.conf
# chmod g+r /usr/local/etc/dovecot/*.conf
# chgrp vmail /usr/local/etc/dovecot/*.ext
# chmod g+r /usr/local/etc/dovecot/*.ext
# chgrp vmail /usr/local/etc/dovecot/conf.d/*.conf
# chmod g+r /usr/local/etc/dovecot/conf.d/*.conf
# chgrp vmail /usr/local/etc/dovecot/conf.d/*.ext
# chmod g+r /usr/local/etc/dovecot/conf.d/*.ext


Теперь можно вернуться к PostfixAdmin и приступить к созданию доменов и ящиков