3

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('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';
        }
    }
}
Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
Edmond Tamas
  • 3,148
  • 9
  • 44
  • 89
  • 1
    Shouldn't you be using `->ClearAllRecipients()` ? – tlenss Nov 10 '15 at 12:19
  • Possible duplicate of [phpMailer - How do you Remove Recipients](http://stackoverflow.com/questions/10952441/phpmailer-how-do-you-remove-recipients) – tlenss Nov 10 '15 at 12:20
  • @tlenss - I have just tried about a minute, and still not clearing recipients...:( – Edmond Tamas Nov 10 '15 at 12:22
  • 1
    Make sure you're using the latest version. Look at the code for `clearAllRecipients`; It's pretty hard for it not to work! Move `addReplyTo` and `setFrom` outside your loops. Look at the mailing ist example provided with PHPMailer. – Synchro Nov 10 '15 at 12:33
  • 1
    @Synchro - Man, my iMac is making jokes. For testing, I have set one of my email as 'user1' another as 'use2'. Osx Mail is grouping conversations by default, and while the sender address was the same, it grouped all messages by the sender (mydomain.eu). I had to uncheck View ---> "Organize by conversation," now messages display only in their own mailbox (where they belong)...:) – Edmond Tamas Nov 10 '15 at 13:24

1 Answers1

6

In your code, change:

$mail->ClearAddresses();

to:

$mail->ClearAllRecipients();

This should fix the problem.

itoctopus
  • 4,133
  • 4
  • 32
  • 44