php 使用 PHPMailer 时遇到问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13344239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Having trouble with PHPMailer
提问by Goaler444
I am trying to use PHPMailer to send a gmail email. I followed this post
我正在尝试使用 PHPMailer 发送 Gmail 电子邮件。我关注了这个帖子
In order to do this, I set up a function shown below:
为了做到这一点,我设置了一个如下所示的函数:
function sendEmail($email, $name) {
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
//IsSMTP(); // send via SMTP I commented it cos it gives an error
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = '[email protected]'; // Changed my email
$mail->Password = "password";// Changed my password
$mail->From = '[email protected]';
$mail->FromName = 'FROM NAME';
$mail->AddAddress($email);
$mail->IsHTML(true); // send as HTML
$mail->Subject = "Subject";
$mail->Body = "Body";
if (!$mail->Send()) {
return false;
} else {
return true;
}
}
Unfortunately, it keeps on returning false. Can you please tell me whats wrong with the code?
不幸的是,它一直返回 false。你能告诉我代码有什么问题吗?
Edit: The error which I am getting is shown below:
编辑:我得到的错误如下所示:
SMTP -> ERROR: Failed to connect to server: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
SMTP Error: Could not connect to SMTP host.
UPDATED CODE:
更新代码:
$Mail = new PHPMailer();
$Mail->IsSMTP(); // Use SMTP
$Mail->Host = "smtp.gmail.com"; // Sets SMTP server
$Mail->SMTPDebug = 2; // 2 to enable SMTP debug information
$Mail->SMTPAuth = TRUE; // enable SMTP authentication
$Mail->SMTPSecure = "tls"; //Secure conection
$Mail->Port = 587; // set the SMTP port
$Mail->Username = EMAIL; // SMTP account username
$Mail->Password = PASS; // SMTP account password
$Mail->Priority = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
$Mail->CharSet = 'UTF-8';
$Mail->Encoding = '8bit';
$Mail->Subject = 'SUB';
$Mail->ContentType = 'text/html; charset=utf-8\r\n';
$Mail->From = EMAIL;
$Mail->FromName = 'FROM NAME';
$Mail->WordWrap = 900; // RFC 2822 Compliant for Max 998 characters per line
$Mail->AddAddress($email); // To:
$Mail->isHTML(TRUE);
$Mail->Body = "Hi";
$Mail->AltBody = "Hi";
$Mail->Send();
$Mail->SmtpClose();
回答by Felipe Alameda A
Here is a working example:
这是一个工作示例:
<?php
function SendMail( $ToEmail, $MessageHTML, $MessageTEXT ) {
require_once ( 'class.phpmailer.php' ); // Add the path as appropriate
$Mail = new PHPMailer();
$Mail->IsSMTP(); // Use SMTP
$Mail->Host = "smtp.gmail.com"; // Sets SMTP server
$Mail->SMTPDebug = 2; // 2 to enable SMTP debug information
$Mail->SMTPAuth = TRUE; // enable SMTP authentication
$Mail->SMTPSecure = "tls"; //Secure conection
$Mail->Port = 587; // set the SMTP port
$Mail->Username = '[email protected]'; // SMTP account username
$Mail->Password = 'MyGmailPassword'; // SMTP account password
$Mail->Priority = 1; // Highest priority - Email priority (1 = High, 3 = Normal, 5 = low)
$Mail->CharSet = 'UTF-8';
$Mail->Encoding = '8bit';
$Mail->Subject = 'Test Email Using Gmail';
$Mail->ContentType = 'text/html; charset=utf-8\r\n';
$Mail->From = '[email protected]';
$Mail->FromName = 'GMail Test';
$Mail->WordWrap = 900; // RFC 2822 Compliant for Max 998 characters per line
$Mail->AddAddress( $ToEmail ); // To:
$Mail->isHTML( TRUE );
$Mail->Body = $MessageHTML;
$Mail->AltBody = $MessageTEXT;
$Mail->Send();
$Mail->SmtpClose();
if ( $Mail->IsError() ) { // ADDED - This error checking was missing
return FALSE;
}
else {
return TRUE;
}
}
$ToEmail = '[email protected]';
$ToName = 'Name';
$Send = SendMail( $ToEmail, $MessageHTML, $MessageTEXT );
if ( $Send ) {
echo "<h2> Sent OK</h2>";
}
else {
echo "<h2> ERROR</h2>";
}
die;
?>
I tried this script and had no problem sending several messages.
我试过这个脚本,发送几条消息没有问题。
UPDATED:
更新:
This is the typical response from Gmail on success:
这是 Gmail 对成功的典型响应:
SMTP -> FROM SERVER:220 mx.google.com ESMTP 20sm6345523qek.6
SMTP -> FROM SERVER: 250-mx.google.com at your service, [181.155.13.39]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250 ENHANCEDSTATUSCODES
SMTP -> FROM SERVER:220 2.0.0 Ready to start TLS
SMTP -> FROM SERVER: 250-mx.google.com at your service, [181.155.13.39]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2
250 ENHANCEDSTATUSCODES
SMTP -> FROM SERVER:250 2.1.0 OK 20sm6345523qek.6
SMTP -> FROM SERVER:250 2.1.5 OK 20sm6345523qek.6
SMTP -> FROM SERVER:354 Go ahead 20sm6345523qek.6
SMTP -> FROM SERVER:250 2.0.0 OK 1353474062 20sm6345523qek.6
SMTP -> FROM SERVER:221 2.0.0 closing connection 20sm6345523qek.6
回答by Baba
Your Code is not working because you did not set the SMTPSecureoption to sslwhich is required for gmailaccount
您的代码不起作用,因为您没有设置帐户所需的SMTPSecure选项sslgmail
include_once "/lib/phpmailer/PHPMailer.class.php";
include_once "/lib/phpmailer/SMTP.class.php";
include_once "/lib/phpmailer/POP3.class.php";
$mail = new PHPMailer(true);
$mail->IsSMTP();
try {
$mail->Host = "smtp.gmail.com";
$mail->SMTPDebug = 2;
$mail->SMTPSecure = 'ssl'; //<----------------- You missed this
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; //
$mail->Username = "[email protected]";
$mail->Password = "xxxxxx";
$mail->AddAddress('[email protected]', 'John Doe');
$mail->SetFrom('[email protected]', 'First Last');
$mail->Subject = 'This is a TEST message';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
$body = "To view the message, please use an HTML compatible email viewer!"; // automatically
$mail->MsgHTML($body);
$mail->Send();
echo "Message Sent OK</p>\n";
} catch ( phpmailerException $e ) {
echo $e->errorMessage();
} catch ( Exception $e ) {
echo $e->getMessage();
}
Output
输出
SMTP -> FROM SERVER:220 mx.google.com ESMTP q22sm2927759bkv.16
SMTP -> FROM SERVER: 250-mx.google.com at your service, [62.173.54.190] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 250 ENHANCEDSTATUSCODES
SMTP -> FROM SERVER:250 2.1.0 OK q22sm2927759bkv.16
SMTP -> FROM SERVER:250 2.1.5 OK q22sm2927759bkv.16
SMTP -> FROM SERVER:354 Go ahead q22sm2927759bkv.16
SMTP -> FROM SERVER:250 2.0.0 OK 1353341553 q22sm2927759bkv.16
Message Sent OK
回答by inigomedina
In such kinds of issues it is important to check how it runs on development environment before you deploy to production, since there are many server issues that might be related to the problem.
在此类问题中,重要的是在部署到生产之前检查它如何在开发环境中运行,因为有许多服务器问题可能与该问题相关。
Because of that before anything set debug to true and check the messages you get.
因此,在将 debug 设置为 true 并检查您收到的消息之前。
$mail->SMTPDebug = 1;
That said, common server issues in such situations are the following.
也就是说,在这种情况下常见的服务器问题如下。
Lack of SSL support in PHP. You must enable it.
Some kind of firewall might be blocking you from connecting to outbound sockets. You can check that using PHP.
PHP 中缺少 SSL 支持。您必须启用它。
某种防火墙可能会阻止您连接到出站套接字。您可以使用 PHP 进行检查。
-
——
$p = fsockopen( '127.0.0.1', <port number>, $errno, $errstr, 5 );
if ( !$p )
// port is closed or blocked
else
// port is open and available
fclose( $p );`
回答by Matzo
Try...
尝试...
<?php
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "smtp.gmail.com"; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "yourname@yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->AddReplyTo('[email protected]', 'First Last');
$mail->AddAddress('[email protected]', 'John Doe');
$mail->SetFrom('[email protected]', 'First Last');
$mail->AddReplyTo('[email protected]', 'First Last');
$mail->Subject = 'This is a TEST Message';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($obdy);
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Just replace with your configuration, set the require_once('class.phpmailer.php'); to point to the right place and replace 'contents.html' your HTML template.
只需替换您的配置,设置 require_once('class.phpmailer.php'); 指向正确的位置并替换“contents.html”您的 HTML 模板。
or
或者
Use this code if you choose not to use an HTML template...
如果您选择不使用 HTML 模板,请使用此代码...
<?php
$body ='Your HTML message should go here';
require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "smtp.gmail.com"; // sets the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "yourname@yourdomain"; // SMTP account username
$mail->Password = "yourpassword"; // SMTP account password
$mail->AddReplyTo('[email protected]', 'First Last');
$mail->AddAddress('[email protected]', 'John Doe');
$mail->SetFrom('[email protected]', 'First Last');
$mail->AddReplyTo('[email protected]', 'First Last');
$mail->Subject = 'This is a TEST message';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML($body);
$mail->AddAttachment('images/phpmailer.gif'); // attachment
$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
$mail->Send();
echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
回答by user2514863
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPDebug = 0; // This will print debugging info
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "tls"; // Connect using a TLS connection
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Encoding = '7bit'; // SMS uses 7-bit encoding
$mail->IsHTML(true); // Set email format to HTML
// Authentication
$mail->Username = "[email protected]"; // Login
$mail->Password = "xxxxxx"; // Password
//$to=
$to = "[email protected]";
$mail->Subject = "Outstanding Balance Notification "; // Subject (which isn't required)
$mail->Body = "Dear Sir / Madam";
$mail->FromName = "stackoverflow";
$mail->From = "[email protected]";
$mail->AddAddress($row["Email1"]);
try this.. :)
尝试这个.. :)
回答by saurabh agrawal
I have send mail from xampp server from localhost
我已经从本地主机的 xampp 服务器发送邮件
This code is perfectly work for me
这段代码非常适合我
1: down load phpmailer from https://github.com/PHPMailer/PHPMailer
1:从https://github.com/PHPMailer/PHPMailer下载phpmailer
2: go to xampp and search php.ini
2:去xampp并搜索php.ini
3 In php.ini search
3 在php.ini中搜索
;extension=php_openssl.dll
remove(;)
extension=php_openssl.dll
then save and restart p.c. its work
然后保存并重新启动电脑它的工作
<%php <br/>
require_once("C:\xampp\phpMailer\PHPMailer-master\class.phpmailer.php"); <br/>
$mail = new PHPMailer(); <br/>
$mail->IsSMTP(); // telling the class to use SMTP <br/>
$mail->SMTPAuth = true; // Enable SMTP authentication <br/>
$mail->SMTPSecure = 'ssl' ; <br/>
$mail->Host = "smtp.gmail.com" ;// SMTP server <br/>
$mail->Port = 465; // or 587 <br/>
$mail->Username = '[email protected]'; // SMTP username <br/>
$mail->Password = 'senderpassword'; // SMTP password <br/>
$mail -> IsHTML(true); <br/>
$mail->From = '[email protected]'; <br/>
$mail->FromName = 'sendername'; <br/>
$mail->addAddress('[email protected]','receivername'); <br/>
$mail->WordWrap = 50; <br/>
$mail->Subject = "This mail send from PhP code xampp"; <br/>
$mail->Body = "Hi! \n\n This is my first e-mail sent through PHPMailer."; <br/>
if(!$mail->Send()) { <br/>
echo 'Message was not sent.'; <br/>
echo 'Mailer error: ' . $mail->ErrorInfo; <br/>
} else <br/>
{ <br/>
echo 'Message has been sent.'; <br/>
} <br/>
?> <br/>
回答by Cesar Bielich
2019 Update phpMailer with Gmail
2019 使用 Gmail 更新 phpMailer
I know this is an old question but it still comes up in Google and I need to update the answer to this.
我知道这是一个老问题,但它仍然出现在谷歌中,我需要更新这个问题的答案。
If you are experience the issue (where many do) with phpmailer that it only works when you comment out IsSMTP()when trying to use gmail's SMTP then here is why.
如果您在使用 phpmailer 时遇到这个问题(很多人都遇到过),只有当您IsSMTP()在尝试使用 gmail 的 SMTP时注释掉它才有效,那么这就是原因。
When you comment out IsSMTP()you are telling phpmailer NOT TO USE SMTP which by default phpmailer will send the request to your local mail()instead. If you look at the emails sent at this point and look at the header of the email you will see that it is coming from your local server and not the address/domain you are trying to send it as. So yes commenting out IsSMTP()will make it work, but it really isn't. And sending from your local server that is not setup correctly will most likely result in your emails going to spam.
当您注释掉时,IsSMTP()您是在告诉 phpmailer 不要使用 SMTP,默认情况下 phpmailer 会将请求发送到您的本地mail()。如果您查看此时发送的电子邮件并查看电子邮件的标题,您将看到它来自您的本地服务器,而不是您尝试发送的地址/域。所以是的,注释掉IsSMTP()会使它起作用,但实际上不是。从未正确设置的本地服务器发送很可能会导致您的电子邮件成为垃圾邮件。
So how do I fix this
那么我该如何解决这个问题
Plain and simple you most likely are using an old version of phpmailer, you need a newer version. The easy way to tell this is how you set your Fromaddress. If it looks like this $mail->From = "[email protected]"then you are using an old version.
简单明了,您很可能正在使用旧版本的 phpmailer,您需要一个新版本。告诉这一点的简单方法是您如何设置From地址。如果看起来像这样,$mail->From = "[email protected]"那么您使用的是旧版本。
The newest versions of phpmailer defines From as $mail->setFrom("[email protected]", "First Last"). If you see that then you are using a newer version of phpmailer.
最新版本的 phpmailer 将 From 定义为$mail->setFrom("[email protected]", "First Last"). 如果您看到,那么您使用的是较新版本的 phpmailer。
How to do it right and actually make it work
如何正确地做并真正让它发挥作用
Please make sure that you have TCP OUT port for 587 on your firewall
SMTP Gmail will only work with tls/587 AND NOT ssl/465 (ssl is 1990's)
Make sure that you have allow less secure appsset correctly within gmail. If you are using a G Suite account then you will have to have your admin enable it if it isn't already.
This is a perfect example how to use the new phpmailer with gmail smtp(and yes it does work, if not then something is wrong on your end)
请确保您的防火墙上有 587 的 TCP OUT 端口
SMTP Gmail 仅适用于 tls/587 而不是 ssl/465(ssl 是 1990 年代)
确保您在 Gmail 中正确设置了允许安全性较低的应用程序。如果您使用的是 G Suite 帐户,则必须让您的管理员启用它(如果尚未启用)。
这是一个如何将新的 phpmailer 与 gmail smtp 一起使用的完美示例(是的,它确实有效,如果没有,那么您的最终出了点问题)
How to install phpmailer
如何安装phpmailer
First downloadthe latest version of phpmailer
首先下载最新版本的phpmailer
There are 2 ways to install it. Composer or manual. The manual way all you need is
有2种安装方法。作曲家或手册。您只需要手动方式
use PHPMailer\PHPMailer\PHPMailer; <-- make sure these are not in a function
use PHPMailer\PHPMailer\Exception;
require 'path/src/Exception.php';
require 'path/src/PHPMailer.php';
require 'path/src/SMTP.php';
EXAMPLE
例子
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
* This uses traditional id & password authentication - look at the gmail_xoauth.phps
* example to see how to use XOAUTH2.
* The IMAP section shows how to save this message to the 'Sent Mail' folder using IMAP commands.
*/
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'path/src/Exception.php';
require 'path/src/PHPMailer.php';
require 'path/src/SMTP.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;
//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 = "[email protected]";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('[email protected]', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('[email protected]', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('[email protected]', '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'), __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!";
//Section 2: IMAP
//Uncomment these to save your message in the 'Sent Mail' folder.
#if (save_mail($mail)) {
# echo "Message saved!";
#}
}
//Section 2: IMAP
//IMAP commands requires the PHP IMAP Extension, found at: https://php.net/manual/en/imap.setup.php
//Function to call which uses the PHP imap_*() functions to save messages: https://php.net/manual/en/book.imap.php
//You can use imap_getmailboxes($imapStream, '/imap/ssl') to get a list of available folders or labels, this can
//be useful if you are trying to get this working on a non-Gmail IMAP server.
function save_mail($mail)
{
//You can change 'Sent Mail' to any other folder or tag
$path = "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail";
//Tell your server to open an IMAP connection using the same username and password as you used for SMTP
$imapStream = imap_open($path, $mail->Username, $mail->Password);
$result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
imap_close($imapStream);
return $result;
}
?>

