使用Swift Mailer、GMail和PHP发送电子邮件,出现“Permission Denied”错误

11

我下载了SwiftMailer 4.1.6来使用Gmail发送电子邮件。我为此编写了以下代码。

<?php

require_once 'swiftmailer/lib/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
        ->setUsername('jomit.jmt@gmail.com')
        ->setPassword('***********');

$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Wonderful Subject')
        ->setFrom(array('jomit.jmt@gmail.com' => 'Jomit Jose'))
        ->setTo(array('jomit.jmt@gmail.com' => 'Jomit Jose'))
        ->setBody('This is the text of the mail send by Swift using SMTP transport.');

$numSent = $mailer->send($message);
printf("Sent %d messages\n", $numSent);

然后出现了以下错误:

Fatal error: Uncaught exception 'Swift_TransportException' with message 
'Connection could not be established with host smtp.gmail.com 
[Permission denied #13]' in 
/home/jomit/public_html/email_test/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php:266 

Stack trace: 

#0 /home/jomit/public_html/email_test/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php(66): 
Swift_Transport_StreamBuffer->_establishSocketConnection() 

#1 /home/jomit/public_html/email_test/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(117):   
Swift_Transport_StreamBuffer->initialize(Array) 

#2 /home/jomit/public_html/email_test/swiftmailer/lib/classes/Swift/Mailer.php(79): 
Swift_Transport_AbstractSmtpTransport->start() 

#3 /home/jomit/public_html/email_test/test.php(16): 
Swift_Mailer->send(Object(Swift_Message)) 

#4 {main} thrown in /home/jomit/public_html/email_test/swiftmailer/lib/classes/Swift/Transport/StreamBuffer.php on line 266

可能出了什么问题?


尝试使用443端口而不是465端口。 - maxjackie
@maxjackie 哎呀!它也导致了同样的错误:未捕获的异常 'Swift_TransportException',消息为 '无法与主机smtp.gmail.com建立连接[权限被拒绝#13]' - Jomoos
你的PHP设置支持SSL吗? - Álvaro González
@ÁlvaroG.Vicario phpinfo() 显示 OpenSSL 支持已启用 - Jomoos
1个回答

37

我们曾经遇到过这个问题,原因是SELinux设置阻止Apache以及PHP打开任何外部的socket连接。我们已经将其禁用,但是忘记了-P参数,所以在下一次重启时被恢复了。如果你正在使用CentOS、RHEL或其他启用了SELinux的发行版,这很可能是问题的原因。

可以使用以下命令禁用连接限制:

setsebool -P httpd_can_network_connect on

好的解决方案。对我有用。 - user2681579
1
在安装OrangeHRM时遇到了这个问题。花了我一些时间才找到这个隐藏的答案。非常感谢。 - jasperado
1
经过漫长的搜索,我找到了这篇文章,并解决了我的问题,使得flyspray无法发送电子邮件,谢谢 :) - steabert
我知道这很老,但是如果你收到一条消息,上面写着“没有受管理策略就不能设置持久布尔值”,那么请尝试运行“sudo setsebool -P httpd_can_network_connect on”。 - DarthCaniac
这让我朝着正确的方向前进。在我的PHP服务器上,我有出站连接自动封禁IP地址。我需要进去允许每一个通过smtp.office365.com的IP地址。 - jc.021286
setsebool -P httpd_can_network_connect off 是反转命令。 - dev4life

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接