如何使用php将邮件发送到使用SMTP的gmail帐户


How to send mail using php to gmail account using SMTP

我正在php中尝试使用SMTP发送邮件的代码。我正在使用xampp服务器运行php代码。我从发送邮件neelabhsingh1986@gmail.comneelabhsingh1000@gmail.com。我从这个网站和github获得了php代码。但我收到了类似的信息

SMTP错误:无法进行身份验证。无法发送消息
Mailer错误:SMTP错误:无法进行身份验证

发送邮件的Php代码

<?php
require("D:xampp/htdocs/PHPMailer_5.2.0/class.PHPMailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->Host = "smtp.gmail.com";  // specify main and backup server
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Username = "neelabhsingh1986@gmail.com";  // SMTP username
$mail->Password = "mypassword"; // SMTP password
$mail->From = "neelabhsingh1986@gmail.com";
$mail->FromName = "Neelabh Singh";
$mail->AddAddress("neelabhsingh1000@gmail.com");                  // name is optional

$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$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. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}
echo "Message has been sent";
?>

在我的设置中,我还有这个:

$mail->SMTPSecure = "ssl";
$mail->Port = 465;

请注意,您可能需要在您的帐户上授权此操作。你会收到一封来自gmail的带有链接的电子邮件。

这是我的帖子的答案。请查看链接。下载PHPMailer_5.2.0.zip并解压缩。我使用的是xampp服务器,我在D:''xamp''htdocs''中创建了名为phpMail的文件夹。我将这两个文件(class.phpmailer.phpclass.smtp.php)从phpmailer_5.2.0复制到phpMail。现在制作文件sendMail.php并粘贴以下代码。

<?php
require("class.PHPMailer.php");    
$mail = new PHPMailer();
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->Host = "smtp.gmail.com";  // specify main and backup server
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Username = "yourEmailAddress@gmail.com";  // SMTP username, sender email address
$mail->Password = "yourGmailPassword"; // SMTP password
$mail->From = "yourEmailAddress@gmail.com";
$mail->FromName = "YourName";
$mail->AddAddress("Receiver@gmail.com");                  // Write the email of receiver. Who will get the mail.

$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$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. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}
echo "Message has been sent";
?>

编写完代码后,您必须运行服务器。就我而言,这是http://localhost/phpMail/sendMail.php。当您从浏览器运行此代码时,您将收到一封关于此应用程序的邮件,如谷歌帐户:已启用对不太安全的应用程序的访问。当你单击此链接时,他们要求获得权限,如果你愿意,访问不太安全的应用程序,请单击"是"。感谢@rjdown的帮助。