Postfix
之前介紹過使用 Linux
自帶的 mail
來發送郵件 Linux使用mailx通過第三方SMTP發送郵件,帶附件操作。
最近發現 Ubuntu 18.04
中移除了 heirloom-mail
1。
Postfix is the default Mail Transfer Agent (MTA) in Ubuntu. It attempts to be fast and secure, with flexibility in administration. It is compatible with the MTA sendmail. This section will explain installation, including how to configure SMTP for secure communications.
可見 Postfix
是官方的郵件MTA,工具本身也很好用。因此將此作爲新的郵件發送工具吧。
如果機器上沒有這個軟件的話,安裝即可。
sudo apt-get update
sudo apt-get install libsasl2-modules
sudo apt install postfix
安裝過程中會彈出配置界面,選擇 Internet Site
。
System mail name 可以隨便填一個,可以填你郵箱名後綴,如 163.com
。
配置2
安裝完成後,其配置文件爲 /etc/postfix/main.cf
打開配置文件,增加一個字段,myhostname = [email protected]
。
自然地,需要用戶名和密碼,SMTP服務器需要這個來鑑權。
- 添加用戶名密碼
sudo vim /etc/postfix/sasl_passwd
// 格式如下,注意以下的 [] 都不需要在文本中體現
[smtp.example.com] username:password
// 如果需要指定端口號,例如 587
[smtp.example.com]:587 username:password
- 創建上述用戶名密碼的
hash data base
文件
// 創建 hash 文件
sudo postmap /etc/postfix/sasl_passwd
操作成功的話,此時會在目錄下出現 sasl_passwd.db
。
- 更改文件權限
// 安全起見,更改文件權限
sudo chown root:root /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
sudo chmod 0600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
使用外部 SMTP 代理進行發送
使用外部代理髮送郵件的一個益處是避免被當成垃圾郵件。外部郵件發送代理很多,比如 163, foxmail, gmail
。
-
配置外部 SMTP 代理,
sudo vim /etc/postfix/main.cf
繼續編輯配置文件,指定字段內容relayhost = [smtp.example.com]:587
。注意如果sasl_passwd
文件裏指定了端口號,那麼這裏需要保持一致。 -
在文件尾部增加鑑權操作
# enable SASL authentication
smtp_sasl_auth_enable = yes
# disallow methods that allow anonymous authentication.
smtp_sasl_security_options = noanonymous
# where to find sasl_passwd
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
# Enable STARTTLS encryption
smtp_use_tls = yes
# where to find CA certificates
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt
- 重啓 Postfix 服務
sudo service postfix restart
or
sudo systemctl restart postfix.service
測試 SMTP 服務
我們發一份郵件給自己來測試一下配置的正確性,使用 mail
命令來發送。sudo apt-get install mailutils
echo "Hello, this is George, how are you?" | mail -s "From Ubuntu 18.04" -a "From: [email protected]" [email protected] -A your_attachment_file
可以看到,發送成功了。
問題定位
發送的日誌,錯誤日誌可以在 /var/log/mail.log
以及 /var/log/mail.err
中查看。