2016-04-01 145 views
3
<?php 

include("class.phpmailer.php"); 
include("class.smtp.php"); 

$mail = new PHPMailer(); 

$mail->IsSMTP(); // telling the class to use SMTP 
$mail->Mailer = "smtp"; 
$mail->SMTPDebug = 2; 
$mail->Host = "ssl://smtp.gmail.com"; // specify main and backup server 
$mail->Port = 587; // set the port to use 
$mail->SMTPAuth = true; // turn on SMTP authentication 
$mail->SMTPSecure = "tls"; 

$mail->Username = "[email protected]"; // SMTP username 
$mail->Password = "password"; // SMTP password 

$mail->From = "[email protected]"; 
$mail->FromName = "Webmaster"; 

$mail->AddAddress("[email protected]"); 
$mail->AddReplyTo("[email protected]", "Webmaster"); 
$mail->IsHTML(true); 

$mail->Subject = "First PHPMailer Message"; 
$mail->Body  = "Hi! \n\n This is my first e-mail sent through PHPMailer."; 
$mail->WordWrap = 50; 

if(!$mail->Send()) { 
    echo 'Message was not sent.'; 
    echo 'Mailer error: ' . $mail->ErrorInfo; 
} else { 
    echo 'Message has been sent.'; 
} 
?> 

它返回一個錯誤PHPMailer的SMTP錯誤:無法連接到服務器

2016-04-01 08:41:43 SMTP ERROR: Failed to connect to server: (0) 
2016-04-01 08:41:43 SMTP connect() failed. 

https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Message was not sent.Mailer error: SMTP connect() failed. 

https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting 

我主持我的XAMPP本地服務器上的PHP。 php.ini上的extension=php_openssl.dll已被取消推薦。

+0

您使用的是舊版本的PHPMailer的,你已經根據你的過時的示例代碼。 [獲取最新版本](https://github.com/PHPMailer/PHPMailer)並使用[提供的gmail示例](https://github.com/PHPMailer/PHPMailer/tree/master/examples)。這是**第一件事**故障排除指南(鏈接從您的錯誤信息)說要檢查,但你顯然沒有讀到。 – Synchro

+3

[通過PHP Mailer使用Gmail SMTP服務器發送電子郵件的可能的副本](https://stackoverflow.com/questions/16048347/send-email-using-gmail-smtp-server-through-php-mailer) –

回答

2

您的配置可能是錯誤的。我相信,如果您將主機更改爲smtp.gmail.com,它可能會解決您的問題。

我注意到你設置了安全tls,但你也想連接ssl。

$mail->Host = "ssl://smtp.gmail.com";改爲$mail->Host = "smtp.gmail.com";並將安全性改爲ssl。

this answer

$mail = new PHPMailer(); // create a new object 
$mail->IsSMTP(); // enable SMTP 
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only 
$mail->SMTPAuth = true; // authentication enabled 
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail 
$mail->Host = "smtp.gmail.com"; 
$mail->Port = 465; // or 587 
$mail->IsHTML(true); 
$mail->Username = "[email protected]"; 
$mail->Password = "password"; 
$mail->SetFrom("[email protected]"); 
$mail->Subject = "Test"; 
$mail->Body = "hello"; 
$mail->AddAddress("[email protected]"); 

if(!$mail->Send()) { 
    echo "Mailer Error: " . $mail->ErrorInfo; 
} else { 
    echo "Message has been sent"; 
} 
+0

這解決了連接問題。但我有一個進一步的問題,谷歌郵件似乎阻止訪問。 http://stackoverflow.com/questions/20337040/gmail-smtp-debug-error-please-log-in-via-your-web-browser這解決了安全問題 –

+0

你有什麼錯誤嗎? –

+0

請勿根據過時的示例發佈代碼。使用[PHPMailer提供的示例](https://github.com/PHPMailer/PHPMailer/tree/master/examples),因爲它們保持最新。 – Synchro

相關問題