」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 在 Gmail 中使用 PHPmailer 時如何解決「SMTP Connect() Failed」錯誤?

在 Gmail 中使用 PHPmailer 時如何解決「SMTP Connect() Failed」錯誤?

發佈於2024-11-08
瀏覽:414

  How to Resolve \

PHPmailer 中SMTP 連線失敗:解決問題

透過PHPmailer 傳送電子郵件時,開發者可能會遇到錯誤:「Mailer Error : SMTP連線()失敗。

解決方案在於 Google 實施了新的授權機制 XOAUTH2。若要允許 PHPmailer 連線到 Gmail 的 SMTP,您必須在 Google 帳戶中啟用「較不安全的應用程式」設定。此步驟授予不遵守嚴格加密協議的應用程式的存取權限。

此外,不要使用連接埠 465 上的 SSL,而是切換到連接埠 587 上的 TLS。 TLS 可確保您的要求已安全加密,從而滿足Google 的要求.

下面是包含這些變更的修改後的程式碼片段:

require_once 'C:\xampp\htdocs\email\vendor\autoload.php';

define ('GUSER','[email protected]');
define ('GPWD','your password');

// make a separate file and include this file in that. call this function in that file.

function smtpmailer($to, $from, $from_name, $subject, $body) { 
    global $error;
    $mail = new PHPMailer();  // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 2;  // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true;  // authentication enabled
    $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
    $mail->SMTPAutoTLS = false;
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;

    $mail->Username = GUSER;  
    $mail->Password = GPWD;           
    $mail->SetFrom($from, $from_name);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->AddAddress($to);
    if(!$mail->Send()) {
        $error = 'Mail error: '.$mail->ErrorInfo; 
        return false;
    } else {
        $error = 'Message sent!';
        return true;
    }
}

透過實施這些修改,您可以成功建立與 Gmail 的 SMTP 伺服器的連線並透過 PHPmailer 傳輸電子郵件。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3