Skip to content
Advertisement

How to fix Connection could not be established with host smtp.gmail.com in php

Good day guys. I’m trying to send email to the new user after registration on PHP website. The user record is submitting to databse but am getting error sending email to user; Uncaught Swift_TransportException: Connection could not be established with host smtp.gmail.com. I really need your help. below is my code

<?php

require_once 'vendor/autoload.php';
require_once 'config/constants.php';

// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl'))
  ->setUsername(EMAIL)
  ->setPassword(PASSWORD);

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);


function sendVerificationEmail($userEmail, $token){

    global $mailer;

    $body = '<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Verify email</title>
    </head>
    <body>
        
        <div class="wrapper">
            <p> Thank you for registrating on our website. Please click on the link below to verify your email</p>
            <a href="http://localhost/medxpress-ng/index.php?token= '. $token. '"> Verify your email address</a>
        </div>
    </body>
    </html>';

    // Create a message
$message = (new Swift_Message('Verify your email address'))
  ->setFrom(EMAIL)
  ->setTo($userEmail)
  ->setBody($body, 'text/html');
  ;

// Send the message
$result = $mailer->send($message);

}

function sendPasswordResetLink($userName, $token){
  global $mailer;

    $body = '<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Verify email</title>
    </head>
    <body>
        
        <div class="wrapper">
            <p> Hello there.
            Please click on the link below to reset your password</p>
            <a href="http://localhost/medxpress-ng/?password-token= '. $token. '"> Reset your password</a>
        </div>
    </body>
    </html>';

    // Create a message
$message = (new Swift_Message('Reset your password'))
  ->setFrom(EMAIL)
  ->setTo($userName)
  ->setBody($body, 'text/html');
  ;

// Send the message
$result = $mailer->send($message);

}

Advertisement

Answer

You should use port 587 instead and tls or ssl would have same behaviour:

https://support.google.com/mail/answer/7126229?hl=en

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement