PhpMailer、ClearAddresses() 不起作用,消息发送给所有人

PhpMailer, ClearAddresses() won't work, message get sent to everyone

我正在尝试向不同的用户发送不同的消息。我制作了一个电子邮件地址数组,在遍历它时,我想将 message2 发送给 user2。

在重复使用同一个邮件实例时,在每次迭代开始时我都声明 $mail -> ClearAddresses(),但现在用户 2 收到用户 1 的消息,用户 2...等等。

我错过了什么地址不会在迭代开始时被清除?

谢谢!

// settings
        
$mail = new PHPMailer;
        
$mail->isSMTP();            // Set mailer to use SMTP
$mail->Host = 'xxx';        // Specify main and backup SMTP servers
$mail->SMTPAuth = true;     // Enable SMTP authentication
$mail->Username = 'xxx';    // SMTP username
$mail->Password = 'xxx';    // SMTP password
$mail->SMTPSecure = 'ssl';  // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;  
$mail->CharSet = "UTF-8";   // TCP port to connect to

function sendInvoice($mail, $addresses) {
    foreach($addresses as $recipient) {
        $mail->ClearAddresses();
        $mail->setFrom('mail@domain.eu', 'My Server');
        $mail->addAddress($recipient['email'], $recipient['name']);  // Add a recipient
        $mail->addReplyTo('mail@domain.eu', 'My Server');
        $mail->isHTML(true);
        $mail->Subject = $recipient[subject];
        //$mail->Body    = $message;
        $mail->MsgHTML($recipient[message]);        
            
        if (! $mail->send()) {
            echo 'Message could not be sent.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
        } else {                    
            //echo 'Message has been sent';
        }
    }
}

在您的代码中,更改:

$mail->ClearAddresses();

至:

$mail->ClearAllRecipients();

这应该可以解决问题。