首頁  >  文章  >  後端開發  >  為什麼我的 PHPmailer SMTP connect() 與 Gmail 失敗,如何修復?

為什麼我的 PHPmailer SMTP connect() 與 Gmail 失敗,如何修復?

Barbara Streisand
Barbara Streisand原創
2024-10-27 04:26:03814瀏覽

Why is my PHPmailer SMTP connect() failing with Gmail and how can I fix it?

SMTP connect() failed PHPmailer - PHP

當您嘗試使用PHPmailer 發送電子郵件時遇到錯誤,特別是,會出現此問題「郵件程式錯誤:SMTP 連線()失敗。」根本原因通常與身份驗證設定以及與您的電子郵件提供者的相容性有關。

在這種情況下,解決方案包括為您的 Google 帳戶啟用安全性較低的應用程式。 Google 最近實施了 XOAUTH2 身份驗證,這要求您明確允許存取第三方應用程式。

要解決這個問題:

  • 訪問https://www.google.com/settings /security/lesssecureapps
  • 選取「開啟」選項
  • 此步驟授權PHPmailer 使用XOAUTH2 機制連接到Google SMTP 伺服器。

此外,確保您使用正確的SMTP 設置:

  • SMTP 服務器: smtp.gmail.com
  • 連接埠: 587
  • TLS:已啟用
  • 驗證:
  • 身份驗證:
  • 使用者名稱:您的Google 帳戶電子郵件地址

密碼:

您的Google 帳戶密碼
<code class="php">require_once 'C:\xampp\htdocs\email\vendor\autoload.php';

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

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>

以下是包含以下設定的更新代碼範例:透過啟用不太安全的應用程式並使用正確的SMTP 設置,您應該能夠使用PHPmailer 與Gmail 的SMTP 伺服器成功發送電子郵件。

以上是為什麼我的 PHPmailer SMTP connect() 與 Gmail 失敗,如何修復?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn