3

I'm trying to use PHPMailer but I'm getting the following error:

Connection failed. Error #2: stream_socket_client(): unable to connect to ssl://smtp.gmail.com:465 (Connection refused)

Here is my code:

$mail = new PHPMailer;
$mail->SMTPDebug = 4;                               // Enable verbose debug  output
$mail->isSMTP();                                      // Set mailer to use SMTP  
$mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication  
$mail->Username = 'test@gmail.com';                 // SMTP username
$mail->Password = 'some_password';                           // SMTP password  
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted  
$mail->Port = 465;                                    // TCP port to connect to  
$mail->setFrom('earndreamsol@gmail.com' );
$mail->addAddress($email);     // Add a recipient      
//$mail->addReplyTo($email, $name);  
$mail->isHTML(true);                                  // Set email format to HTML  
$mail->Subject = "Email from Alahmed & Co";  
$mail->Body    = " Thanks For Subscribe Alahamed & co"; 
$mail->AltBody = "Thanks For Subscribe Alahamed & co";
if(!$mail->send()) {  
    echo 'Message could not be sent.';  
    echo 'Mailer Error: ' . $mail->ErrorInfo;  
} else {  
    $_SESSION['msg']="you are successfully subscribed !!";  
    $_SESSION['msg1']="you are successfully subscribed !!";
    header("location:index.php#newssection");
}
  • in your gmail account, you have to allow sending mails from `less secure methods` (google's term, not mine). – YvesLeBorg Oct 23 '18 at 11:21
  • 1
    If that's your password, then it should be removed. Ask moderators to remove history. – Matt D Oct 23 '18 at 11:34
  • It's likely that your ISP is blocking outbound SMTP - read the troubleshooting guide to diagnose that. It also looks like you may be using an old version of PHPMailer, and have based your code on an obsolete example, so make sure you're up to date. – Synchro Oct 23 '18 at 15:47

1 Answers1

3

Have you try to use :

$mail->SMTPSecure = 'tls';

and/or :

$mail->Port = 587;
noobie-php
  • 6,817
  • 15
  • 54
  • 101
Noxyra
  • 31
  • 2
  • Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.gmail.com:587 (Connection refused) this kind of error i got – Áwáīš Àhmāđ Oct 23 '18 at 17:18
  • same error ErrorException stream_socket_enable_crypto(): Peer certificate CN=`sgvip1.noc401.com' did not match expected CN=`smtp.gmail.com' – MH Fuad Mar 08 '20 at 05:15