I really need help with this, I'm trying for some hours to make my code to work properly but I can't.
I'll place some of my code and my outputs to easily understand what I need and what I'm getting.
As you can see in the output there are some users with more than one card, and what I need is, send one e-mail for each user with their cards, for example:
Email #1
To: test1@gmail.com
Text: 
Card 1
Email #2
To: test2@gmail.com
Text: 
Card 2
Card 3
Email #3
To: test3@gmail.com
Text: 
Card 1
Card 2
Card 4
I should send e-mails like above, but my code that I will post below is not doing it, it sends the e-mails but the first e-mail that it sends goes to test1@gmail.com and test2@gmail.com and the second e-mail goes to test3@gmai.com, and it sends one e-mail for each card instead one e-mail with all the client cards
if (!$stm)
{
    echo "";
}
else
{
    $last_email = null;
    while ($rows = $stm->fetch())
    {
        $CPersonUId = isset($rows['PersonUId']) ? $rows['PersonUId'] : NULL;
        $CType = isset($rows['CardType']) ? $rows['CardType'] : NULL;
        $CNr = isset($rows['CardNr']) ? $rows['CardNr'] : NULL;
        $CValFrom = isset($rows['ValidFrom']) ? $rows['ValidFrom'] : NULL;
        $CValUntil = isset($rows['ValidUntil']) ? $rows['ValidUntil'] : NULL;
        $CLTCCTime = isset($rows['LastTccTime']) ? $rows['LastTccTime'] : NULL;
        $CLTPEmail = isset($rows['Email']) ? $rows['Email'] : NULL;
        if ($CValUntil != NULL)
        {
            $time1 = strtotime($CValUntil);
            $mytime1 = date("d/m/Y", $time1);
            $CValUntil = $mytime1;
        }else{
            $mytime1 = $CValUntil;
        }
        if($CType == 6){
            $CType = 'Type 1';
        }elseif($CType == 5){
            $CType = 'Type 2';
        }elseif($CType == 1){
            $CType = 'Type 3';
        }
    $message = '<html><body>';
        $message .= "<p>Cartão nº<b>".$CNr."</b> válido até <b>".$mytime1." Tipo: ".$CType."</b></p>";
    $message .= '</body></html>';
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;
    $mail->Host = "test-localhost";
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'ssl'; 
    $mail->Port = "465";
    $mail->Username = "admin@gmail.com";
    $mail->Password = "passxxxxx";
    $mail->SetFrom('admin@gmail.com', 'admin');
    $mail->addReplyTo("admin@gmail.com");
    $mail->Subject    = "Subject";
    $mail->AltBody    = "Alt";
    $mail->MsgHTML($message);
        if ( $last_email == null ) {
        $last_email = $CLTPEmail;
        }
        if ( $CLTPEmail != $last_email ) {
            //echo $last_email . "</br>";
            $mail->addAddress($last_email);
             if(!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message sent!";
    }
            $last_email = $CLTPEmail;
        }
    }
    echo $last_email."</br>";
}
 
     
    