【问题标题】:Sending multiple emails with PHPmailer使用 PHPmailer 发送多封电子邮件
【发布时间】:2014-01-03 16:45:06
【问题描述】:

编辑:我忘了我自己创建了 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";

【问题讨论】:

  • 您是否使用 same PHPMailer 对象来发送两封电子邮件?您必须为第二封电子邮件创建一个完全不同的PHPMailer 对象,或者您可以只使用AddAddress 将同一封电子邮件发送到多个地址。如果您不希望发件人看到对方,请使用密件抄送。
  • 我不知道这是否对你有帮助,但我已经收藏了这个书签,并在我使用 PHPMailer 的任何时候使用它:inmotionhosting.com/support/email/send-email-from-a-page/…
  • 我想重复使用同一个对象,是的,但我也尝试将SendMail2 创建为一个单独的函数并一个接一个地运行它们。他们仍然使用相同的文件 - class.phpmailer.php,所以我是否还必须复制与该函数有关的所有内容?
  • 感谢@Ryan,我将它作为单个函数工作,但重新使用该函数是导致问题的原因。
  • 您为什么不发布您的 broken 代码为 PHPMailer 而不仅仅是实际为您工作的代码.. 我怀疑您可能没有使用 PHPMailer正确地反对。我们可以随心所欲地查看 PHPMailer 的示例代码,但显然您编写的代码并不完全像示例一样。

标签: php phpmailer


【解决方案1】:

在下面添加了一个示例:

<?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。
【解决方案2】:

您还没有发布这段代码让我得出一个完整的结论,但是从异常和您在函数中定义覆盖类的方式来看,您可能每次都像这样加载class.phpmailer.php

require('class.phpmailer.php');

include('class.phpmailer.php');

你应该把那行改成

require_once('class.phpmailer.php');

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

【讨论】:

  • PHPMailer 现在提供了一个自动加载器,您应该使用它而不是显式加载类,只需 require 'PHPMailerAutoload.php';,它就会去寻找它需要的任何其他类。
  • 谢谢。就是这样。
【解决方案3】:

除了@Amr 最优秀的代码。 为了在 cron 中使用它,两个添加是有用的。

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

_log 功能由您决定。写入文件、数据库或任何地方。我个人已将其减少到

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

只写更精彩的消息

【讨论】:

    【解决方案4】:

    解决方案是像这样重置收件人数据:

    $Mailer->clearAddresses()
    

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

    【讨论】:

      【解决方案5】:

      $Mailer->clearAddresses()

      这是避免将多个 msj 发送给同一收件人的解决方案。

      【讨论】:

        猜你喜欢
        • 2020-02-24
        • 1970-01-01
        • 2017-06-05
        • 2017-06-27
        • 1970-01-01
        • 1970-01-01
        • 2014-04-14
        • 2011-02-08
        • 1970-01-01
        相关资源
        最近更新 更多