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

Patricia Arquette
發布: 2024-10-26 03:23:02
原創
382 人瀏覽過

  How to Resolve

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

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

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

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

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

<code class="php">require_once 'C:\xampp\htdocs\email\vendor\autoload.php';

define ('GUSER','[email&#160;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;
    }
}</code>
登入後複製

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

以上是在 Gmail 中使用 PHPmailer 時如何解決「SMTP Connect() Failed」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!