1. 程式人生 > >Ubuntu Server 12.04 配置郵件伺服器完整篇

Ubuntu Server 12.04 配置郵件伺服器完整篇

一、準備工作

首先設定域名的A記錄和MX記錄

1.web登入到域名解析的後臺介面,選擇新建,型別選擇A記錄,主機名為mail.您的域名,ip/主機值填寫您的伺服器的公網地址。

2.新增Mx記錄,型別選擇mx,主機名為您的域名(不用加字首)值為mail.您的域名。

一定要注意在新增MX記錄時,RR值要留空,沒有任何字首,如圖。

配置完畢後必須有兩條記錄:

如上圖中紅色框圈中的部分

3.檢查域名配置

Windows環境下:

做好後檢查是否生效可以在ms-dos下去檢查,開始-執行-cmd,輸入nslookup回車

檢查mx記錄後輸入set type=mx 回車,輸入您的域名(yourdomain.com,注意不要加mail) 如果出現類似這樣的提示那就是mx是成功的。

> set type=mx

>yourdomain.com

Server:cache-b.guangzhou.gd.cn

Address:202.96.128.166

Non-authoritativeanswer:

yourdomain.com MXpreference = 10, mail exchanger = mail. yourdomain.com

mail.yourdomain.com internet address = 1.1.1.1

同樣檢查a記錄也一樣set type=a 輸入您的主機名(這裡要加mail),如果最後得到的反饋地址是您的伺服器的公網地址,那說明解析是正確生效的。

Linux環境下:

 host -t mx example.org

注意沒有mail字首


返回類似上面的資訊說明配置成功了。

二.配置郵件服務

本文中的所有操作都是在root環境下操作的,請切換到root後再進行操作sudo su -

要安裝的軟體如下:Apache、PHP、Postfix、Postfix Admin、Dovecot、Postgrey、amavisd-new、Clam AntiVirus、SpamAssassin

本節參考文章:https://www.exratione.com/2012/05/a-mailserver-on-ubuntu-1204-postfix-dovecot-mysql/

1.配置web環境

apt-get install apache2
apt-get install libapache2-mod-php5 php5 php5-imap php-apc php5-curl php5-gd php-xml-parser

在瀏覽器裡輸入http://localhost或者mail.xxxx.org(剛才配置的域名),如果看到了It works!,就說明Apache安裝成功了。

Apache的預設安裝,會在/var下建立一個名為www的目錄,這個就是Web目錄了,所有要能過瀏覽器訪問的Web檔案都要放到這個目錄裡。

我們在Web目錄下面新建一個test.php檔案來測試PHP是否能正常的執行,命令:

vi /var/www/test.php
加入如下內容
<?php echo "hello,world"?>
儲存退出。

重啟apache

service apache2 restart
訪問:mail.xxx.org/test.php,顯示hello,world就表示php環境已經搭建好了。

安裝資料庫,配置過程我就不說了,很簡單。

apt-get install mysql-server

安裝完成後,用root登入
mysql -uroot -p
執行下列語句,建立一個mail資料庫和使用者並賦予許可權
create database mail;
grant all on mail.* to 'mail'@'localhost' identified by 'mailpassword';

2.設定主機域名
hostname mail.example.com
編輯/etc/hostname 為
mail.example.com

再編輯/etc/hosts檔案在第一行加入
127.0.0.1 mail.example.com localhost
 
# Usually some IPv6 configuration below the first line, but leave that alone.

3.配置postfix

安裝郵件服務軟體

apt-get install mail-server^
apt-get install postfix-mysql dovecot-mysql postgrey
apt-get install amavis clamav clamav-daemon spamassassin
apt-get install libnet-dns-perl pyzor razor
apt-get install arj bzip2 cabextract cpio file gzip nomarch pax unzip zip

安裝postfixadmin
wget http://downloads.sourceforge.net/project/postfixadmin/postfixadmin/postfixadmin-2.3.6/postfixadmin-2.3.6.tar.gz
gunzip postfixadmin-2.3.6.tar.gz
tar -xf postfixadmin-2.3.6.tar
mv postfixadmin-2.3.6 /var/www/postfixadmin
chown -R www-data:www-data /var/www/postfixadmin

編輯postfixadmin的安裝配置檔案
vi /var/www/postfixadmin/config.inc.php

