使用PHPmailer发送多封电子邮件

问题描述 投票:2回答:2

编辑:我忘记了我自己创建的SendMail();函数,这就是为什么解释开始时没有提及它的作用的原因。

尝试发送两封电子邮件时,我在使用PHPMailer(https://github.com/PHPMailer/PHPMailer)时遇到了麻烦,一个直接在另一个之后。

该脚本几乎完全是“开箱即用”的,仅作了一些修改,例如foreach循环以允许多个地址,并且一切仍然正常运行。

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

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

[以前,我使用内置的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);

以上将导致两封相同的电子邮件发送给不同的人,但是我无法轻松地使用PHPmailer复制此功能。

是否有一种堆叠这些请求的方式,以便我可以连续发送电子邮件而不会失败?强迫脚本等到发送第一封电子邮件之前也可以接受,尽管不是优先选择。

正如我提到的,我知道只有调用一个实例时它才有效,但是我似乎无法重用该函数。

我没有提供源代码,尽管在上面提供的链接上都可以找到。

提前感谢

根据要求编辑

// 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();

以上是我希望此方法的工作方式,因为它可以与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 = "[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";
php phpmailer
2个回答
12
投票

您尚未发布使我得出完整结论的代码,但是从Exception以及您在函数内部定义重写类的方式来看,您每次都可能会加载class.phpmailer.php,如下所示:

require('class.phpmailer.php');

include('class.phpmailer.php');

您应该将该行更改为

require_once('class.phpmailer.php');

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


0
投票

[在下面添加示例:

<?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();
}
© www.soinside.com 2019 - 2024. All rights reserved.