”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 在 Gmail 中使用 PHPmailer 时如何解决“SMTP Connect() Failed”错误?

在 Gmail 中使用 PHPmailer 时如何解决“SMTP Connect() Failed”错误?

发布于2024-11-08
浏览:362

  How to Resolve \

PHPmailer 中 SMTP 连接失败:解决问题

通过 PHPmailer 发送电子邮件时,开发者可能会遇到错误:“Mailer Error: SMTP连接()失败。”这个问题在使用 Gmail 的 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