不接受用户名和密码

2022-07-03 00:00:00 gmail php phpmailer smtpclient

我正在尝试使用Gmail的SMTP(请参见下面的代码)发送电子邮件,但收到"用户名和密码不被接受"错误。

我已尝试:

  • this link
  • allow less secure apps
  • 已启用SSL
  • 在Gmail的设置上启用IMAP/POP
  • 其他登录名

它们都不起作用。

以下是PHP代码:

function sendEmail($from, $fromName, $msg)
{
    $mail = new PHPMailer();
    $mail->SMTPDebug  = 4; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only
    $mail->WordWrap    = 900; // RFC 2822 Compliant for Max 998 characters per line
    $mail->IsSMTP();

    //$mail->Host = 'tls://smtp.gmail.com:587';
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 587; //465
    $mail->SMTPSecure = "tls";
    $mail->SMTPAuth = true;
    $mail->Username = 'xxxx@gmail.com';
    $mail->Password = 'yyyyyyy';

    $mail->From = $from;
    $mail->FromName = $fromName;

    $mail->AddAddress('foo@gmail.com', ' ');

    $mail->IsHTML(true);

    $mail->CharSet = 'UTF-8';
    $mail->Priority = 1;
    $mail->Timeout = 60;
    $mail->SMTPKeepAlive = true; 
    $mail->Subject  = "subject here";
    $mail->Body = $msg;
    $mail->AltBody = 'testing..';
    $ok = $mail->Send();

    $mail->ClearAllRecipients();
    $mail->ClearAttachments();

    return $ok;
}

更新:Here's完整错误消息(调试模式=4)


解决方案

测试后,我通过将主机更改为包括tls前缀使其正常工作。

function sendEmail($from, $fromName, $msg)
{
$mail = new PHPMailer();
$mail->SMTPDebug  = 4; 
$mail->WordWrap    = 900; 
$mail->IsSMTP();

//$mail->Host = 'tls://smtp.gmail.com:587';
$mail->Host = "tls://smtp.gmail.com";
$mail->Port = 587; //465
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = 'xxxx@gmail.com';
$mail->Password = 'yyyyyyy';

// Define o remetente
$mail->From = $from;
$mail->FromName = $fromName;

$mail->AddAddress('foo@gmail.com', ' ');

$mail->IsHTML(true);

$mail->CharSet = 'UTF-8';
$mail->Priority = 1;
$mail->Timeout = 60;
$mail->SMTPKeepAlive = true; 
$mail->Subject  = "subject here";
$mail->Body = $msg;
$mail->AltBody = 'testing..';
$ok = $mail->Send();

$mail->ClearAllRecipients();
$mail->ClearAttachments();

return $ok;
}

相关文章