啟用安裝
/*****************************************************************
 *  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 * You have to set $CONF['configured'] = true; before the
 * application will run!
 * Doing this implies you have changed this file as required.
 * i.e. configuring database etc; specifying setup.php password etc.
 */
$CONF['configured'] = true;

postfixadmin的管理地址

// Postfix Admin Path
// Set the location of your Postfix Admin installation here.
// YOU MUST ENTER THE COMPLETE URL e.g. http://domain.tld/postfixadmin
$CONF['postfix_admin_url'] = 'https://mail.example.com/postfixadmin';

資料庫配置

// Database Config
// mysql = MySQL 3.23 and 4.0, 4.1 or 5
// mysqli = MySQL 4.1+
// pgsql = PostgreSQL
$CONF['database_type'] = 'mysql';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'mail';
$CONF['database_password'] = 'mailpassword';
$CONF['database_name'] = 'mail';
管理員賬號
// Site Admin
// Define the Site Admins email address below.
// This will be used to send emails from to create mailboxes.
$CONF['admin_email'] = '[email protected]';
 
// Mail Server
// Hostname (FQDN) of your mail server.
// This is used to send email to Postfix in order to create mailboxes.
//
// Set this to localhost for now, but change it later.
$CONF['smtp_server'] = 'localhost';
$CONF['smtp_port'] = '25';
密碼加密方式
// Encrypt
// In what way do you want the passwords to be crypted?
// md5crypt = internal postfix admin md5
// md5 = md5 sum of the password
// system = whatever you have set as your PHP system default
// cleartext = clear text passwords (ouch!)
// mysql_encrypt = useful for PAM integration
// authlib = support for courier-authlib style passwords
// dovecot:CRYPT-METHOD = use dovecotpw -s 'CRYPT-METHOD'. Example: dovecot:CRAM-MD5
$CONF['encrypt'] = 'md5crypt';
開啟http://mail.example.com/postfixadmin/setup.php進行安裝

這個時候在安裝密碼處輸入你的密碼(隨便輸),然後點生成,把生成的加密密碼複製到剛才的配置檔案中

// In order to setup Postfixadmin, you MUST specify a hashed password here.
// To create the hash, visit setup.php in a browser and type a password into the field,
// on submission it will be echoed out to you as a hashed value.
$CONF['setup_password'] = '...a long hash string...';

替換掉...a long hash string...

再回到頁面進行安裝即可,同時還可以新增管理員賬號。

安裝完成後我們要把/var/www/postfixadmin/setup.php 設定成禁止訪問,以防出現安全問題。

建立一個新檔案

vi /var/www/postfixadmin/.htaccess 
加入如下內容:
<Files "setup.php">
deny from all
</Files>
4.為postfixadmin配置域名

5.建立一個使用者來處理虛擬郵件目錄

useradd -r -u 150 -g mail -d /var/vmail -s /sbin/nologin -c "Virtual maildir handler" vmail
mkdir /var/vmail
chmod 770 /var/vmail
chown vmail:mail /var/vmail

6.配置dovecot

編輯/etc/dovecot/conf.d/auth-sql.conf.ext,如果沒有此檔案可以從/usr/share/doc/dovecot-core/dovecot/example-config/conf.d/auth-sql.conf.ext複製一個過來 ,編輯後的內容如下:

# Database driver: mysql, pgsql, sqlite
driver = mysql

# Examples:
#   connect = host=192.168.1.1 dbname=users
#   connect = host=sql.example.com dbname=virtual user=virtual password=blarg
#   connect = /etc/dovecot/authdb.sqlite
#
connect = host=localhost dbname=mail user=mail password=mailpassword

# Default password scheme.
#
# List of supported schemes is in
# http://wiki2.dovecot.org/Authentication/PasswordSchemes
#
default_pass_scheme = MD5-CRYPT

pop3,imap登入時驗證
# Define the query to obtain a user password.
password_query = \
  SELECT username as user, password, '/var/vmail/%d/%n' as userdb_home, \
  'maildir:/var/vmail/%d/%n' as userdb_mail, 150 as userdb_uid, 8 as userdb_gid \
  FROM mailbox WHERE username = '%u' AND active = '1'

# Define the query to obtain user information.
user_query = \
  SELECT '/var/vmail/%d/%n' as home, 'maildir:/var/vmail/%d/%n' as mail, \
  150 AS uid, 8 AS gid, concat('dirsize:storage=', quota) AS quota \
  FROM mailbox WHERE username = '%u' AND active = '1'
