配置 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