电子邮件不会在php上发送给gmaill

时间:2018-12-18 07:13:42

标签: php email smtp phpmailer

我是php的初学者,所以我编写了用于测试的代码,该代码将使用php发送电子邮件。 我正在使用“ PHPMailer-5.2.27”在php上通过SMTP发送电子邮件,但是当我运行代码时,电子邮件未发送。我不知道是什么问题。谁能帮我!

<?php

require 'phpmailer/PHPMailerAutoload.php';

$mail = new PHPMailer();
$mail->Host = "smtp.gmail.com";
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Username = "example@gmail.com";
$mail->Password = "xxxxxxxx";
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->Subject = "test mail";
$mail->Body = "just a test";
$mail->setFrom('example@gmail.com','aaaa');
$mail->addAddress('example@gmail.com');

if ($mail->send())
    echo "mail is sent";
else
    echo "something wrong ";
?>

1 个答案:

答案 0 :(得分:0)

假设您已允许您的Gmail帐户从发送电子邮件的位置授权服务器。

使用$mail->ErrorInfo;来调试您的问题,这将澄清发送电子邮件的实际失败原因是什么,您可以参考以下我共享的代码。

<?php
require "PHPMailer/PHPMailerAutoload.php";
echo !extension_loaded('openssl')?"Not Available":"Available"; //check openssl is available or not
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 2; // 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 = "mygmailaccount@gmail.com";
$mail->Password = "**********";
$mail->SetFrom("example@gmail.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("toaddress@gmail.com");

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