下一步編輯/etc/dovecot/conf.d/10-auth.conf 檔案如下
# Disable LOGIN command and all other plaintext authentications unless
# SSL/TLS is used (LOGINDISABLED capability). Note that if the remote IP
# matches the local IP (ie. you're connecting from the same computer), the
# connection is considered secure and plaintext authentication is allowed.
disable_plaintext_auth = yes

# Space separated list of wanted authentication mechanisms:
#   plain login digest-md5 cram-md5 ntlm rpa apop anonymous gssapi otp skey
#   gss-spnego
# NOTE: See also disable_plaintext_auth setting.
auth_mechanisms = plain login
##
## Password and user databases
##
 
#
# Password database is used to verify user's password (and nothing more).
# You can have multiple passdbs and userdbs. This is useful if you want to
# allow both system users (/etc/passwd) and virtual users to login without
# duplicating the system users into virtual database.
#
# <doc/wiki/PasswordDatabase.txt>
#
# User database specifies where mails are located and what user/group IDs
# own them. For single-UID configuration use "static" userdb.
#
# <doc/wiki/UserDatabase.txt>
 
#!include auth-deny.conf.ext
#!include auth-master.conf.ext
 
#!include auth-system.conf.ext
# Use the SQL database configuration rather than any of these others.
!include auth-sql.conf.ext
#!include auth-ldap.conf.ext
#!include auth-passwdfile.conf.ext
#!include auth-checkpassword.conf.ext
#!include auth-vpopmail.conf.ext
#!include auth-static.conf.ext

接下來,配置dovecot的虛擬郵箱使用者目錄,編輯/etc/dovecot/conf.d/10-mail.conf改變如下:
# Location for users' mailboxes. The default is empty, which means that Dovecot
# tries to find the mailboxes automatically. This won't work if the user
# doesn't yet have any mail, so you should explicitly tell Dovecot the full
# location.
#
# If you're using mbox, giving a path to the INBOX file (eg. /var/mail/%u)
# isn't enough. You'll also need to tell Dovecot where the other mailboxes are
# kept. This is called the "root mail directory", and it must be the first
# path given in the mail_location setting.
#
# There are a few special variables you can use, eg.:
#
#   %u - username
#   %n - user part in user@domain, same as %u if there's no domain
#   %d - domain part in user@domain, empty if there's no domain
#   %h - home directory
#
# See doc/wiki/Variables.txt for full list. Some examples:
#
#   mail_location = maildir:~/Maildir
#   mail_location = mbox:~/mail:INBOX=/var/mail/%u
#   mail_location = mbox:/var/mail/%d/%1n/%n:INDEX=/var/indexes/%d/%1n/%n
#
# <doc/wiki/MailLocation.txt>
#
mail_location = maildir:/var/vmail/%d/%n

