使用 PHPMailer 5.2.1 透過 Gmail SMTP(ssl://smtp.gmail.com:465)發信時,常遇到 SMTP Error: Could not connect to SMTP host。根因多為 PHP 未啟用 openssl 擴展,導致無法建立 SSL/TLS 加密連線。本文提供完整排查與修復步驟。
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = 'yourname@gmail.com';
$mail->Password = 'yourpassword';
// ... 設定寄件人、收件人、內容
if (!$mail->Send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo; // 輸出:SMTP Error: Could not connect to SMTP host
}
php -m | grep openssl 或 phpinfo() 檢查。php.ini,將 ;extension=php_openssl.dll 前分號移除。sudo apt-get install php-openssl && sudo systemctl restart php-fpm(或 apache2/nginx 對應服務)。sudo yum install php-openssl && sudo systemctl restart php-fpm。Message sent!。Password,而非登入密碼。SMTPSecure = 'tls'、Port = 587。// 開啟詳細除錯輸出至檔案
$mail->SMTPDebug = 3; // 4 = 低層級
$mail->Debugoutput = function($str, $level) {
file_put_contents('phpmailer_debug.log', date('Y-m-d H:i:s') . " [$level] $str\n", FILE_APPEND);
};
fsockopen 能連上 465 就代表 PHP SSL 正常 —— 錯誤,PHPMailer 內部使用 stream_socket_client 需 openssl 支援。php.ini 中 openssl.cafile / openssl.capath 設定 —— 部分需指定 CA 憑證路徑才能驗證 Gmail 憑證鏈。