Search code examples
phpemailloopsphpmaileremail-address

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


I am trying to send different messages to different users. I made an array of email addresses and while iterating through it, I want to send message2 to user2.

While reusing the same mail instance, at the beginning of each iteration I declare $mail -> ClearAddresses(), but now user2 gets the message of user1, and user2... and so one.

What am I missing that the Address won't get cleared at the beginning of the iteration?

Thanks!

// 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('[email protected]', 'My Server');
        $mail->addAddress($recipient['email'], $recipient['name']);  // Add a recipient
        $mail->addReplyTo('[email protected]', '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';
        }
    }
}

Solution

  • In your code, change:

    $mail->ClearAddresses();
    

    to:

    $mail->ClearAllRecipients();
    

    This should fix the problem.