无法通过PHPMailer使用Gmail SMTP服务器发送电子邮件,出现错误:在端口587上需要SMTP AUTH进行消息提交。如何解决?

82
我想通过PHP Mailer使用Gmail SMTP服务器发送电子邮件。
这是我的代码。
<?php
require_once('class.phpmailer.php');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = 'MyUsername@gmail.com';
$mail->Password = 'valid password';
$mail->SMTPAuth = true;

$mail->From = 'MyUsername@gmail.com';
$mail->FromName = 'Mohammad Masoudian';
$mail->AddAddress('anotherValidGmail@gmail.com');
$mail->AddReplyTo('phoenixd110@gmail.com', 'Information');

$mail->IsHTML(true);
$mail->Subject    = "PHPMailer Test Subject via Sendmail, basic";
$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";
$mail->Body    = "Hello";

if(!$mail->Send())
{
  echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
  echo "Message sent!";
}
?>

但我收到以下错误信息

Mailer Error: SMTP Error: The following recipients failed: anotherValidGmail@gmail.com

SMTP server error: SMTP AUTH is required for message submission on port 587

my domain is vatandesign.ir


你可能想看一下Jorj在这个帖子上的回答:https://dev59.com/P1bTa4cB1Zd3GeqP_H2B - Human Wannabe
13个回答

149
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "email@gmail.com";
$mail->Password = "password";
$mail->SetFrom("example@gmail.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("email@gmail.com");

 if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
    echo "Message has been sent";
 }

这段代码已经经过我的测试并且可以正常工作。

可能需要添加$mail->SMTPSecure = 'ssl';

同时,请确保该账户未开启两步验证,因为这也会导致问题。

更新:

你可以尝试将 $mail->SMTP 更改为:

$mail->SMTPSecure = 'tls';

值得注意的是,一些SMTP服务器会阻止连接。一些SMTP服务器不支持SSL(或TLS)连接。


当我使用你的代码时,我收到了以下错误信息:邮件发送错误:以下发件人地址失败:phoenixd110@gmail.com :在未连接的情况下调用Mail()。 - Mohammad Masoudian
3
更新答案并提供进一步建议。代码肯定没问题。您可以查看这两个来源:http://phpmailer.worxware.com/index.php?pg=exampleagmail 和 https://github.com/Synchro/PHPMailer/blob/master/examples/test_smtp_gmail_advanced.php - andrew-caulfield
我收到以下错误信息: CLIENT -> SMTP: EHLO localhost SMTP -> ERROR: 服务器不接受EHLO指令 CLIENT -> SMTP: HELO localhost 注意:在C:\xampp\htdocs\program\mailsending1\mailsending_v1\PHPMailer-master\class.smtp.php的第1023行,fwrite()函数发送16字节数据失败,错误码为10054,表示远程主机强制关闭了一个现有的连接。 SMTP -> ERROR: 服务器不接受HELO指令 SMTP -> NOTICE: 检查连接时捕获到EOF SMTP Connect() 失败。邮件发送错误:SMTP Connect() 失败。 - Anurag Singh
2
请注意,如果您指定了“ssl”(强烈建议这样做),则您的PHP安装需要加载(或编译)“openssl”扩展,使用您喜欢的PHP扩展机制(我碰巧使用OS X Macports,其中sudo port install php5-openssl)。 - xgretsch
最好检查返回值和错误:if(!$mail->Send() || $mail->ErrorInfo) { - ymakux
根据我的经验,您现在需要匹配端口和安全选项。$mail->SMTPSecure = 'tls'; $mail->Port = 587;或者$mail->SMTPSecure = 'ssl'; $mail->Port = 465; - Westy92

34

所以我刚刚解决了我的“SMTP连接失败”错误,并且我想发布解决方案,以防可以帮助其他人。

我使用了 PHPMailer 示例 gmail.phps 文件中提供的精确代码。在使用 MAMP 时它可以正常工作,但当我将其移动到我的个人服务器上后就出现了 SMTP 连接错误。

我读过所有的 Stack Overflow 答案,以及 PHPMailer 的所有故障排除文档都表示这不是 PHPMailer 的问题,而是服务器端的设置问题。我尝试了不同的端口(587、465、25),尝试了“SSL”和“TLS”加密。我检查过我的 php.ini 文件确保启用了 openssl,也检查过防火墙是否有问题。一切都正常,但仍然无法解决问题。

解决方案是我必须删除这一行代码:

$mail->isSMTP();

现在所有东西都可用了。我不知道为什么,但它可以工作。我的其余代码是从PHPMailer示例文件中复制和粘贴的。


7
这种解决方案的作用是完全关闭SMTP。我不推荐使用这种方法。我从未解决过这个问题,现在我打算改用Mandrill API来发送邮件。 - Evan Butler
只需使用Mandrill,它更好,并且实际上具有一些分析功能。 - Evan Butler
它对我也起作用了。奇怪,这个库相当成熟。 - ymakux
1
糟糕的解决方案,您没有像这样使用SMTP,而是使用裸的PHP mail()函数,这可能会使您的电子邮件被某些收件人视为垃圾邮件。 - Nassim
我之前也遇到了同样的问题,这个解决方案对我很有效。现在邮件已经能够被发送并且不会进入垃圾邮件文件夹了。虽然不知道为什么,但它确实起作用了。 - Cesar Bielich
显示剩余3条评论

9
值得注意的是,如果您启用了双重身份验证,您需要设置一个应用程序特定密码来替代您的电子邮件账户密码。
您可以按照以下说明生成应用程序特定密码: https://support.google.com/accounts/answer/185833 然后将$mail->Password设置为您的应用程序特定密码。

5
似乎您的服务器无法与Gmail SMTP服务器建立连接。 以下是一些故障排除提示: 1)检查PHP上是否正确配置了SSL(处理它的模块不会默认安装在PHP上。您需要在phph.ini中检查配置)。 2)检查防火墙是否允许对所需端口进行传出调用(这里为465或587)。使用telnet进行检查。如果端口未打开,则需要从系统管理员那里获得一些支持,以设置配置。 希望您能尽快解决问题!