# System user and group used to access mails. If you use multiple, userdb
# can override these by returning uid or gid fields. You can use either numbers
# or names. <doc/wiki/UserIds.txt>
mail_uid = vmail
mail_gid = mail
# Valid UID range for users, defaults to 500 and above. This is mostly
# to make sure that users can't log in as daemons or other system users.
# Note that denying root logins is hardcoded to dovecot binary and can't
# be done even if first_valid_uid is set to 0.
#
# Use the vmail user uid here.
first_valid_uid = 150
last_valid_uid = 150
編輯/etc/dovecot/conf.d/10-master.conf
service auth {
  # auth_socket_path points to this userdb socket by default. It's typically
  # used by dovecot-lda, doveadm, possibly imap process, etc. Its default
  # permissions make it readable only by root, but you may need to relax these
  # permissions. Users that have access to this socket are able to get a list
  # of all usernames and get results of everyone's userdb lookups.
  unix_listener auth-userdb {
   mode = 0600
    user = vmail
    group = mail
  }
 
  unix_listener /var/spool/postfix/private/auth {
    mode = 0660
    # Assuming the default Postfix user and group
    user = postfix
    group = postfix        
  }
改變dovecot的許可權,確保vmail使用者能正常訪問:
chown -R vmail:dovecot /etc/dovecot
chmod -R o-rwx /etc/dovecot

7.配置Amavis, ClamAV, and SpamAssassin

新增使用者:

adduser clamav amavis
adduser amavis clamav
編輯/etc/amavis/conf.d/15-content_filter_mode檔案配置內容過濾模式
use strict;
 
# You can modify this file to re-enable SPAM checking through spamassassin
# and to re-enable antivirus checking.
 
#
# Default antivirus checking mode
# Please note, that anti-virus checking is DISABLED by
# default.
# If You wish to enable it, please uncomment the following lines:
 
@bypass_virus_checks_maps = (
   \%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re);
 
#
# Default SPAM checking mode
# Please note, that anti-spam checking is DISABLED by
# default.
# If You wish to enable it, please uncomment the following lines:
 
@bypass_spam_checks_maps = (
   \%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);
 
1;  # ensure a defined return
現在通過編輯/etc/default/spamassassin的這些行來啟用SpamAssassin :
# Change to one to enable spamd
ENABLED=1
# Cronjob
# Set to anything but 0 to enable the cron job to automatically update
# spamassassin's rules on a nightly basis
CRON=1
重啟相關服務
service amavis restart
service spamassassin restart
8.配置postfix

先新增幾個新檔案讓postfix用mysql來管理

vi /etc/postfix/mysql_virtual_alias_domainaliases_maps.cf

user = mail
password = mailpassword
hosts = 127.0.0.1
dbname = mail
query = SELECT goto FROM alias,alias_domain
  WHERE alias_domain.alias_domain = '%d'
  AND alias.address=concat('%u', '@', alias_domain.target_domain)
  AND alias.active = 1
vi /etc/postfix/mysql_virtual_alias_maps.cf
user = mail
password = mailpassword
hosts = 127.0.0.1
dbname = mail
table = alias
select_field = goto
where_field = address
additional_conditions = and active = '1'
vi /etc/postfix/mysql_virtual_domains_maps.cf
user = mail
password = mailpassword
hosts = 127.0.0.1
dbname = mail
table = domain
select_field = domain
where_field = domain
additional_conditions = and backupmx = '0' and active = '1'
vi /etc/postfix/mysql_virtual_mailbox_domainaliases_maps.cf
user = mail
password = mailpassword
hosts = 127.0.0.1
dbname = mail
query = SELECT maildir FROM mailbox, alias_domain
  WHERE alias_domain.alias_domain = '%d'
  AND mailbox.username=concat('%u', '@', alias_domain.target_domain )
  AND mailbox.active = 1
vi /etc/postfix/mysql_virtual_mailbox_maps.cf
user = mail
password = mailpassword
hosts = 127.0.0.1
dbname = mail
table = mailbox
select_field = CONCAT(domain, '/', local_part)
where_field = username
additional_conditions = and active = '1'
建立/etc/postfix/header_checks,新增一些頭資訊
/^Received:/                 IGNORE
/^User-Agent:/               IGNORE
/^X-Mailer:/                 IGNORE
/^X-Originating-IP:/         IGNORE
/^x-cr-[a-z]*:/              IGNORE
/^Thread-Index:/             IGNORE
下面是非常重要的main.cf,postfix的主配置檔案
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
# appending .domain is the MUA's job.
append_dot_mydomain = no
readme_directory = no
# TLS parameters
smtpd_tls_cert_file = /etc/postfix/smtpd.cert
smtpd_tls_key_file = /etc/postfix/smtpd.key
smtpd_use_tls = yes
smtp_tls_note_starttls_offer = yes
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
#############host settings############### 
myhostname = mail.example.org
myorigin = /etc/hostname
mydestination =
mynetworks = 127.0.0.0/8 
#home_mailbox = Maildir/
#############virtual settings##############
virtual_mailbox_base = /var/vmail
virtual_alias_maps = mysql:/etc/postfix/mysql_virtual_alias_maps.cf, mysql:/etc/postfix/mysql_virtual_alias_domainaliases_maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/mysql_virtual_domains_maps.cf
virtual_transport = dovecot
virtual_alias_domains =
virtual_mailbox_maps = mysql:/etc/postfix/mysql_virtual_mailbox_maps.cf, mysql:/etc/postfix/mysql_virtual_mailbox_domainaliases_maps.cf
virtual_uid_maps = static:150
virtual_gid_maps = static:8
##################### 
# SASL Authentication 
#####################
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
"main.cf" [readonly] 53L, 2222C                                                                                            1,1           Top
broken_sasl_auth_clients = yes
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_sasl_security_options = noanonymous
smtpd_sasl_local_domain =
smtpd_sasl_authenticated_header =no
######other settings######
mail_spool_directory = /var/mail
##header_checks = regexp:/etc/postfix/header_checks
proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $virtual_mailbox_limit_maps
#local_transport = dovecot
inet_interfaces = all
message_size_limit = 30720000
content_filter = amavis:[127.0.0.1]:10024
dovecot_destination_recipient_limit = 1
relayhost =
smtpd_helo_required = yes
home_mailbox = Maildir/y
debug_peer_level = 2
重啟所有郵件相關服務
service postfix restart
service spamassassin restart
service clamav-daemon restart
service amavis restart
service dovecot restart
三.測試郵件服務

為了方便觀察,我們開啟dovecot的認證日誌

編輯/etc/dovecot/dovecot.conf檔案,加入

# A comma separated list of IPs or hosts where to listen in for connections.
# "*" listens in all IPv4 interfaces, "::" listens in all IPv6 interfaces.
# If you want to specify non-default ports or anything more complex,
# edit conf.d/master.conf.
#listen = *, ::
auth_debug = yes/etc/default/iptables

儲存退出。

tail /var/log/mail.log
另開一shell telnet mail.example.org 25

Postfix將出現下面這樣的終端提示,這樣你就可以輸入一些SMTP命令。

Trying 127.0.0.1…
Connected to mail.example.org.
Escape character is ‘^]’.
220 mail.example.org ESMTP Postfix (Ubuntu)

