如何修复 PHPmailer 中的'Mailer 错误:SMTP connect() 失败”?

Mary-Kate Olsen
发布: 2024-10-27 00:03:30
原创
301 人浏览过

How to Fix

PHPmailer 中的 SMTP Connect() 故障排除

简介

尝试发送电子邮件时使用 PHPmailer,可能会遇到错误“Mailer Error: SMTP connect() failed”。此问题的出现是由于 Google 实施了名为 XOAUTH2 的新授权机制。

解决方案

要解决此问题,请按照以下步骤操作:

1.在 Google 帐户中启用不太安全的应用

  • 登录您的 Google 帐户并导航至:https://www.google.com/settings/security/lesssecureapps
  • 确保启用“打开对不太安全的应用程序的访问”选项。

2.使用端口 587 上的 TLS 而不是端口 465 上的 SSL

  • 修改代码以使用端口 587 上的 TLS 而不是端口 465 上的 SSL。替换以下行:

    <code class="php">$mail->Host = "ssl://smtp.gmail.com";
    $mail->Port = 465;</code>
    登录后复制

    与:

    <code class="php">$mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;</code>
    登录后复制

示例代码

这是修改后的代码:

<code class="php">require "class.phpmailer.php";
$mail = new PHPMailer(); 
$mail->IsSMTP();                              // send via SMTP
$mail->SMTPDebug = 2;  // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;                       // turn on SMTP authentication
$mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for GMail
$mail->SMTPAutoTLS = false;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = "[email&#160;protected]";        // SMTP username
$mail->Password = "mypassword";               // SMTP password
$webmaster_email = "[email&#160;protected]";       //Reply to this email ID
$email="[email&#160;protected]";                // Recipients email ID
$name="My Name";                              // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "My Name";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"My Name");
$mail->WordWrap = 50;                         // set word wrap
$mail->IsHTML(true);                          // send as HTML
$mail->Subject = "subject";
$mail->Body = "Hi,
This is the HTML BODY ";                      //HTML Body 
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body 

if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}</code>
登录后复制

通过实施这些更改,您应该能够使用 PHPmailer 成功发送电子邮件。

以上是如何修复 PHPmailer 中的'Mailer 错误:SMTP connect() 失败”?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!