1
这段代码对我来说运行良好。
    $mail = new PHPMailer;
    //Enable SMTP debugging. 
    $mail->SMTPDebug = 0;
    //Set PHPMailer to use SMTP.
    $mail->isSMTP();
    //Set SMTP host name                          
    $mail->Host = $hostname;
    //Set this to true if SMTP host requires authentication to send email
    $mail->SMTPAuth = true;
    //Provide username and password     
    $mail->Username = $sender;
    $mail->Password = $mail_password;
    //If SMTP requires TLS encryption then set it
    $mail->SMTPSecure = "ssl";
    //Set TCP port to connect to 
    $mail->Port = 465;
    $mail->From = $sender;  
    $mail->FromName = $sender_name;
    $mail->addAddress($to);
    $mail->isHTML(true);
    $mail->Subject = $Subject;
    $mail->Body = $Body;
    $mail->AltBody = "This is the plain text version of the email content";
    if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    }
    else {
           echo 'Mail Sent Successfully';
    }

$mail->SMTPSecure = 'ssl'; $mail->Port = 465;我只是将TSL更改为ssl,将587更改为465,然后它就对我起作用了,谢谢。GMAIL允许不安全的应用程序:https://myaccount.google.com/lesssecureapps - Kodali444
谷歌将于2022年5月30日之前删除此设置。没有人能够仅使用用户名和密码登录谷歌。https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637886225982390768-515471651&p=less-secure-apps&rd=1 - Bellash

1
谷歌根据用户提供的信息不同对待Gmail账户,可能是为了遏制垃圾邮件。在进行电话验证之前,我无法使用SMTP。我创建了另一个账户进行了双重检查,然后成功确认了它。

0
 $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

1
虽然这段代码片段可能解决了问题,但包括解释真的有助于提高您的帖子质量。请记住,您正在为未来的读者回答问题,而这些人可能不知道您的代码建议原因。 - Athul Nath
这只是很危险的。不要这样做。 - Synchro

