linux下phpmailer发送邮件出现SMTP ERROR: Failed to connect to server: (0)错误

在做项目的过程中,后期客户提出了发送邮件的需求,既然客户有需求,那么没啥说的,上呗。

经过网上的一般资料查找,PHPMailer这个插件貌似用起来不错,那就从github clone一份来,下载链接是PHPMailer。

官当demo如下:当然相关的配置要换成你自己的

//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Set the hostname of the mail server
$mail->Host = 'smtp.qq.com';
//$mail->Host = 'smtp.163.com';
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
//$mail->SMTPAuth = false;
//$mail->SMTPSecure = false;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = 'xxxxxxx@qq.com';
//$mail->Username = 'raincowl@163.com';
//Password to use for SMTP authentication
//$mail->Password = 'lingshuan008';
$mail->Password = 'password';
//Set who the message is to be sent from
//$mail->setFrom('raincowl@163.com', 'fromuser');
$mail->setFrom('xxxxxxx@qq.com', 'fromuser');
//Set an alternative reply-to address
//$mail->addReplyTo('raincowl@163.com', 'First Last');
$mail->addReplyTo('xxxxxxx@qq.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('yyyyyyy@qq.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//$mail->msgHTML(file_get_contents('contents.html'), __DIR__);
$mail->msgHTML('hello,body!');
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');

//send the message, check for errors
if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message sent!';
}

 

首先本地windows下,发送成功,很happy,那就放上linux上试下,一运行,出现

SMTP ERROR: Failed to connect to server: (0)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

然后各大技术论坛查资料;首先检查linux服务器上的openssl和sockets已经开启,fsockopen函数也没有禁用,邮箱的smtp服务也已经开启,依然还是不行。至于有一种说法将smtp换成SMTP,是能够发送成功,后来查看下源码,发现这种只是通过sendmail发送的,不是smtp。然后,直接在linux上ping smtp.qq.com,telnet  smtp.qq.com 465都没什么问题,可是依然发送报上述的错误,后来查看官网资料,发现下面一段代码

$mail->SMTPOptions = array(
'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
    )
);

就猜测了是不是自己的ssl认证没有通过,将这段代码加上之后,神奇的事情发生了,邮件发送成功。

到此,问题圆满解决。

如有疑问,可以留言。

转载请注明出处!

posted @ 2018-04-18 16:18  raincowl  阅读(5543)  评论(3编辑  收藏  举报