3

I am trying to send email using PEAR Mail via my gmail smtp

I done a lot of research for several days and tried A LOT of options and I am always getting the error:

error: authentication failure [SMTP: Invalid response code received from server (code: 535, response: Incorrect authentication data)**]

Here is my code:

 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>');
}
  • On my php.ini OpenSSL is enabled
  • PEAR - Mail - Mail_Mime - Net_SMTP - NET_Socket - Auth_SASL are
    installed
  • On my Google account "Less secure apps" is ON

  • Also tried touse the "2-Step-Verification" and for password to use the code provided by Google

I know that there are several other options out there (Swift Mailer...) but I have my own reasons to make PEAR Mail works

Thanks in advance!

theok
  • 121
  • 9

1 Answers1

0

Simple Working Test code:

<?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

You must use Google App Password:

enter image description here

Dung
  • 19,199
  • 9
  • 59
  • 54