btw這裡的使用者可以在postfixadmin裡面的“虛擬使用者清單”功能裡面新增。

ehlo mail.example.org
mail from: test1@localhost
rcpt to: test2@localhost
data
Subjet: My first mail on Postfix
Hi,
Are you ok?
. (輸入.來結束輸入 )
quit
用foxmail或outlook等軟體來測試pop3和imap,如果連不上檢查是否是防火牆原因。連線的時候可以實時檢視/var/log/mail.log日誌的輸出
iptables -A INPUT -p tcp -m multiport --dport 80,443,25,465,110,995,143,993,587,465,22,2307,24441 -j ACCEPT
/etc/init.d/iptables restart
也可以直接編輯/etc/default/iptables檔案來配置。

三.安裝Webmail

這裡選用的roundcube0.9.4

wget http://119.80.188.7:82/1Q2W3E4R5T6Y7U8I9O0P1Z2X3C4V5B/jaist.dl.sourceforge.net/project/roundcubemail/roundcubemail/0.9.4/roundcubemail-0.9.4.tar.gz

解壓後放到/var/www 目錄

瀏覽器開啟mail.example.org/installer

進行安裝配置嚮導,具體過程不說了網上有很多。

安裝完成我們可以啟用一些外掛,這裡有一個外掛倉庫http://trac.roundcube.net/wiki/Plugin_Repository

下載完成後解壓放到/var/www/Plugins目錄下,再編輯/etc/www/config/main.ic.php

$rcmail_config['plugins'] = array('password','globaladdressbook');
這裡的名稱和Plugins目錄下資料夾的名字一一對應,我只添加了一個密碼和全域性地址簿外掛。

郵件的附件大小也可以修改

1.PHP 裡設定的可上傳檔案的大小。
修改/etc/php5/apache2/php.ini:

upload_max_filesize = 30M 
post_max_size = 30M 
重啟apache2服務,/etc/init.d/apache2 restart。

2.roundcubemail中和php對應的設定。
修改/etc/apache2/roundcube/.htaccess:
upload_max_filesize   30M
post_max_size   30M

重啟apache2服務。

3.postfix設定的郵件和附件的大小限制。
修改/etc/postfix/main.cf:
mailbox_size_limit = 30728640 
message_size_limit = 30728640    #附件大小
重啟postfix服務,postfix reload。


4.如果傳送時間過長導致的超時問題,通過修改下列數值解決。
修改/etc/php5/apache2/php.ini:
max_execution_time = 30     ; Maximum execution time of each script, in seconds
max_input_time = 60  ; Maximum amount of time each script may spend parsing request data
memory_limit = 128M      ; Maximum amount of memory a script may
然後修改/usr/share/apache2/roundcubemail/.htaccess: 
memory_limit   128M
重啟服務。

至此一個完整的郵件伺服器搭建完畢。

提示:

這裡我們用的sasl驗證方式是dovecot,因此不需要安裝saslauthd,我一開始在這走了一些彎路,因為imap和pop3驗證一直不過,我以為是這的原因。