clock-up-blog

junk-junction

PHPMailer エラー「SMTP Error: Could not authenticate.」への対処

SMTP Error: Could not authenticate.」が出る原因はいくつかあると思いますが、その一例への対処。

先にまとめ

  • SMTP Error: Could not authenticate.」のログが出る時点で PHPMailer が古いので新しくすること
  • SMTPDebug をセットしてエラー詳細を見ること
  • GMail のパスワード認証は安全性が低いため、それを利用したい場合はあらかじめアクセス許可の設定をしておくこと

利用コード

<?php
require("phpmailer/class.phpmailer.php");
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->Host = 'ssl://smtp.gmail.com:465';
$mailer->SMTPAuth = true;
$mailer->Username = 'from@xxx.yyy';
$mailer->Password = 'xxxxxx';
$mailer->CharSet  = 'iso-2022-jp';
$mailer->Encoding = '7bit';
$mailer->From     = 'from@xxx.yyy';
$mailer->FromName = "from";
$mailer->Subject  = "Hello";
$mailer->Body     = "Hello World";
$mailer->AddAddress('to@xxx.yyy');
$mailer->Send();

結果

$ php test.php
SMTP Error: Could not authenticate.

そもそもこのエラーメッセージのフォーマット自体が古いので、まずは PHPMailer を最新にする。
2015/10/25 時点の master だと、require の仕方も変わっているので注意。

PHPMailer 差し替え

$ rm -rf phpmailer
$ git clone git@github.com:PHPMailer/PHPMailer.git phpmailer

利用コード変更

- require("phpmailer/class.phpmailer.php");
+ require("phpmailer/PHPMailerAutoload.php");

PHPMailer 差し替え後の実行結果

$ php test.php
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

最新の PHPMailer だと親切にもエラーログ内にサポートページの URL が表示される。
ページ内の情報によると「SMTPDebug を 2 にして詳細を見ろ(意訳)」とある。

詳細ログを出す

<?php
require("phpmailer/class.phpmailer.php");
$mailer = new PHPMailer();
$mailer->SMTPDebug = 2; // ←これを追加

実行結果

SMTPDebug をセットしたことでログに流れる情報が増える。

$ php test.php
2015-10-25 09:03:45     SERVER -> CLIENT: 220 smtp.gmail.com ESMTP xxxxxxxx.26 - gsmtp
2015-10-25 09:03:45     CLIENT -> SERVER: EHLO myserver
2015-10-25 09:03:45     SERVER -> CLIENT: 250-smtp.gmail.com at your service, [xxxx]
…
2015-10-25 09:03:46     SMTP ERROR: Password command failed: .....
                                  xxxxxx  Learn more at
                                  xxxxxx  https://support.google.com/mail/answer/78754 xxxxxx - gsmtp
2015-10-25 09:03:46     SMTP Error: Could not authenticate.
…
2015-10-25 09:03:46     SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

ログ内に「SMTP ERROR: Password command failed」とある。
さらに Google のサポートページ の URL が表示されている。

そこを見ると、
「メールアプリが最新のセキュリティ規格をサポートしていない可能性があります。
アカウントに対して安全性の低いアプリによるアクセスを許可する方法をご覧ください。」
とある。

パスワード認証は安全性が低いため、アクセスがブロックされていた模様。

安全性の低いアプリによるアクセスを許可する

以下にアクセスする。
https://www.google.com/settings/security/lesssecureapps

f:id:kobake:20151025190501p:plain:w500

「安全性の低いアプリのアクセス」の「オンにする」を選択。反映には 2~3分くらいかかるみたいなので注意。

アクセス許可後のスクリプト実行

$ php test.php

エラーは表示されなくなった。(メールも届くようになった)