首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHPMailer 透過 Gmail SMTP 發信失敗:openssl 擴展缺失完整解決方案

     編輯:PHP 相關知識

使用 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
}

解決步驟

  1. 確認 openssl 擴展狀態:執行 php -m | grep openssl 或 phpinfo() 檢查。
  2. 啟用擴展:
    • Windows:編輯 php.ini,將 ;extension=php_openssl.dll 前分號移除。
    • Linux(Debian/Ubuntu):sudo apt-get install php-openssl && sudo systemctl restart php-fpm(或 apache2/nginx 對應服務)。
    • Linux(CentOS/RHEL):sudo yum install php-openssl && sudo systemctl restart php-fpm。
  3. 重啟 Web 服務:Apache/Nginx + PHP-FPM 均需重啟生效。
  4. 驗證:再次執行發信腳本,Debug 輸出應顯示 Message sent!。

Gmail 專項配置補充

  • 兩步驟驗證帳號:必須生成「應用程式密碼」填入 Password,而非登入密碼。
  • 低安全性應用程式存取權:若未開啟兩步驟驗證,需在 Google 帳號設定開啟「允許安全性較低的應用程式存取」(Google 2022 年後逐步移除此選項,建議改用應用程式密碼)。
  • TLS 替代方案:若 SSL 端口受限,可改用 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 憑證鏈。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved