I have recently been unable to send out mails through php on localhost. I use PHPMailer
and SwiftMailer
in different parts of the application.
With SwiftMailer
I get this:
Connection could not be established with host smtp.gmail.com [ #0]
With PHPMailer
, the message is:
SMTP Error: Could not connect to SMTP host.
My settings on SwiftMailer look like this:
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername(APP_GMAIL_EMAIL)
->setPassword(APP_GMAIL_PWD);
I have gone through several threads here at SO and elsewhere, and tried many 'fixes' but the error messages remain the same. Some "solutions" I've tried are:
php.ini
(It was previously off) smtp.gmail.com
to smtp.googlemail.com
smtp.gmail.com
with certain gmail IP addresses smtp.gmail.com
with gethostbyname('smtp.gmail.com')
->setSourceIp('0.0.0.0')
to the instantiation code above, after setUsername
and setPassword
This code was previously working, and I'm not sure what could have broken the function. As part of troubleshooting, I have just confirmed that a similar code on Linux shared hosting is emailing satisfactorily, suggesting that the problem is somehow from my environment. Thus, I even tried different sources of internet access, in case it's an ISP thing.
How can I crack this nut?
I have been able to overcome the problem, at least with SwiftMailer
. The solution must have arisen after my PHP upgrade from 5.2.5 to 5.6, which is the version I have currently. The insight came from this page:
https://github.com/swiftmailer/swiftmailer/issues/544
If you are using PHP 5.6, the error does occur because of the "SSL context options" used for the stream context in swiftmailer. IN PHP 5.6 verify_peer and verify_peer_name the default was set to TRUE, so PHP checks the SSL certificate. It is currently not possible to disable it in swiftmailer using some options.
You could disable the SSL check by modifying the function "_establishSocketConnection" in StreamBuffer.php. Add these lines before stream_socket_client command:
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
It would be great if these options could be set without hacking the code.
Thanks to https://stackoverflow.com/a/29448735/2554788 who first pointed me to the said post.
By the way, the path to StreamBuffer.php
is:
\lib\classes\Swift\Transport
A word of warning though: this solution is based on hacking the code inside a class, and will probably fail, say, after upgrading SwiftMailer
versions (in which case you'd need to go back and hack the code again).
Perhaps, more current versions of SwiftMailer
have put their acts together in PHP 5.6 (I use SwiftMailer 5.1 currently). I intend to try an upgrade ASAP, hoping there has been an elegant fix for this issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.