使用PEAR Mail通过Gmail SMTP发送PHP电子邮件时出现错误

3

我正在尝试通过我的Gmail SMTP使用PEAR邮件发送电子邮件。

我进行了几天的大量研究,并尝试了很多选项,但我始终收到以下错误:

错误:认证失败[SMTP:服务器收到无效响应代码(代码:535,响应:不正确的身份验证数据)**]

以下是我的代码:

 require_once "Mail.php";

$from = '<MY_EMAIL@gmail.com>';
$to = '<foo@gmail.com>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you2?";

$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);

$smtp = Mail::factory('smtp', array(
        'host' => 'ssl://smtp.gmail.com', //tried also without ssl:// or tls://
        'port' => '465', //tried also 578
        'auth' => true,
        'username' => 'MY_EMAIL@gmail.com',
        'password' => 'MY_GMAIL_PASS' //or code provided by google 2-step-verification
    ));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
    echo('<p>' . $mail->getMessage() . '</p>');
} else {
    echo('<p>Message successfully sent!</p>');
}
  • 我的php.ini中启用了OpenSSL
  • 已安装PEAR-Mail-Mail_Mime-Net_SMTP-NET_Socket-Auth_SASL
  • 我的Google账户上“使用较不安全的应用程序”是打开的

  • 我还尝试过使用“两步验证”,并使用由Google提供的代码作为密码

我知道有其他几种选项(如Swift Mailer...),但我有自己使用PEAR Mail的原因

提前致谢!


2
你不能使用常规密码,而是需要一个“应用程序”/SMTP 密码:https://support.google.com/accounts/answer/185833?hl=zh - mario
@mario 请检查我的第四个评论。我尝试过了。 - theok
端口号 = 587? - Eric F.
有一个工厂的参数 - 'debug' => true,可能会有所帮助。 - Harijs Krūtainis
1个回答

0
简单的工作测试代码:
<?php

require "Mail.php";

$to = "dddd@gmail.com";
$from = "llll@gmail.com"; // the email address
$subject = "hiii";
$body = "\n\nEmail contents here";

$host = "smtp.gmail.com";
$port = "587";
$user = "hhh@gmail.com";
$pass = "hhh";

$headers = array("From" => $from, "To" => $to, "Subject" => $subject);
$smtp = @Mail::factory("smtp", array("host" => $host, "port" => $port, "auth" => true, "username" => $user, "password" => $pass));
$mail = @$smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
    echo "error: {$mail->getMessage()}";
} else {
    echo "Message sent";
}

enter image description here

您必须使用谷歌应用密码:

enter image description here


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