設定 postfix 與 gmail 從 Linux 命令列發送電子郵件
一個關於如何設定 postfix 和 gmail smtp 伺服器以直接從 linux 命令列發送電子郵件的工作範例,並在帶有 ubuntu precise 32 的 vagrant vm 上進行測試。
Install necessary packages
# install dependencies
$ sudo apt-get install postfix mailutils libsasl2-2 ca-certificates libsasl2-modules
Open postfix config file /etc/postfix/main.cf and add below content
relayhost = [smtp.gmail.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_tls_CAfile = /etc/postfix/cacert.pem
smtp_use_tls = yes
Open /etc/postfix/sasl_passwd and add below line
[smtp.gmail.com]:587 USERNAME@gmail.com:PASSWORD
=> USERNAME: your gmail username
=> PASSWORD: your gmail password or app password if 2-factor authentication is enabled
Set permission and update postfix config to use the sasl_passwd file
# set permission
$ sudo chmod 400 /etc/postfix/sasl_passwd
$ sudo postmap /etc/postfix/sasl_passwd
Validate certificate
$ cat /etc/ssl/certs/Thawte_Premium_Server_CA.pem | sudo tee -a /etc/postfix/cacert.pem
Start postfix and reload the config
sudo /etc/init.d/postfix start
sudo /etc/init.d/postfix reload
or
sudo /etc/init.d/postfix restart
Finally send a test email
$ echo "Test mail from postfix" | mail -s "Test Postfix" username@anothermail.com
=> The echo message is the mail body
=> The -s message is the subject
=> The mail address at the end is the recipient