使用PHPmailer发送多个电子邮件

3

编辑:我忘记了我自己创建了SendMail();函数,这就是为什么解释一开始没有提到它做什么。

我在使用PHPMailer (https://github.com/PHPMailer/PHPMailer)时遇到了一些问题,尝试发送两个电子邮件,一个紧接着另一个。

这个脚本基本上是默认的,只有一些修改,例如`foreach`循环以允许多个地址,而且一切正常。

但是,如果我尝试调用多个`SendMail();`实例,我会收到错误消息:

Fatal error: Cannot override final method Exception::__clone() in .... online 0

以前我使用内置的mail();函数,它允许我连续多次使用,但是使用PHPmailer似乎并不那么简单:

$to = me@me.com;
$to2 = me2@me2.com';
$headers = 'php headers etc';
$subject = 'generic subject';
$message = 'generic message';
mail($to, $subject, $message, $headers);
mail($to2, $subject, $message, $headers);

上述代码会导致相同的电子邮件发送给不同的人,但我无法使用PHPmailer轻松复制此功能。是否有一种方式可以堆叠这些请求,以便我可以连续发送电子邮件而不会出错?强制脚本等待第一个电子邮件发送也可行,尽管不是首选。正如我所提到的,当仅调用一个实例时,我知道它可以工作,但是我似乎无法重复使用该函数。我没有包含源代码,但它都可以在上面提供的链接中找到。先行感谢。
// First Email
$to = array(
'test@test.com',
 'test2@test.com',);
$subject = "Subject";
$message = $message_start.$message_ONE.$message_end;

sendMail();

// Second Email
$to = array(
'test@test.com',
 'test2@test.com',);
$subject = "Subject";
$message = $message_start.$message_TWO.$message_end;

sendMail();

以下是我希望这个功能的工作方式,就像使用mail();一样。第一个电子邮件将正常工作,而第二个电子邮件将无法正常工作。 SendMail() 代码 这是来自PHPmailer网站的代码,被定义为SendMail();。与示例唯一的区别是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 = "from@example.com";
$mail->FromName = "Mailer";
foreach($to as $to_add){
$mail->AddAddress($to_add);                  // name is optional
}
$mail->AddReplyTo("info@example.com", "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";

3
你是否在使用相同的 PHPMailer 对象发送这两封邮件?你需要为第二封邮件创建一个全新的 PHPMailer 对象,或者你可以使用 AddAddress 将同一封邮件发送到多个地址。如果你不希望发件人看到彼此的电子邮件地址,请使用 BCC。 - sjagr
我不知道这是否能帮到你,但我将其加为书签,并在使用PHPMailer时随时使用它:http://www.inmotionhosting.com/support/email/send-email-from-a-page/using-phpmailer-to-send-mail-through-php - Ryan
为什么不把你的“有问题”的PHPMailer代码发布出来,而不是只发布那些能正常工作的代码呢?我怀疑你可能没有正确地使用PHPMailer对象。我们可以看看PHPMailer的示例代码,但显然你的代码并不完全像示例那样编写。 - sjagr
正如我所说,我非常清楚 PHPMailer 代码是可行的,因为当只调用一个实例时它可以完美地工作。因此,没有损坏的代码,只有与源代码相同的工作代码。我编写的代码与 PHPMailer 没有任何关系,它只是演示我试图复制的功能。 - JoeP
是的,但我想看看您如何重复使用函数并将PHPMailer应用于自己的编程方法。如果您的代码没有出错,您就不会收到异常。您很可能正在重复使用对象,而这个类有一个异常来防止使用相同对象两次调用“Send”。 - sjagr
显示剩余6条评论
5个回答

14
你没有发布能让我完成这个结论所需的代码,但从异常以及你在函数内定义一个覆盖类的方式来看,你可能每次都是像这样加载class.phpmailer.php文件:
require('class.phpmailer.php');
或者
include('class.phpmailer.php');

你应该将那行代码改为

require_once('class.phpmailer.php');

你需要将其更改为require_once的原因是,这样当您尝试创建新的/第二个PHPMailer类时,PHP不会再次加载类文件。否则,class PHPMailer一行会抛出__clone()异常。


2
PHPMailer现在提供了一个自动加载器,您应该优先使用它来代替显式加载类,只需require 'PHPMailerAutoload.php';,它就会去查找所需的任何其他类。 - Synchro
谢谢。就这些了。 - user4651092

4

下面添加一个示例:

<?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 = 'yourname@example.com';
$mail->Password = 'yourpassword';
$mail->setFrom('list@example.com', 'List manager');
$mail->addReplyTo('list@example.com', '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();
}

很棒的解决方案,@amir。 - theking2

0

解决方案是重置收件人数据,如下所示:

$Mailer->clearAddresses()

使用您自己的变量作为 PHPMailer 的实例(而不是 $Mailer)


0

除了@Amr的优秀代码之外。 为了在cron模式下使用它,有两个附加项是有用的。

$mail-> SMTPDebug = true;
$mail-> Debugoutput = function( $str, $level ) {_log($str);};

_log函数由您决定。可以写入文件、数据库或其他地方。我个人已将其简化为

$mail-> Debugoutput = function( $str, $level ) {if( $level===3 ) {_log( $str ); } };

只写更有吸引力的信息


0

$Mailer->clearAddresses()

这是避免多条消息发送到同一收件人的解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接