简体   繁体   中英

How to stop PHP Mailer from appending all email address on every email?

I've been trying many different ways to prevent PHP Mailer from appending every email address coming from my DB to every single email.

I feel it doesn't look right for every user to receive an email from my website and being able to see a few other thousand emails appended to that same email as well.

Here's my code, I already tried to many diferent things:

$query_select = "SELECT * FROM users";
$query = mysqli_query($connection, $query_select);

if($select_to == 'all'){
    while($row = mysqli_fetch_assoc($query)) {
        $user_email = $row['user_email']; 
        $send_to = $user_email;

        $mail->setFrom('example@gmail.com', 'My website');
        $mail->addAddress($send_to); 

        $mail->isHTML(true);
        $mail->Subject = $subject_email;
        $mail->Body    = $content_email;
        $mail->AltBody = $content_email;
    }
} else {
    if($select_to == 'single'){
        $send_to = $to_single_email;
    }
}




if($mail->send()){
    $confirm = 'Sent.';
    $send = array(
        'confirm'=>$confirm
    );
    echo json_encode($send);

} else {
    $confirm = 'There was en error while sending this email.';
    $send = array(
        'confirm'=>$confirm
    );
    echo json_encode($send);
}

$mail->send() will send to all addresses via a single message. Instead you need to send one message per recipient.

The while() loop would be refactored similar to:

while($row = mysqli_fetch_assoc($query)) {
    $user_email = $row['user_email']; 
    $send_to = $user_email;

    $mail->setFrom('example@gmail.com', 'My website');
    $mail->addAddress($send_to); 

    $mail->isHTML(true);
    $mail->Subject = $subject_email;
    $mail->Body    = $content_email;
    $mail->AltBody = $content_email;
    $mail->send();
    $mail->clearAllRecipients();
}

The call to clearAllRecipients() will clear out the previous addresses that would otherwise accumulate via addAddress()

You'll also need to add the error checking within the loop for each call of send()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM