1. 程式人生 > >郵件服務器postfix+dovecot+mysql

郵件服務器postfix+dovecot+mysql

root con 域名 extern ech edi 概覽 value detail

1.前期準備

1.1設置hostname

CentOS7,可以通過hostnamectl set-hostname hostname命令設置hostname,並且修改hosts文件.這裏域名是sijibao.info.

hostnamectl set-hostname mail.sijibao.info

為什麽要設置hostname呢?因為一般情況下,Postfix在與其他的SMTP服務器進行通信的時候,會使用hostname來表名自己的身份.
主機名有兩種形式,單名字與FQDN(Fully Qualified Domain Name).如果SMTP服務器不是用FQDN來表明身份,則有可能會被拒收.

1.2修改防火墻開放端口

修改防火墻開發相應的端口,分別是25, 465, 587, 110, 995, 143, 993.

1.3域名解析配置

MX       mail       sijibao.info
A        mail       ip

2.安裝Postfix, Dovecot以及數據庫

2.1首先更新系統

yum update -y.
把系統的一些組件更新到最新,然後需要修改一些CentOS的源設置.
因為CentOS默認源裏面的Postfix默認是不能和MariaDB協同工作的,因而我們需要安裝擴展源裏面的Postfix.

修改: /etc/yum.repos.d/CentOS-Base.repo
[base]
name=CentOS-$releasever - Base
exclude=postfix
#released updates
[updates]
name=CentOS-$releasever - Updates
exclude=postfix
修改完畢以後,我們讓擴展源生效,並且安裝我們所需要的應用以及服務.

2.2 yum 安裝

yum --enablerepo=centosplus install postfix
yum install dovecot mariadb-server dovecot-mysql

2.3數據庫概覽

創建mail數據庫用以處理郵件相關的業務.並且創建郵件管理員.


GRANT SELECT, INSERT, UPDATE, DELETE ON mail.* TO ‘mail_admin‘@‘%‘ IDENTIFIED BY ‘mys123456‘;
FLUSH PRIVILEGES;

mail數據庫中一共有3個表,分別是虛擬域名, 用戶信息, 郵件轉發.

CREATE TABLE `domains` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
);

CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`domain_id` int(11) NOT NULL,
`password` varchar(106) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
);

CREATE TABLE `aliases` (
`id` INT NOT NULL AUTO_INCREMENT,
`domain_id` INT NOT NULL,
`source` varchar(100) NOT NULL,
`destination` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE
);

在虛擬域名表中插入域名

INSERT INTO `mail`.`domains`
(`id` ,`name`)
VALUES
(‘1‘, ‘sijibao.info‘),
(‘2‘, ‘localhost.sijibao.info‘);

在用戶 信息表中插入用戶

INSERT INTO `mail`.`users`
(`id`, `domain_id`, `password` , `email`)
VALUES
(‘1‘, ‘1‘, ENCRYPT(‘123123‘), ‘[email protected]‘),
(‘2‘, ‘1‘, ENCRYPT(‘123123‘), ‘[email protected]‘);

設置別名

INSERT INTO `mail`.`aliases`
(`id`, `domain_id`, `source`, `destination`)
VALUES
(‘1‘, ‘1‘, ‘[email protected]‘, ‘[email protected]‘),
(‘2‘, ‘1‘, ‘[email protected]‘, ‘[email protected]‘);

檢查是否有數據

SELECT * FROM mail.domains;
SELECT * FROM mail.users;
SELECT * FROM mail.aliases;

3.配置Postfix

        master: /etc/postfix/master.cf   (主進程的配置文件)
        mail:   /etc/postfix/main.cf    (功能性配置文件)
表示方法:參數 = 值   (參數定格寫在行首,以空白開頭的行認為是上一行的延續)

3.1 postfix模塊化配置:

先備份源文件

cp /etc/postfix/main.cf /etc/postfix/main.cf.org
更改配置(默認的不用動)
vi /etc/postfix/main.cf
myhostname = mail.sijibao.info
mydestination = localhost, localhost.localdomain
mynetworks = 127.0.0.0/8            
inet_interfaces = all               
message_size_limit = 30720000         
relayhost =                     
alias_maps = hash:/etc/aliases          

smtpd_tls_key_file = /etc/pki/dovecot/private/dovecot.pem   
smtpd_tls_cert_file = /etc/pki/dovecot/certs/dovecot.pem
smtpd_use_tls=yes
smtpd_tls_auth_only = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes 
smtpd_recipient_restrictions =permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination

virtual_transport = dovecot
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf,mysql:/etc/postfix/mysql-virtual-email2email.cf

3.2 postfix配置文件解釋:

mydomain參數是指email服務器的域名,請確保為正式域名(如sijibao.info)
myhostname參數是指系統的主機名稱(如我的服務器主機名稱是mail.sijibao.info)
myorigin參數指定本地發送郵件中來源和傳遞顯示的域名。
myorigin = $mydomain 設置由本機寄出的郵件所使用的域名或主機名稱
mynetworks參數指定受信任SMTP的列表,具體的說,受信任的SMTP客戶端允許通過Postfix傳遞郵件。0.0.0.0/0 #配置這一項使用用戶可在任意地發送郵件 
mydestination參數指定哪些郵件地址允許在本地發送郵件。這是一組被信任的允許通過服務器發送或傳遞郵件的IP地址。
用戶試圖通過發送從此處未列出的IP地址的原始服務器的郵件將被拒絕。
inet_interfaces參數設置網絡接口以便Postfix能接收到郵件。
relay_domains:該參數是系統傳遞郵件的目的域名列表。如果留空,我們保證了我們的郵件服務器不對不信任的網絡開放。
home_mailbox:該參數設置郵箱路徑與用戶目錄有關,也可以指定要使用的郵箱風格。 
message_size_limit = 52428800 ###限制附件大小 
mailbox_size_limit = 209715200 ###容量大小 
註意:默認postfix從mydestination和virtual_mailbox_domains兩個參數來確定postfix需要接收哪些域的郵件。
如果接收的郵件域與mydestination匹配,則使用系統帳號處理郵件;
如果接收的郵件域與virtual_mailbox_domains匹配則使用虛擬帳號處理郵件。
alias_maps = hash:/etc/aliases   在具有NIS的系統上,缺省值是搜索本地別名數據庫,然後搜索NIS別名數據庫。
不設置會有 warning: dict_nis_init: NIS domain name not set - NIS lookups disabled

smtpd_tls_key_file = /etc/pki/dovecot/private/dovecot.pem   你希望使用自己的SSL證書,私鑰路徑,則把/etc/pki/dovecot/private/dovecot.pem替換成你的證書路徑.
smtpd_tls_cert_file = /etc/pki/dovecot/certs/dovecot.pem    你希望使用自己的SSL證書,公鑰路徑,則把/etc/pki/dovecot/certs/dovecot.pem替換成你的證書路徑.
smtpd_sasl_auth_enable = yes     //使用SMTP認證  
smtpd_sasl_security_options = noanonymous //取消匿名登陸方式 
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination //設定郵件中有關收件人部分的限制  
smtpd_sasl_type = dovecot smtp使用dovecot驗證
smtpd_use_tls=yes     向遠程SMTP客戶端宣布STARTTLS支持,但不要求客戶端使用TLS加密
smtpd_tls_auth_only = yes  當Postfix SMTP服務器中的TLS加密是可選的時,請勿通過未加密的連接通告或接受SASL認證。

virtual_transport = dovecot 以dovecot 默認郵件傳遞傳輸和下一跳的目標
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf  /讀取數據庫虛擬域 
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf     查詢包含與$ virtual_mailbox_domains匹配的域中的所有有效地址。
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf,mysql:/etc/postfix/mysql-virtual-email2email.cf
用於將特定郵件地址或域別名混合到其他本地或遠程地址

4.創建連接mysql的虛擬用戶文件

4.1創建配置文件

創建虛擬域名配置

vim /etc/postfix/mysql-virtual-mailbox-domains.cf 
user = mail_admin
password = mys123456
hosts = 127.0.0.1
dbname = mail
query = SELECT 1 FROM domains WHERE name=‘%s‘

創建虛擬郵箱配置

vim /etc/postfix/mysql-virtual-mailbox-maps.cf 
user = mail_admin
password = mys123456
hosts = 127.0.0.1
dbname = mail
query = SELECT 1 FROM users WHERE email=‘%s‘

創建電子郵件與文件映射

vim /etc/postfix/mysql-virtual-alias-maps.cf 
user = mail_admin
password = mys123456
hosts = 127.0.0.1
dbname = mail
query = SELECT destination FROM aliases WHERE source=‘%s‘
vim /etc/postfix/mysql-virtual-email2email.cf 
user = mail_admin
password = mys123456
hosts = 127.0.0.1
dbname = mail
query = SELECT email FROM users WHERE email=‘%s‘

啟動postfix

service postfix restart

4.2 測試文件是否調用成功

postmap -q sijibao.info mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
1
postmap -q [email protected] mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
1
postmap -q [email protected] mysql:/etc/postfix/mysql-virtual-alias-maps.cf
[email protected]

返回結果就配置正常

5.更改master.cf配置文件

cp /etc/postfix/master.cf /etc/postfix/master.cf.org

vim /etc/postfix/master.cf

#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master").
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================