0
如果有人没有得到有效的答案,可以尝试这个方法。
注意:我正在使用PHPMailer 5.2.23。
<?php

    date_default_timezone_set('Asia/Kolkata');

    require './Libraries/PHPMailer5/PHPMailerAutoload.php';
    $mail = new PHPMailer;

    $mail->isSMTP();

    // Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = 2;

    $mail->Debugoutput = 'html';

    $mail->Host = 'localhost';
    $mail->Port = 587;

    $mail->SMTPSecure = 'tls';

    $mail->SMTPAuth = true;
    $mail->Username = "yourWebmailUsermail";
    $mail->Password = "yourWebmailPassword";

    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

    $mail->setFrom('formEmailAddress', 'First Last');

    $mail->addAddress('toEmailAddress', 'John Doe');

    $mail->Subject = 'PHPMailer GMail SMTP test';

    $mail->msgHTML("<h1>Hi Test Mail</h1>");
    $mail->AltBody = 'This is a plain-text message body';

    if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message sent!";
    }
?>

0

我已经找到了一个解决方案,而且它正在运作。

基本设置:

$mail->IsHTML(true);
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_CLIENT;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 587;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = 'user@gmail.com';
//Password to use for SMTP authentication
$mail->Password = 'PASSWORD_HERE';
//Set who the message is to be sent from
$mail->setFrom('email@email.ext', 'From where it is sent');
//Set an alternative reply-to address
$mail->addReplyTo('email@email.ext', 'Reply To');
//Set who the message is to be sent to
$mail->addAddress('email@email.ext');
//Set the subject line
$mail->Subject = 'Email subject';
// Body message
$mail->Body = '
  <h1>Message details</h1>
';
// Send message
if( $mail->send()  ) {
    echo "Sent"
} else {
    echo "Not Sent";
}

如果你已经尝试了所有方法,可以尝试以下步骤:

  1. 禁用阻止可疑应用/技术的功能 https://www.google.com/settings/u/1/security/lesssecureapps
  2. 清除验证码 https://accounts.google.com/b/0/DisplayUnlockCaptcha

进行测试。

以下是一些有用的文章,可以帮助你解决问题:

https://support.google.com/a/thread/108782439/smtp-error-password-command-failed-535-5-7-8-username-and-password-not-accepted?hl=en&msgid=108963583

https://bobcares.com/blog/phpmailer-smtp-error-password-command-failed/


0

我想分享一下我的phpMailer经验,它在本地(XAMPP)上运行正常,但在我的托管提供商上无法正常工作。

我打开了phpMailer的错误报告功能。

 $mail->SMTPDebug=2

我遇到了“连接被拒绝错误”

我向我的主机提供商发送了电子邮件,他们说他们会打开SMTP端口25、465、587。

然后我得到了以下错误响应:“SMTP ERROR: Password command failed:”....“请通过您的Web浏览器登录,然后重试”....“SMTP Error: Could not authenticate.”

因此,谷歌会检查您是否已登录到您的帐户(当我通过我的浏览器本地运行脚本时,我已经登录),然后允许您通过phpMailer脚本发送邮件。

要解决这个问题:

1:进入您的Google帐户->安全 2:滚动到密钥图标并选择“双重验证”,然后按照程序进行操作 3:完成后,从Google帐户中返回到密钥图标->安全,并选择第二个选项“创建应用程序密码”,然后按照程序进行操作以获取密码。

现在转到您的phpMailer对象,并使用上述过程给出的密码更改您的Google密码。

你完成了。

代码:

require_once('class.phpmailer.php');

$phpMailerObj= new PHPMailer();

                $phpMailerObj->isSMTP();                    
                $phpMailerObj->SMTPDebug = 0;
                $phpMailerObj->Debugoutput = 'html';                    
                $phpMailerObj->Host = 'smtp.gmail.com';                     
                $phpMailerObj->Port = 587;
                $phpMailerObj->SMTPSecure = 'tls';
                $phpMailerObj->SMTPAuth = true;                 
                $phpMailerObj->Username = "YOUR EMAIL";                 
                $phpMailerObj->Password = "THE NEW PASSWORD FROM GOOGLE ";
                $phpMailerObj->setFrom('YOUR EMAIL ADDRESS', 'THE NAME OF THE SENDER',0);
                $phpMailerObj->addAddress('RECEIVER EMAIL ADDRESS', 'RECEIVER NAME');
                
                $phpMailerObj->Subject = 'SUBJECT';
                $phpMailerObj->Body ='MESSAGE';
                
                if (!phpMailerObj->send()) {
                    echo "phpMailerObjer Error: " . $phpMailerObj->ErrorInfo;
                    return 0;
                } else {
                    echo "Message sent!";
                    return 1;
                } 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接