How to send PHP email using GMail SMTP – Enable Gmail SMTP security – stop authentication failure SMTP: Invalid response code received from server 534 error

Was having some troubles sending using PHP SMTP email and Gmail, kept getting an error saying "error:  authentication failure [SMTP: Invalid response code received from server (code: 534...).

It turns out you have to authorise Gmail to allow your PHP script to send.

It was a 3 stage thing for me. First enable "Access for less secure apps" at the Google account security page :

https://www.google.com/settings/security

Then go to the Unlock Google Captcha link.

https://accounts.google.com/displayunlockcaptcha

You've now got a few minutes to run your script, so that Google captcha knows you're alright and trusted!

>php my_mail_script.php.

Your script should now run.

DONE! finally it worked.

Here's my PHP script that sends HTML email using SMTP :

<?php

require_once "Mail.php";
require_once('Mail/mime.php');

$from    = "Somebody <someone@gmail.com>;;;"; // the email address

$to="aperson@domain.com";

// subject
$subject = 'Testing from Startnet';

// message
$body = '<html>
<head>
  <title>Test by Startnet</title>
</head>
<body>
<p>This is a test of <b>HTML</b></p>
<p>from Startnet</p>
</body>
</html>';

// login data

    $host    = "smtp.gmail.com";

    $port    =  "587";

    $user    = "someone@gmail.com";
    $pass    = "mypassword";
    
    $smtp    = @Mail::factory("smtp", array("host"=>$host, "port"=>$port, "auth"=> true, "username"=>$user, "password"=>$pass));

    $headers = array("From"=> $from,

        "To"=>$to,
        "Subject"=>$subject,
        "MIME-Version"=>"1.0",
        "Content-type"=>"text/html; charset=iso-8859-1"
        );

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

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

 

Leave a Reply