php 使用 PHPmailer 发送多封电子邮件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20908580/
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
Sending multiple emails with PHPmailer
提问by JoeP
Edit: I forgot I'd created the SendMail();function myself, which is why the explanation doesn't mention at first what it does.
编辑:我忘了我自己创建了这个SendMail();函数,这就是为什么解释一开始没有提到它的作用。
I'm having some trouble with PHPMailer (https://github.com/PHPMailer/PHPMailer) when attempting to send two emails, one directly after the other.
尝试发送两封电子邮件时,我在使用 PHPMailer ( https://github.com/PHPMailer/PHPMailer) 时遇到了一些问题,一个接一个。
The script is almost completely 'out of the box', with only a few modifications such as a foreachloop to allow for multiple addresses, and everything still works perfectly.
该脚本几乎完全“开箱即用”,仅进行了一些修改,例如foreach允许多个地址的循环,并且一切仍然完美无缺。
However, if I attempt to call more than one instance of SendMail();I get the error message:
但是,如果我尝试调用多个实例,则会SendMail();收到错误消息:
Fatal error: Cannot override final method Exception::__clone() in .... online 0
Previously I was using the in-built mail();function, which allowed me to use it as many times as I liked in quick succession , but it doesn't appear to be that simple with PHPmailer:
以前我使用内置mail();函数,它允许我快速连续使用它,我喜欢它的次数,但使用 PHPmailer 似乎并不那么简单:
$to = [email protected];
$to2 = [email protected]';
$headers = 'php headers etc';
$subject = 'generic subject';
$message = 'generic message';
mail($to, $subject, $message, $headers);
mail($to2, $subject, $message, $headers);
The above would result in two identical emails being sent to different people, however I can't easily replicate this functionality with PHPmailer.
以上会导致两封相同的电子邮件被发送给不同的人,但是我无法使用 PHPmailer 轻松复制此功能。
Is there a way of stacking these requests so that I can send successive emails without it failing? Forcing the script to wait until the first email has been sent would also be acceptable, although not preferential.
有没有办法堆叠这些请求,以便我可以连续发送电子邮件而不会失败?强制脚本等待第一封电子邮件发送也是可以接受的,尽管不是优先考虑的。
As I mentioned I know it works when only one instance is called, but I don't seem to be able to re-use the function.
正如我提到的,我知道它在只调用一个实例时有效,但我似乎无法重用该函数。
I haven't included the source code, although it is all available on the link provided above.
我没有包含源代码,尽管它可以在上面提供的链接中找到。
Thanks in advance
提前致谢
Edit as requested
按要求编辑
// First Email
$to = array(
'[email protected]',
'[email protected]',);
$subject = "Subject";
$message = $message_start.$message_ONE.$message_end;
sendMail();
// Second Email
$to = array(
'[email protected]',
'[email protected]',);
$subject = "Subject";
$message = $message_start.$message_TWO.$message_end;
sendMail();
The above is how I want this to work, as it would work with mail();. The first email will work fine, the second will not.
以上是我希望它如何工作,因为它可以与mail();. 第一封电子邮件会正常工作,第二封不会。
SendMail() code
SendMail() 代码
This is from the PHPmailer website, and is what is defined as SendMail();. The only difference from the example is the loop for AddAddress, and the inclusion of $toas a global variable.
这是来自 PHPmailer 网站,定义为SendMail();. 与示例的唯一区别是 for 的循环AddAddress,以及$to作为全局变量的包含。
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "smtp1.example.com;smtp2.example.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "jswan"; // SMTP username
$mail->Password = "secret"; // SMTP password
$mail->From = "[email protected]";
$mail->FromName = "Mailer";
foreach($to as $to_add){
$mail->AddAddress($to_add); // name is optional
}
$mail->AddReplyTo("[email protected]", "Information");
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->AddAttachment("/var/tmp/file.tar.gz"); // add attachments
$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional name
$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";
回答by sjagr
You haven't posted this code that lets me make this a complete conclusion, but from the Exception and the way you've defined an overriding class inside a function, you probably have class.phpmailer.phploading every time like this:
你还没有发布这段代码让我得出一个完整的结论,但是从 Exception 和你在函数中定义一个覆盖类的方式,你可能class.phpmailer.php每次都像这样加载:
require('class.phpmailer.php');
or
或者
include('class.phpmailer.php');
You should change that line to
您应该将该行更改为
require_once('class.phpmailer.php');
The reason you need to change it to require_onceis so that PHP will not load the class file the second time when you try to create the new/second PHPMailerclass. Otherwise, the line class PHPMailerthrows the __clone()exception.
您需要将其更改为的原因require_once是当您尝试创建新/第二个PHPMailer类时,PHP 不会第二次加载类文件。否则,该行将class PHPMailer引发__clone()异常。
回答by Amr
Added an example below:
在下面添加了一个示例:
<?php
/**
* This example shows how to send a message to a whole list of recipients efficiently.
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
require '../vendor/autoload.php';
//Passing `true` enables PHPMailer exceptions
$mail = new PHPMailer(true);
$body = file_get_contents('contents.html');
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 25;
$mail->Username = '[email protected]';
$mail->Password = 'yourpassword';
$mail->setFrom('[email protected]', 'List manager');
$mail->addReplyTo('[email protected]', 'List manager');
$mail->Subject = 'PHPMailer Simple database mailing list test';
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
$mail->msgHTML($body);
//msgHTML also sets AltBody, but if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
//Connect to the database and select the recipients from your mailing list that have not yet been sent to
//You'll need to alter this to match your database
$mysql = mysqli_connect('localhost', 'username', 'password');
mysqli_select_db($mysql, 'mydb');
$result = mysqli_query($mysql, 'SELECT full_name, email, photo FROM mailinglist WHERE sent = FALSE');
foreach ($result as $row) {
try {
$mail->addAddress($row['email'], $row['full_name']);
} catch (Exception $e) {
echo 'Invalid address skipped: ' . htmlspecialchars($row['email']) . '<br>';
continue;
}
if (!empty($row['photo'])) {
//Assumes the image data is stored in the DB
$mail->addStringAttachment($row['photo'], 'YourPhoto.jpg');
}
try {
$mail->send();
echo 'Message sent to :' . htmlspecialchars($row['full_name']) . ' (' . htmlspecialchars($row['email']) . ')<br>';
//Mark it as sent in the DB
mysqli_query(
$mysql,
"UPDATE mailinglist SET sent = TRUE WHERE email = '" .
mysqli_real_escape_string($mysql, $row['email']) . "'"
);
} catch (Exception $e) {
echo 'Mailer Error (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
//Reset the connection to abort sending this message
//The loop will continue trying to send to the rest of the list
$mail->getSMTPInstance()->reset();
}
//Clear all addresses and attachments for the next iteration
$mail->clearAddresses();
$mail->clearAttachments();
}