smtp      inet  n       -       n       -       -       smtpd
#smtp      inet  n       -       n       -       1       postscreen
#smtpd     pass  -       -       n       -       -       smtpd
#dnsblog   unix  -       -       n       -       0       dnsblog
#tlsproxy  unix  -       -       n       -       0       tlsproxy
submission inet n       -       n       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_client_restrictions=$mua_client_restrictions
  -o smtpd_helo_restrictions=$mua_helo_restrictions
  -o smtpd_sender_restrictions=$mua_sender_restrictions
  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       n       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_client_restrictions=$mua_client_restrictions
  -o smtpd_helo_restrictions=$mua_helo_restrictions
  -o smtpd_sender_restrictions=$mua_sender_restrictions
  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       n       -       -       qmqpd
pickup    unix  n       -       n       60      1       pickup
cleanup   unix  n       -       n       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       n       1000?   1       tlsmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
trace     unix  -       -       n       -       0       bounce
verify    unix  -       -       n       -       1       verify
flush     unix  n       -       n       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       n       -       -       smtp
relay     unix  -       -       n       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       n       -       -       showq
error     unix  -       -       n       -       -       error
retry     unix  -       -       n       -       -       error
discard   unix  -       -       n       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
anvil     unix  -       -       n       -       1       anvil
scache    unix  -       -       n       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
#maildrop  unix  -       n       n       -       -       pipe
#  flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/usr/lib/cyrus-imapd/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
#
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/usr/lib/cyrus-imapd/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
#uucp      unix  -       n       n       -       -       pipe
#  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# ====================================================================
#
# Other external delivery methods.
#
#ifmail    unix  -       n       n       -       -       pipe
#  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
#
#bsmtp     unix  -       n       n       -       -       pipe
#  flags=Fq. user=bsmtp argv=/usr/local/sbin/bsmtp -f $sender $nexthop $recipient
#
#scalemail-backend unix -       n       n       -       2       pipe
#  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store
#  ${nexthop} ${user} ${extension}
#
#mailman   unix  -       n       n       -       -       pipe
#  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
#  ${nexthop} ${user}
dovecot   unix  -       n       n       -       -       pipe
    flags=DRhu user=vmail:vmail argv=/usr/libexec/dovecot/deliver -f ${sender} -d ${recipient}

-------------------------------------------------

重啟postfix

service postfix restart

6.測試本地郵件服務是否正常

6.1 smtp協議命令源語

helo (smtp協議)
ehlo(esmtp協議)

mail from:senduser  指定發件人信息
rcpt to:reciver             指定收件人信息      對於公共郵箱必須有域名、A紀錄、PTR解析。
data                    指定發送的信息

6.2 測試

telnet 127.0.0.1 25
helo mail.sijibao.info
mail from:[email protected]
250 2.1.0 Ok
rcpt to:[email protected]
250 2.1.5 Ok
data
354 End data with <CR><LF>.<CR><LF>
This is a test mail from root.
.
250 2.0.0 Ok: queued as 3E55D20DCF12
quit  
221 2.0.0 Bye
[root@mail conf.d]#  mailq
-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------
3E55D20DCF12      355 Fri Jun 15 14:57:01  [email protected]
                                                  (mail transport unavailable)

7. Dovecot Configuration Setup

備份文件

cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf.org
cp /etc/dovecot/conf.d/10-mail.conf /etc/dovecot/conf.d/10-mail.conf.org
cp /etc/dovecot/conf.d/10-auth.conf /etc/dovecot/conf.d/10-auth.conf.org
cp /etc/dovecot/dovecot-sql.conf.ext /etc/dovecot/dovecot-sql.conf.ext.org
cp /etc/dovecot/conf.d/10-master.conf /etc/dovecot/conf.d/10-master.conf.org
cp /etc/dovecot/conf.d/10-ssl.conf /etc/dovecot/conf.d/10-ssl.conf.org

7.1 配置10-mail.conf

vim /etc/dovecot/conf.d/10-mail.conf
mail_location =  maildir:/home/vmail/%d/%n/Maildir   ##指定用戶郵件保存路徑
mail_privileged_group = mail
# groupadd -g 5000 vmail
# useradd -g vmail -u 5000 vmail
vim /etc/dovecot/conf.d/10-auth.conf
auth_mechanisms = plain login
#!include auth-system.conf.ext
!include auth-sql.conf.ext     ##在同一文件中註釋系統用戶登錄行,並通過取消註釋‘auth-sql.conf.ext‘行來啟用MySQL身份驗證

7.2 配置auth-sql.conf.ext

vim /etc/dovecot/conf.d/auth-sql.conf.ext
# Authentication for SQL users. Included from 10-auth.conf.
#
# <doc/wiki/AuthDatabase.SQL.txt>

passdb {
  driver = sql

  # Path for SQL configuration file, see example-config/dovecot-sql.conf.ext
  args = /etc/dovecot/dovecot-sql.conf.ext       ##使用指定文件,mysqlsql驗證密碼
}

