问题
I'm facing this issue from last three days, before this script worked perfectly. Now getting error:
SMTP ERROR: Failed to connect to server: (0) 2017-10-06 21:05:34 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 ahsanazhar12@gmail.com
Here is my script:
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->SMTPDebug = 2; // Enable verbose debug output
$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 = 'example@gmail.com'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;
$mail->setFrom('example@gmail.com', 'Your Name');
$mail->addAddress('example@gmail.com', 'My Friend');
$mail->Subject = 'First PHPMailer Message';
$mail->Body = 'Hi! This is my first e-mail sent through PHPMailer.';
if (!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
I think Gmail may have changed settings for sending emails using SMTP, or something like that.
回答1:
Finally i'm able to send emails from localhost. Here is my code.
To install:
- Download PHPMailer
- Add it to your project (i put it on root)
- Add Autoload class to your Script.
Rest of code is below
require "PHPMailer/PHPMailerAutoload.php"; $mail = new PHPMailer; $mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) ); //$mail->SMTPDebug = 2; // Enable verbose debug output $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 = 'example@gmail.com'; // SMTP username $mail->Password = 'securepass'; // SMTP password $mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 465; // TCP port to connect to //Recipients $mail->setFrom('example@gmail.com', "Mailer"); $mail->addAddress("example@gmail.com","receiver Name"); $mail->isHTML(true); $mail->Subject = "Subject"; $mail->Body = "Body"; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if( $mail->send()){ return array("msg"=>msg("success","Email has been sent.<br>")); } else { return array("msg"=>msg("error","Email can't send.Try Again<br>")); }
来源:https://stackoverflow.com/questions/46614035/smtp-connection-failed