Search code examples
phpemailsmtpphpmailer

SMTP connect failed - PHPMailer Error on Localhost


I was using PHPMailer latest version and I was able to send emails using it. But now I don't know what had happened? Now I'm not able to send mail using it. It gives me following error -

Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

I have also checked openssl extension.

Here is my code -

<form method="post" action="mail.php">
  <input type="text" placeholder="Enter your email to subscribe" name="emailid" />
  <input type="submit" value="Submit" />
</form>

The contents of mail.php file

<?php
$emailSubscr = $_POST['emailid'];
$sub = 'New Subscriber';
$message = $emailSubscr.' has subscribed for newsletter';

require 'phpmailer/PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;

$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';     // SMTP Host Name
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = 'mypassword';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;                                    // TCP port to connect to

$mail->From = $emailSubscr;
$mail->FromName = 'Subscriber';
$mail->addAddress('[email protected]', 'Rohit Kumar');     // Add a recipient
$mail->addReplyTo($emailSubscr, 'Subscriber');

$mail->Subject = $sub;
$mail->Body    = $message;

if(!$mail->send()) {
    echo 'Some error occured, please try again later.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Thanks for subscribing our newsletter on your email id.';
}
?>

Solution

  • Thanks Faiz Rasool. My issue is resolved.

    can you do this please $mail->SMTPDebug = 3; and post the log   – Faiz Rasool

    Actually I use Mobile Broadband and its ip changes most of the time. And yesterday, google might have detected me as suspicious login when I tried accessing it with my app.
    When I login to my gmail account I saw a notice to change my password due to which my app was not able to login to my account.
    You helped me. When I checked the debug log, there was a message from google saying to login via web browser. I did so, resetted the password, selected the Suspicious login attempt as ME and my issue is resolved.. But the main thing here is, after setting google's option - Allow less secure apps to ON, Google was still blocking my app sometimes. I think the reason behind this (I think) is that my ip changes when I disconnect and reconnect my mobile broadband. And hence, my location changes. By the way, I'm not using the GMail account anymore for my app.