LoginSignup
49
65

More than 5 years have passed since last update.

mailコマンドでgmailを送る

Last updated at Posted at 2017-04-05

やりたいこと

  • Linux(CentOS)のmailコマンドでgmailにメールを送りたい。

環境

  • CentOS7.3(postfix稼働済)

mailコマンドのインストールと送信テスト

インストール

まず、CentOS7.3には標準でmailコマンドが入っていないので入れます。実際はmailx。postfixは稼働しているようです。

sudo yum install mailx

送信テスト

とりあえず、送信してみます。

echo "test mail!" | mail -s "test" xxxxx@gmail.com

残念ながらとどきません。postfixのログを見てみます。

/var/log/maillog
.
Apr  5 17:39:19 localhost postfix/smtp[26381]: connect to gmail-smtp-in.l.google.com[64.233.189.27]:25: Connection refused
.

どうやらgmailのsmtpに到達できていないようです。

Gmailの設定

数年前にGmailのセキュリティーが強化され、普通のメアド(ID)+パスワードではgmailクライアント以外からはメールの送信ができなくなっています。gmailクライアント以外から送信する場合は専用のパスワードを取得する必要があるので取得します。

アプリパスワードの設定

[アカウント] -> [ログインとセキュリティ ] -> [アプリパスワード]にて、パスワードを発行します。

私は2段階認証をONにしているので上記の手順なのかもしれません。2段階認証を設定してない場合は別の設定かもしれません。

Postfixの設定

アプリパスワードが取得できたので、Postfixの設定を行います。

必要コンポーネントのインストール

まずSASL認証をするために必要なコンポーネントをインストールします。

sudo yum install cyrus-sasl-plain

main.cfの編集

mail.cfを編集し必要な記述を行います。gmailのアカウントは外部ファイルで設定します。

/etc/postfix/main.cf
## add for gmail
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_sasl_tls_security_options = noanonymous
smtp_sasl_mechanism_filter = plain
smtp_use_tls = yes

パスワードファイルの準備

gmailのアカウントを下記のフォーマットで記述し、ハッシュ化します。

/etc/postfix/sasl_passwd
[smtp.gmail.com]:587 xxxxx@gmail.com:PASSWORD

xxxxx@gmail.comおよびPASSWORDは各自の環境で。

ハッシュ化します。

sudo postmap /etc/postfix/sasl_passwd
sudo chmod 600 /etc/postfix/sasl_passwd

実際利用されるのはsasl_passwd.dbファイルのようなのでsasl_passwdファイルは削除してもいいようです。

postfix再起動

設定を反映させるためにpostfixを再起動します。

sudo systemctl reload postfix.service

送信テスト

再度送信してみます。

echo "test" | mail -s "test1" xxxxx@gmail.com

いちおうmaillogを確認するとstatus=sentとなっています。

.
 relay=smtp.gmail.com[64.233.189.108]:587, delay=2.4, delays=0.02/0.01/1.2/1.2, dsn=2.0.0, status=sent (250 2.0.0 OK 1491422360 v9sm39011968pfg.133 - gsmtp)
.

うまくいったようです。

49
65
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
65