在Debian 8 系统里为 postfix 配置外部smtp服务器发邮件
有不少网友在使用阿里云ECS实例时,发现无法发出邮件,因为新近创建的ECS实例默认禁止连接外网TCP 25端口,避免滥发邮件。
环境:Debian 8,postfix 2.11,使用免费的阿里云云邮账户发信
过程:
- apt-get update # 先更新软件库
- hostname swas.anqun.org # 设置主机名
- apt-get install libsasl2-modules postfix # 安装 postfix 及相关组件
- 在配置 postfix 里,选择 Internet Site 类型,填写完整主机名 swas.anqun.org
- 安装好 postfix 后,在配置文件 /etc/postfix/main.cf 里确认 myhostname 的值是否与主机名相符
- apt-get install stunnel # 安装stunnel,目的是让postfix支持连接 smtp.aliyun.com:465
创建 /etc/stunnel/stunnel.conf 配置文件,内容如下,监听本地11125端口,连接 smtp.aliyun.com:465
[smtp-tls-wrapper] accept = 11125 client = yes connect = smtp.aliyun.com:465
- 启动 stunnel 后,可查看到本地有 11125 端口使用情况
创建或修改 /etc/postfix/sasl/sasl_passwd 文件,写上相应的服务器地址、端口和登录名密码,如下例:
[localhost]:11125 anqunhe@aliyun.com:password
- postmap /etc/postfix/sasl/sasl_passwd # 生成 hash 文件
- chmod 600 /etc/postfix/sasl/* # 为了保护smtp的登录信息,需要修改上边两个文件为root用户只读写
修改 /etc/postfix/main.cf 文件,修改 relayhost = [localhost]:11125 , 添加SMTP验证信息:
# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for # information on enabling SSL in the smtp client. smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination myhostname = swas.anqun.org alias_maps = hash:/etc/aliases alias_database = hash:/etc/aliases myorigin = /etc/mailname mydestination = swas.anqun.org, localhost, localhost.localdomain, localhost # relayhost = relayhost = [localhost]:11125 mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 mailbox_command = procmail -a "$EXTENSION" mailbox_size_limit = 0 recipient_delimiter = + inet_interfaces = all #### SMTP # Enable SASL authentication smtp_sasl_auth_enable = yes # Disallow methods that allow anonymous authentication smtp_sasl_security_options = noanonymous # Location of sasl_passwd smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd # Enable STARTTLS encryption # smtp_tls_security_level = encrypt # Location of CA certificates smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt smtp_generic_maps = hash:/etc/postfix/generic
因为多数免费邮箱限定发信人是登录名(如anqunhe@aliyun.com),所以在 /etc/postfix/generic 文件里填写可能发信的地址,如:www-data,wordpress
www-data anqunhe@aliyun.com wordpress anqunhe@aliyun.com
- postmap /etc/postfix/generic # 生成或更新postfix查询表
- service postfix restart # 重启postfix后,从Shell和从wordpress程序测试,发信成功
参考:
- https://core.trac.wordpress.org/ticket/25239
- https://www.codeforest.net/debugging-wp-mail-like-a-boss-debugger
- https://codeseekah.com/2013/11/01/correct-sender-for-wordpress-mail-routed-via-postfix/
- https://stackoverflow.com/questions/14370224/change-outgoing-mail-address-from-rootservername-rackspace-sendgrid-postfix
- http://www.postfix.org/TLS_README.html
- https://ubuntuforums.org/archive/index.php/t-1370982.html
- https://mailhelp.aliyun.com/freemail/detail.vm?knoId=5869705
- https://linode.com/docs/email/postfix/configure-postfix-to-send-mail-using-gmail-and-google-apps-on-debian-or-ubuntu/