我试图通过GMail的SMTP服务器从PHP页面发送电子邮件,但我得到这个错误:
身份验证失败[SMTP: SMTP服务器不支持身份验证(code: 250, response: mx.google.com at your service, [98.117.99.235] SIZE 35651584 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING)]
有人能帮忙吗?这是我的代码:
<?php
require_once "Mail.php";
$from = "Sandra Sender <sender@example.com>";
$to = "Ramona Recipient <ramona@microsoft.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
$host = "smtp.gmail.com";
$port = "587";
$username = "testtest@gmail.com";
$password = "testtest";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>
// Pear Mail Library
require_once "Mail.php";
$from = '<fromaddress@gmail.com>';
$to = '<toaddress@yahoo.com>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
$smtp = Mail::factory('smtp', array(
'host' => 'ssl://smtp.gmail.com',
'port' => '465',
'auth' => true,
'username' => 'johndoe@gmail.com',
'password' => 'passwordxxx'
));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo('<p>' . $mail->getMessage() . '</p>');
} else {
echo('<p>Message successfully sent!</p>');
}
<?php
date_default_timezone_set('America/Toronto');
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer();
$body = "gdssdh";
//$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); // telling the class to use SMTP
//$mail->Host = "ssl://smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "user@gmail.com"; // GMAIL username
$mail->Password = "password"; // GMAIL password
$mail->SetFrom('contact@prsps.in', 'PRSPS');
//$mail->AddReplyTo("user2@gmail.com', 'First Last");
$mail->Subject = "PRSPS password";
//$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$address = "user2@yahoo.co.in";
$mail->AddAddress($address, "user2");
//$mail->AddAttachment("images/phpmailer.gif"); // attachment
//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
我不推荐Pear Mail。自2010年以来就没有更新过。还要读取源文件;源代码几乎过时了,是用php4风格写的,很多错误/ bug都被贴出来了(谷歌it)。我正在使用Swift Mailer。
Swift Mailer集成到任何用PHP 5编写的web应用程序中,提供了一种灵活而优雅的面向对象的方法来发送具有多种功能的电子邮件。
使用SMTP, sendmail, postfix或自定义传输发送电子邮件
实现你自己。
支持需要用户名和密码和/或加密的服务器。
在不剥离请求数据的情况下保护头部注入攻击
内容。
发送MIME兼容的HTML/多部分电子邮件。
使用事件驱动的插件来定制库。
处理内存较低的大型附件和内联/嵌入式图像
使用。
这是一个免费的开源软件,你可以下载Swift Mailer并上传到你的服务器上。(功能列表从所有者网站复制)。
Gmail SSL/SMTP和Swift Mailer的工作示例在这里…
// Swift Mailer Library
require_once '../path/to/lib/swift_required.php';
// Mail Transport
$transport = Swift_SmtpTransport::newInstance('ssl://smtp.gmail.com', 465)
->setUsername('username@gmail.com') // Your Gmail Username
->setPassword('my_secure_gmail_password'); // Your Gmail Password
// Mailer
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject Here')
->setFrom(array('sender@example.com' => 'Sender Name')) // can be $_POST['email'] etc...
->setTo(array('receiver@example.com' => 'Receiver Name')) // your email / multiple supported.
->setBody('Here is the <strong>message</strong> itself. It can be text or <h1>HTML</h1>.', 'text/html');
// Send the message
if ($mailer->send($message)) {
echo 'Mail sent successfully.';
} else {
echo 'I am sure, your configuration are not correct. :(';
}
通过Gmail使用phpMailer库发送邮件
请从Github下载库文件
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
*/
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require '../PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "username@gmail.com";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('from@example.com', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('replyto@example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('whoto@example.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
我知道这是一个老问题,但它仍然有效,我看到的所有答案都显示了基本的身份验证,这是不推荐的。下面是一个示例,展示如何通过谷歌的Gmail服务器使用PHPMailer和XOAUTH2身份验证,使用SMTP发送电子邮件:
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
//Load dependencies from composer
//If this causes an error, run 'composer install'
require '../vendor/autoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number:
// - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
// - 587 for SMTP+STARTTLS
$mail->Port = 465;
//Set the encryption mechanism to use:
// - SMTPS (implicit TLS on port 465) or
// - STARTTLS (explicit TLS on port 587)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Set AuthType to use XOAUTH2
$mail->AuthType = 'XOAUTH2';
//Fill in authentication details here
//Either the gmail account owner, or the user that gave consent
$email = 'someone@gmail.com';
$clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com';
$clientSecret = 'RANDOMCHARS-----lGyjPcRtvP';
//Obtained by configuring and running get_oauth_token.php
//after setting up an app in Google Developer Console.
$refreshToken = 'RANDOMCHARS-----DWxgOvPT003r-yFUV49TQYag7_Aod7y0';
//Create a new OAuth2 provider instance
$provider = new Google(
[
'clientId' => $clientId,
'clientSecret' => $clientSecret,
]
);
//Pass the OAuth provider instance to PHPMailer
$mail->setOAuth(
new OAuth(
[
'provider' => $provider,
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'refreshToken' => $refreshToken,
'userName' => $email,
]
)
);
//Set who the message is to be sent from
//For gmail, this generally needs to be the same as the user you logged in as
$mail->setFrom($email, 'First Last');
//Set who the message is to be sent to
$mail->addAddress('someone@gmail.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail XOAUTH2 SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->msgHTML(file_get_contents('contentsutf8.html'), __DIR__);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message sent!';
}
参考:PHPMailer示例文件夹
自2022年5月30日起,谷歌将不再支持使用允许您使用用户名和密码登录谷歌帐户的第三方应用程序和设备。
但是,谷歌提供了一个简单的解决方案。
请输入由谷歌生成的app密码,而不是密码。首先,进入设置并启用两步验证。
然后点击App密码。
您应该看到应用程序密码屏幕。应用程序密码可以让你从不支持两步验证的设备上的应用程序登录到你的谷歌帐户。选择“邮件”作为应用程序,然后选择设备。在我的例子中,我选择了Other,因为我想将我的应用程序部署到云中。
完成后,单击GENERATE按钮。您将看到您生成的应用程序密码。
只需复制密码,并替换之前的密码在您的电子邮件发送服务生成的一个。不过,您将无法再次看到密码。
就是这样!