phpmailer does not connect to SMTP servers

2019-09-03 19:43发布

问题:

i've been trying to use phpmailer and tried using live.com and gmail.com but it always can't connect to SMTP server. here's the full code (i've tried live.com using smtp.live.com but i get the same problem "Message could not be sent.Mailer Error: SMTP connect() failed.")

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'my emil address';                 // SMTP username
$mail->Password = 'my password';                           // SMTP password
$mail->SMTPSecure = 'TLS';                            // Enable encryption, 'ssl' also accepted

$mail->From = 'the same email address';
$mail->FromName = 'Mailer';
//$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
$mail->addAddress('another email address');               // Name is optional
//$mail->addReplyTo('info@example.com', 'Information');
//$mail->addCC('cc@example.com');
//$mail->addBCC('bcc@example.com');

$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
//$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}

回答1:

I suspect it's because you've not set the port, and SMTPSecure should be lower case. Change this:

$mail->SMTPSecure = 'tls';
$mail->Port = 587;

Beyond that, check that you're allowed to send outbound mail by your ISP/firewall and that your DNS is working.



回答2:

Try This:

$mail->SMTPSecure = 'tls'; 
$mail->Host = 'tls://smtp.gmail.com';
$mail->Port = 587; //You have to define the Port
$mail->SMTPDebug  = 3;

Remove This:

$mail->Host = 'smtp.gmail.com'; 
$mail->SMTPSecure = 'TLS';