因为自建Email Server发送的情况下,经常会被一些邮箱服务识别成垃圾邮件从而导致用户无法收到信息,在Linux中我就使用了 Postfix 然后调用外部 SMTP 服务进行发件,这样有效解决了上面提到的经常会被垃圾邮件的问题,同时觉得使用外部发送邮件的方式能够解决集群的报警并及时处理的问题。

在此我选择使用腾讯企业邮箱作为发件SMTP,做下记录。

安装配置

先是安装 Postfix 软件

1
yum install postfix

我们需要对以下的配置文件进行调整

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
### Domain 设置
mydomain = Demo.com
myorigin = $mydomain
myhostname = $mydomain
mydestination = $mydomain

### alias设定
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases

### SMTP SETTINGs
relayhost = [smtp.exmail.qq.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_security_level = encrypt
smtp_use_tls = yes
smtp_sasl_security_options = noanonymous

### postfix version 2.2 or up
smtp_generic_maps = hash:/etc/postfix/generic

使用 postconf -n 可以查看当前的配置,下面提供一份示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5
html_directory = no
inet_interfaces = all
inet_protocols = all
mail_owner = postfix
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination = $myhostname, localhost.$mydomain, localhost
mydomain = Demo.com
myhostname = $mydomain
myorigin = $mydomain
newaliases_path = /usr/bin/newaliases.postfix
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix-2.10.1/README_FILES
relayhost = [smtp.exmail.qq.com]:587
sample_directory = /usr/share/doc/postfix-2.10.1/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
smtp_generic_maps = hash:/etc/postfix/generic
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_security_level = encrypt
smtp_use_tls = yes
unknown_local_recipient_reject_code = 550

然后在 /etc/postfix/sasl_passwd 里边写入邮箱用户名和密码:

1
[smtp.exmail.qq.com]:587 noreply@Demo.com:[PASSWORD]

/etc/postfix/generic 里配置信封上的发件人(MAIL FROM 命令)的地址重写,不然会出现认证错误:

1
@Demo.com noreply@Demo.com

/etc/aliases 中添加 root 邮件转发,这样发送到root的邮件,都会转发到Toplay@Demo.com

1
2
postmaster:     root
root: Toplay@Demo.com ##添加这个

之后要使用newaliases命令来重新生成 aliases 库文件,使更改生效。

最后生成 hash 数据库,并更改文件权限,每次修改这些文件:

1
2
3
postmap /etc/postfix/sasl_passwd
postmap /etc/postfix/generic
chmod 600 /etc/postfix/sasl_passwd*

重启或重新加载 Postfix:

1
service postfix restart

发件测试

1
echo 'This is a mail' | mail -s 'This is a mail' xxxxx@163.com

调试

过程中可能并不会那么的一帆风顺,在下面提供了一些简单的调试方法仅供参考:

首先看日志文件:

1
tail -f /var/log/maillog

查看邮件队列:

1
mailq