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

Patricia Arquette
发布: 2024-10-26 03:23:02
原创
382 人浏览过

  How to Resolve

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

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