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認證沒有通過,將這段代碼加上之后,神奇的事情發生了,郵件發送成功。

到此,問題圓滿解決。

如有疑問,可以留言。

轉載請注明出處!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM