我无法使用 gmail 从 Localhost 使用 SwiftMailer 或 PHPMailer 发送邮件

I cannot send mail with SwiftMailer or PHPMailer from Localhost using gmail

我最近无法通过本地主机上的 php 发送邮件。我在应用程序的不同部分使用 PHPMailerSwiftMailer

有了 SwiftMailer 我明白了:

Connection could not be established with host smtp.gmail.com [ #0]

使用PHPMailer,消息是:

SMTP Error: Could not connect to SMTP host.

我在 SwiftMailer 上的设置如下所示:

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername(APP_GMAIL_EMAIL)
->setPassword(APP_GMAIL_PWD);

我在 SO 和其他地方经历了几个线程,并尝试了很多 'fixes' 但错误消息保持不变。我试过的一些 "solutions" 是:

  1. php.ini中启用 OpenSSL(之前是关闭的)
  2. smtp.gmail.com更改为smtp.googlemail.com
  3. 用特定的 gmail IP 地址替换 smtp.gmail.com
  4. smtp.gmail.com替换为gethostbyname('smtp.gmail.com')
  5. 在上面的实例化代码中添加->setSourceIp('0.0.0.0'),在setUsernamesetPassword
  6. 之后

此代码之前可以正常工作,但我不确定是什么破坏了该功能。作为故障排除的一部分,我刚刚确认 Linux 共享主机上的类似代码正在令人满意地发送电子邮件,这表明问题出在我的环境中。因此,我什至尝试了不同的互联网访问来源,以防是 ISP 问题。

我怎样才能破解这个难题?

我已经能够克服这个问题,至少 SwiftMailer。解决方案一定是我 PHP 从 5.2.5 升级到 5.6 后出现的,这是我目前的版本。见解来自此页面:

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.

感谢 最先指出我所说的 post。

对了,StreamBuffer.php的路径是:

\lib\classes\Swift\Transport

警告:这个解决方案是基于破解 class 中的代码,并且可能会失败,比如说,在升级 SwiftMailer 版本之后(在这种情况下你需要返回并再次破解代码)。

也许,SwiftMailer 的更多当前版本已将它们的行为整合到 PHP 5.6 中(我目前使用 SwiftMailer 5.1)。我打算尽快尝试升级,希望这个问题已经得到了很好的解决。