Swiftmailer Gmail 连接超时 #110

app*_*pel 4 smtp swiftmailer

我想使用 gmail 的 smtp 和下面使用 Swiftmailer 发布的 PHP 脚本发送电子邮件。现在这在我自己的网络服务器上运行良好。但是当我在我为其创建它的人的网络服务器上使用它时,我得到了一个例外:

    Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host smtp.gmail.com [Connection timed out #110]' in ...
Run Code Online (Sandbox Code Playgroud)

可能是什么问题呢?我假设它与服务器设置的差异有关,因为代码在我自己的网络服务器上工作。我已经用 phpinfo() 检查了以下内容:

- Registered Stream Socket Transports   tcp, udp, unix, udg, ssl, sslv3, sslv2, tls
- OpenSSL support   enabled 
- OpenSSL Library Version   OpenSSL 1.0.1e-fips 11 Feb 2013 
Run Code Online (Sandbox Code Playgroud)

这是我的 PHP 代码:

    $emailname = MY_GMAIL_ACCOUNT_USERNAME;
    $emailpass = MY_GMAIL_ACCOUNT_PASSWORD;

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

    $mailer = Swift_Mailer::newInstance($transport);

    $message = Swift_Message::newInstance($emailtitle)
      ->setFrom(array($emailname.'@gmail.com' => $emailsender))
      ->setTo(array($emailrecp))
      ->setBody($emailbody,'text/html');

    $result = $mailer->send($message);
Run Code Online (Sandbox Code Playgroud)

小智 6

我在 Digital Ocean 服务器上遇到了同样的问题。原来他们在 IPv6 上默认阻止了 SMTP。这是修复:

nano /etc/gai.conf 优先级 ::ffff:0:0/96 100

根据:https : //www.digitalocean.com/community/questions/outgoing-connections-on-port-25-587-143-blocked-over-ipv6