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

Edm*_*mas 3 php email loops email-address phpmailer

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

在重用相同的邮件实例时,在每次迭代开始时我声明$mail -> ClearAddresses(),但现在 user2 获取了 user1 和 user2... 等等的消息。

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

谢谢!

// 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';
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ito*_*pus 5

在您的代码中,更改:

$mail->ClearAddresses();
Run Code Online (Sandbox Code Playgroud)

到:

$mail->ClearAllRecipients();
Run Code Online (Sandbox Code Playgroud)

这应该可以解决问题。