用户名和密码不被接受

时间:2015-02-11 19:04:02

标签: php gmail phpmailer smtpclient

我正在尝试使用gmail的smtp发送电子邮件(请参阅下面的代码),但我收到“用户名和密码未被接受”错误。

我试过了:

它们都不起作用。

这是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完整的错误消息(使用DebugMode = 4)

1 个答案:

答案 0 :(得分:0)

经过测试,我通过更改主机以包含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;
}