ubuntu使用Postfix外部SMTP代理发送邮件
需求
ubuntu使用指令发送邮件。普通的mail指令通常被识别为垃圾邮件,且由于ubuntu主机邮箱地址不正规,执行指令几次后常被鉴定为风险地址从而禁止。对此,使用外部SMTP代理,驱动正规地址(例如qq邮箱)向指定邮箱发送。
安装软件
# 安装软件,安装界面中保持默认配置即可
sudo apt install mailutils
配置用于发送邮件的SMTP服务器
新建sudo vim /etc/postfix/sasl_passwd
[smtp.qq.com]:587 qqcode@qq.com:password
其中password是QQ邮箱授权码。进入“QQ邮箱 -> 账号与安全 -> 安全设置 -> POP3/IMAP/SMTP/Exchange/CardDAV 服务”。
接着执行sudo postmap /etc/postfix/sasl_passwd
,成功的话会生成sasl_passwd.db
。
配置主机地址映射
当使用QQ作为SMTP服务器时,要求ubuntu主机邮件名称和上一节授权的QQ邮箱相同(gmail则不用),如下:
新建sudo vim /etc/postfix/generic
user@user qqcode@qq.com
其中user@user是我的主机自动生成的地址。
然后执行sudo postmap /etc/postfix/generic
,生成generic.db
。
修改权限
sudo chown root:root /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db /etc/postfix/generic /etc/postfix/generic.db
sudo chmod 0600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db /etc/postfix/generic /etc/postfix/generic.db
Postfix配置
修改sudo vim /etc/postfix/main.cf
,添加:
relayhost = [smtp.qq.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
smtp_generic_maps = hash:/etc/postfix/generic
重启 Postfix 服务:sudo service postfix restart
测试
echo "任务完成,结果已保存" | mail -s "你好啊" qqcode@qq.com
如果成功,则可以收到自己给自己发送的qq邮件。
可以查看/var/log/mail.log
发现错误。