# "prefetch" user database means that the passdb already provided the
# needed information and there‘s no need to do a separate userdb lookup.
# <doc/wiki/UserDatabase.Prefetch.txt>
#userdb {
#  driver = prefetch
#}

userdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf.ext       ##使用指定文件,mysqlsql驗證用戶
}

# If you don‘t have any user-specific settings, you can avoid the user_query
# by using userdb static instead of userdb sql, for example:
# <doc/wiki/UserDatabase.Static.txt>
#userdb {
  #driver = static
  #args = uid=vmail gid=vmail home=/var/vmail/%u
#}

7.3 編輯連接sql的文件


vim /etc/dovecot/dovecot-sql.conf.ext
driver = mysql
connect = host=127.0.0.1  dbname=mail user=mail_admin password=mys123456
default_pass_scheme = CRYPT
password_query = SELECT email as user, password FROM users WHERE email=‘%u‘;
user_query = SELECT (‘5000‘) as ‘uid‘,(‘5000‘) as ‘gid‘

# chown -R vmail:dovecot /etc/dovecot
# chmod -R o-rwx /etc/dovecot

7.4 配置10-master.conf

更改dovecot的master文件


vim /etc/dovecot/conf.d/10-master.conf
#default_process_limit = 100
#default_client_limit = 1000

# Default VSZ (virtual memory size) limit for service processes. This is mainly
# intended to catch and kill processes that leak memory before they eat up
# everything.
#default_vsz_limit = 256M

# Login user is internally used by login processes. This is the most untrusted
# user in Dovecot system. It shouldn‘t have access to anything at all.
#default_login_user = dovenull

# Internal user is used by unprivileged processes. It should be separate from
# login user, so that login processes can‘t disturb other processes.
#default_internal_user = dovecot

service imap-login {
  inet_listener imap {
    #port = 143                  ##禁止使用非ssl端口
  }
  inet_listener imaps {
    port = 993
    ssl = yes
  }

  # Number of connections to handle before starting a new process. Typically
  # the only useful values are 0 (unlimited) or 1. 1 is more secure, but 0
  # is faster. <doc/wiki/LoginProcess.txt>
  #service_count = 1

  # Number of processes to always keep waiting for more connections.
  #process_min_avail = 0

  # If you set service_count=0, you probably need to grow this.
  #vsz_limit = $default_vsz_limit
}

service pop3-login {
  inet_listener pop3 {
    port = 0            ##禁止使用非ssl端口
  }
  inet_listener pop3s {
    port = 995
    ssl = yes           ##開啟ssl
  }
}

service lmtp {
  unix_listener /var/spool/postfix/private/dovecot-lmtp {
    mode = 0600
    user = postfix
    group = postfix
  }

  # Create inet listener only if you can‘t use the above UNIX socket
  #inet_listener lmtp {
    # Avoid making LMTP visible for the entire internet
    #address =
    #port = 
  #}
}

service imap {
  # Most of the memory goes to mmap()ing files. You may need to increase this
  # limit if you have huge mailboxes.
  #vsz_limit = $default_vsz_limit

  # Max. number of IMAP processes (connections)
  #process_limit = 1024
}

service pop3 {
  # Max. number of POP3 processes (connections)
  #process_limit = 1024
}

service auth {
  # auth_socket_path points to this userdb socket by default. It‘s typically
  # used by dovecot-lda, doveadm, possibly imap process, etc. Users that have
  # full permissions to this socket are able to get a list of all usernames and
  # get the results of everyone‘s userdb lookups.
  #
  # The default 0666 mode allows anyone to connect to the socket, but the
  # userdb lookups will succeed only if the userdb returns an "uid" field that
  # matches the caller process‘s UID. Also if caller‘s uid or gid matches the
  # socket‘s uid or gid the lookup succeeds. Anything else causes a failure.
  #
  # To give the caller full permissions to lookup all users, set the mode to
  # something else than 0666 and Dovecot lets the kernel enforce the
  # permissions (e.g. 0777 allows everyone full permissions).
  unix_listener auth-userdb {
    mode = 0666
    user = vmail
    #group = 
  }

  # Postfix smtp-auth
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
    user = postfix
    user = postfix
  }

  # Auth process is run as this user.
  #user = $default_internal_user
  user= dovecot
}

service auth-worker {
  # Auth worker process is run as root by default, so that it can access
  # /etc/shadow. If this isn‘t necessary, the user should be changed to
  # $default_internal_user.
  #user = root
  user = vmail
}

service dict {
  # If dict proxy is used, mail processes should have access to its socket.
  # For example: mode=0660, group=vmail and global mail_access_groups=vmail
  unix_listener dict {
    #mode = 0600
    #user = 
    #group = 
  }
}

重啟dovecot
service dovecot restart

8、測試驗證

使用本地客戶端例如fixmail等
技術分享圖片

郵件服務器postfix+dovecot+mysql