首页  >  文章  >  后端开发  >  为什么我的 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