Search code examples
phpphpmailer

How to show only relevant email on TO Address using php mailer


How do I hide other emails when sending emails using phpmailer? I'm getting emails from the database. The code is sending mails to all but on the headers on TO its showing all emails. Please help my code is as follows:

$stmt = $conn->prepare("SELECT * FROM subscribers");
$stmt->execute();
$results= $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row){
    $mail->addAddress($row['email']); 
}

Solution

  • You can add the send function inside the loop, however this is resource expensive on large datasets.

    $stmt = $conn->prepare("SELECT * FROM subscribers");
    $stmt->execute();
    $results= $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach($results as $row){
        $mail->addAddress($row['email']); 
        $mail->Send();
        $mail->clearAddresses();
    }
    

    You can also use this as a reference for a much more efficient way of doing this

    https://github.com/PHPMailer/PHPMailer/blob/master/examples/mailing_list.phps

    As mention by KIKO Software from the comments above, if the email is not personalized for each users then you can use $mail->addBcc($row['email']) inside the loop and send all emails on bulk.

    // add a main email address
    $mail->addAddress('an_email_here');
    foreach($results as $row){
        // then just bcc other emails.
        $mail->addBcc($row['email'])
    }
    $mail->Send()
    

    Note: this will also appear to users that the emails are just BCCed