Linux のコマンドラインからメールを送信するために Gmail で postfix を設定する

Linux コマンドラインから直接メールを送信するために、Gmail SMTP サーバーで Postfix を構成する方法の実例です。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

linux