2026年8月11日
2026年8月11日
WP Mail SMTPのエラーを解決する方法
はじめに
WP Mail SMTPを設定したがWordPressからメールが一切届かない・GmailのSMTP設定で「535 Authentication Failed」エラーが出る・SendGridやMailgunのAPIキーを入力したが送信テストに失敗する・PHPのmail()関数は動くがWP Mail SMTPを有効化すると届かなくなるといった問題は、SMTP認証設定・セキュリティ設定・サーバーのポート制限が原因です。
症状・原因
- WP Mail SMTPのテスト送信ボタンを押すと「メールの送信に失敗しました」と表示される
- Gmailに接続しようとすると「535-5.7.8 Username and Password not accepted」エラーが出る
- SendGridのAPIキーを設定したが送信テストで「401 Unauthorized」が返ってくる
- 問い合わせフォームからのメールは届くが、WordPressのパスワードリセットメールだけ届かない
解決手順
ステップ1:WP Mail SMTPの状態を確認する
# WP Mail SMTPの設定確認
wp eval "
if (defined('WPMS_PLUGIN_VER')) {
echo 'WP Mail SMTP version: ' . WPMS_PLUGIN_VER . PHP_EOL;
}
// 現在のメーラー設定を確認
\$options = get_option('wp_mail_smtp', []);
echo 'Mailer: ' . (\$options['mail']['mailer'] ?? 'php') . PHP_EOL;
echo 'From email: ' . (\$options['mail']['from_email'] ?? 'not set') . PHP_EOL;
echo 'From name: ' . (\$options['mail']['from_name'] ?? 'not set') . PHP_EOL;
echo 'Reply-to email: '. (\$options['mail']['reply_to_email'] ?? 'not set') . PHP_EOL;
// SMTPマネージャー設定(smtpを使用している場合)
if ((\$options['mail']['mailer'] ?? '') === 'smtp') {
echo 'SMTP host: ' . (\$options['smtp']['host'] ?? 'not set') . PHP_EOL;
echo 'SMTP port: ' . (\$options['smtp']['port'] ?? 'not set') . PHP_EOL;
echo 'SMTP encryption: ' . (\$options['smtp']['encryption'] ?? 'none') . PHP_EOL;
echo 'SMTP auth: ' . ((\$options['smtp']['auth'] ?? false) ? 'yes' : 'no') . PHP_EOL;
echo 'SMTP user: ' . (\$options['smtp']['user'] ?? 'not set') . PHP_EOL;
}
// 送信ログ確認(Pro版)
global \$wpdb;
\$logs = \$wpdb->get_results(
'SELECT * FROM ' . \$wpdb->prefix . 'wpms_debug_events ORDER BY created_at DESC LIMIT 5'
);
echo 'Recent log entries: ' . count(\$logs) . PHP_EOL;
"
ステップ2:PHPMailerをカスタマイズする
// functions.php: WP Mail SMTP PHPMailer設定
// ① PHPMailer の初期化時にSMTP設定を上書き
add_action('phpmailer_init', function(PHPMailer\PHPMailer\PHPMailer $phpmailer): void {
// WP Mail SMTP が設定されていない場合のフォールバック
if ($phpmailer->Mailer !== 'smtp') return;
// タイムアウト延長(遅いSMTPサーバー対策)
$phpmailer->Timeout = 30;
// デバッグ出力をログに記録
$phpmailer->SMTPDebug = 2;
$phpmailer->Debugoutput = function(string $message, int $level): void {
error_log('[WP Mail SMTP Debug] ' . $message);
};
});
// ② wp_mail の引数を検査してデバッグ
add_filter('wp_mail', function(array $args): array {
error_log(sprintf('[WP Mail] To: %s | Subject: %s',
is_array($args['to']) ? implode(',', $args['to']) : $args['to'],
$args['subject']
));
return $args;
});
// ③ メール送信失敗時にエラーをキャプチャ
add_action('wp_mail_failed', function(WP_Error $error): void {
error_log('[WP Mail Failed] ' . $error->get_error_message());
error_log('[WP Mail Failed Data] ' . print_r($error->get_error_data(), true));
});
ステップ3:送信元アドレスを統一する
// functions.php: 送信元統一
// ① すべてのWordPressメールの送信元を統一
add_filter('wp_mail_from', function(string $email): string {
return 'noreply@example.com'; // サイトのドメインに変更
}, 99);
add_filter('wp_mail_from_name', function(string $name): string {
return get_bloginfo('name');
}, 99);
// ② パスワードリセットメールの送信元を修正
add_filter('retrieve_password_title', function(string $title, string $key, string $login): string {
return sprintf('[%s] パスワードのリセット', get_bloginfo('name'));
}, 10, 3);
// ③ 特定のメール種別で送信元を変更
add_filter('wp_mail', function(array $args): array {
// WooCommerceの注文メールは別の送信元を使用
if (isset($args['headers']) && str_contains(implode("\n", (array) $args['headers']), 'WooCommerce')) {
$args['headers'][] = 'From: ' . get_bloginfo('name') . ' <orders@example.com>';
}
return $args;
});
ステップ4:各メールサービスの設定を修正する
# SendGridのAPIキー接続テスト
wp eval "
// SendGrid API テスト
\$api_key = defined('SENDGRID_API_KEY') ? SENDGRID_API_KEY : get_option('wp_mail_smtp')['sendgrid']['api_key'] ?? '';
if (empty(\$api_key)) {
echo 'SendGrid API key not configured' . PHP_EOL;
exit;
}
\$response = wp_remote_get('https://api.sendgrid.com/v3/user/credits', [
'headers' => [
'Authorization' => 'Bearer ' . \$api_key,
'Content-Type' => 'application/json',
],
'timeout' => 15,
]);
if (is_wp_error(\$response)) {
echo 'Connection error: ' . \$response->get_error_message() . PHP_EOL;
exit;
}
\$code = wp_remote_retrieve_response_code(\$response);
\$body = json_decode(wp_remote_retrieve_body(\$response), true);
echo 'Response code: ' . \$code . PHP_EOL;
echo 'Credits remain: ' . (\$body['remaining'] ?? 'N/A') . PHP_EOL;
echo 'Credits used: ' . (\$body['used'] ?? 'N/A') . PHP_EOL;
"
ステップ5:メール送信のテストとログ記録
// functions.php: メール送信テスト・ログ
// ① カスタムメール送信テスト関数
function test_wp_mail_delivery(): void {
$result = wp_mail(
get_option('admin_email'),
'[テスト] WP Mail SMTP 動作確認',
'送信テストメッセージです。このメールが届いていれば設定は正常です。',
['Content-Type: text/plain; charset=UTF-8']
);
if ($result) {
error_log('[WP Mail Test] Success: test email sent to ' . get_option('admin_email'));
} else {
global $phpmailer;
error_log('[WP Mail Test] Failed: ' . ($phpmailer->ErrorInfo ?? 'unknown error'));
}
}
// ② 送信済みメールをカスタムテーブルにログ記録
add_action('wp_mail_succeeded', function(array $mail_data): void {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'mail_log',
[
'recipient' => is_array($mail_data['to']) ? implode(',', $mail_data['to']) : $mail_data['to'],
'subject' => $mail_data['subject'],
'sent_at' => current_time('mysql'),
'status' => 'success',
],
['%s', '%s', '%s', '%s']
);
});
// ③ SMTP接続ポートを動的に切り替え
add_filter('wpms_mailer_smtp_port', function(int $port): int {
// ポート25が使えない環境ではポート587(STARTTLS)を使用
return 587;
});
注意事項
- GmailのSMTP認証には2023年以降「アプリパスワード」が必要です。Googleアカウントで2段階認証を有効にしてから「アプリパスワード」を生成し、通常のGmailパスワードの代わりに使用してください
- 多くのレンタルサーバーはセキュリティ対策のためポート25(SMTP)を送信側からブロックしています。ポート587(STARTTLS)またはポート465(SSL/TLS)を試してください
- SendGridやMailgunなどのAPIベースのメール配信サービスを使用する場合、送信元ドメインのDKIM・SPFレコードの設定が必要です。設定なしだとスパムフォルダに振り分けられることがあります
まとめ
WP Mail SMTP修復は①wp_mail_smtpオプションでメーラー設定・ホスト・ポート・認証設定を確認、②phpmailer_initフックでSMTPタイムアウト延長・デバッグ出力設定・wp_mail_failedフックでエラーをキャプチャ、③wp_mail_fromフィルターで送信元アドレスをサイトドメインに統一・retrieve_password_titleフィルターでパスワードリセットメールを修正、④SendGrid APIキーの接続テスト・クレジット残量確認、⑤wp_mail_succeededフックでカスタムテーブルにログ記録・SMTP接続ポート587に切り替えることで解決します。