How can I solve "Connection could not be established with host smtp.gmail.com"?

Success Man picture Success Man · Feb 7, 2018 · Viewed 15.8k times · Source

If I do send email on the my localhost, it works. No error

But I try on the staging server, it display error like this :

Swift_TransportException in StreamBuffer.php line 268:
Connection could not be established with host smtp.gmail.com [Connection timed out #110]

in StreamBuffer.php line 268
at Swift_Transport_StreamBuffer->_establishSocketConnection() in StreamBuffer.php line 62
at Swift_Transport_StreamBuffer->initialize(array('protocol' => 'tcp', 'host' => 'smtp.gmail.com', 'port' => '587', 'timeout' => '30', 'blocking' => '1', 'tls' => true, 'type' => '1', 'stream_context_options' => array())) in AbstractSmtpTransport.php line 113
at Swift_Transport_AbstractSmtpTransport->start() in Mailer.php line 79
at Swift_Mailer->send(object(Swift_Message), array()) in Mailer.php line 395
at Mailer->sendSwiftMessage(object(Swift_Message)) in Mailer.php line 217
...

My env like this :

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=secret
MAIL_ENCRYPTION=tls

From some reference on the google (Using gmail smtp via Laravel: Connection could not be established with host smtp.gmail.com [Connection timed out #110]), I try some answer. I try change mail port and mail encryption to be like this :

MAIL_PORT=465
MAIL_ENCRYPTION=ssl

It does not work

I try again to change this :

MAIL_DRIVER=sendmail

It does not work too

I do on here : https://myaccount.google.com/lesssecureapps

It's the same

I try :

php artisan cache:clear
php artisan config:cache

It still does not work

My server using gitlab, forge laravel and digital ocean

Previous send mail on the staging server worked, but after I re-install the repository on the forge laravel, it now does not work

What do I need to set?

Answer

Sagar Gautam picture Sagar Gautam · Feb 7, 2018

Few days ago I've faced exactly the same problem and I've searched everywhere like laracast stackoverflow and many github issues and finally solve the problem.

You need configuration something like this,

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=yourpassword
MAIL_ENCRYPTION=ssl

After this setup you should make sure that your google account 2 step verification is turned off because this adds an extra layer of security that's why connection can't be established.

I think this is new feature added by google recently. I've working mail configuration before but recently same code doesn't work.

You can go to your google account where you will see Sign-in and Security tab. Click on it then you will see 2 step verfication there. Then you need to turn off that. Then I think it'll work.

This thing worked for me I hope it'll work for you as well. I hope you understand.