WP Mail SMTPでGmailを接続し、Google APIのOAuthと接続が完了しているにも関わらずエラーが発生してメールを送信できないことがあります。
この場合の対処法についてまとめています。
エラーの内容
WP Mail SMTPでテストメールなどを送信したときに以下のようなメッセージが表示されます。
テストメールの送信中に問題が発生しました。
問題が検出されました。
これは、テスト用メールを送信できなかったことを意味します。
通常、このエラーは次のいずれかの理由で返されます:
プラグインの設定が正しくありません (間違ったSMTP設定、メーラー設定が無効など)。
お使いの Web サーバーは接続をブロックしているようです。
ホストが接続を拒否しています。

具体的には次のようなエラーメッセージが表示されます。
Mailer: Google / Gmail
{
"error": {
"code": 403,
"message": "Gmail API has not been used in project 194064043210 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=194064050136 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
"errors": [
{
"message": "Gmail API has not been used in project 194064043210 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=194064050136 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
"domain": "usageLimits",
"reason": "accessNotConfigured",
"extendedHelp": "https://console.developers.google.com"
}
],
"status": "PERMISSION_DENIED",
"details": [
{
"@type": "type.googleapis.com/google.rpc.Help",
"links": [
{
"description": "Google developers console API activation",
"url": "https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project194064043210"
}
]
},
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "SERVICE_DISABLED",
"domain": "googleapis.com",
"metadata": {
"service": "gmail.googleapis.com",
"consumer": "projects/194064043210"
}
}
]
}
}
簡単にまとめると、API接続しようとしたときに「PERMISSION_DENIED(承認拒否)」。
「Google developers console API activation(GoogleデベロッパーコンソールでAPIを有効化)」APIを有効化してください。という内容です。
対処法:Gmail APIを有効にする
この問題を解決する方法はとても簡単です。Google Cloudにログインして「Gmail API」を有効にします。
メニューから「APIとサービス」→「有効なAPIとサービス」に進みます。

デフォルトでは「使用できる API はまだありません。開始するには、「API とサービスを有効にする」をクリックするか、API ライブラリに移動します。」と記載されています。
(You don’t have any APIs available to use yet. To get started, click “Enable APIs and services” or go to the API library」)
なので、上部にある「+ENABLE APIS AND SERVICES」をクリックします。

「Gmail API」というのがあるので、これを選択します。

クリックすると「Gmail API」を「有効にする」というボタンが出てくるので、これをクリックします。

ステータスが「有効」になります。

以上で設定は完了です。
API有効化への別のアクセス方法
上記ではGoogle ConsoleにログインしてからAPIを有効化しましたが、リンク経由でAPIを有効化することもできます。
WP Mail SMTPで表示されたエラーの中にそのリンクが入っています。
"description": "Google developers console API activation",
"url": "https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=194064043210"
このリンクを検索バーに入れると、Gmail API有効化の画面に遷移します。

「有効にする」を選択すれば、Gmail APIを有効化することができます。
WP Mail SMTPの確認
Gmail APIの有効化が完了したので、WP Mail SMTPからテストメールを送信します。

すると「成功しました」と表示され、無事メールを送信することができます。

もちろんGmailにもきちんとWP Mail SMTPからのテストメールが届いています。

以上ですべて完了です。
お疲れさまでした^^