在作項目的過程當中,後期客戶提出了發送郵件的需求,既然客戶有需求,那麼沒啥說的,上唄。php
通過網上的通常資料查找,PHPMailer這個插件貌似用起來不錯,那就從github clone一份下來,下載連接是PHPMailer。html
官當demo以下:固然相關的配置要換成你本身的linux
//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上試下,一運行,出現git
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都沒什麼問題,但是依然發送報上述的錯誤,後來查看官網資料,發現下面一段代碼github
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
就猜想了是否是本身的ssl認證沒有經過,將這段代碼加上以後,神奇的事情發生了,郵件發送成功。windows
到此,問題圓滿解決。服務器
若有疑問,能夠留言。app
轉載請註明出處!socket