Home > Mobile >  Problem with sending all emails to the same person when sending email with PHPMailer
Problem with sending all emails to the same person when sending email with PHPMailer

Time:02-26

I am trying to send mail to multiple emails with PHPMailer. First, I listed people's names from the table. Then I used the loop to send emails to those people. but the problem is that everyone's information goes to all emails.

PHPMailer

foreach ($id as $mailId) {
    $connect->connect('account where id=:id', array('id' => $mailId), '', 0);
    $users = $connect->connect->fetch(PDO::FETCH_ASSOC);

    $name = $users['name'];
    $mailAdres = $users['mail'];


    // ob_start();
    // include("PHPMailer/template.php");
    // $mail_template = ob_get_clean();

    $mail_template = $name;
    $mail->addAddress($mailAdres, $name);

    // $mail->addBCC($mailAdres, $name);

    //Content
    $mail->isHTML(true);
    $mail->CharSet = 'UTF-8';

    $mail->Subject = $odemeType;
    $mail->Body    = $mail_template;
    $mail->AltBody = '';
        $mail->send();
}

CodePudding user response:

You need to clear the current address once the mail is sent otherwise you are adding a new email to the existing send list each time round the loop.

foreach ($id as $mailId) {
    $connect->connect('account where id=:id', array('id' => $mailId), '', 0);
    $users = $connect->connect->fetch(PDO::FETCH_ASSOC);

    $name = $users['name'];
    $mailAdres = $users['mail'];

    $mail_template = $name;
    $mail->addAddress($mailAdres, $name);

    // $mail->addBCC($mailAdres, $name);

    //Content
    $mail->isHTML(true);
    $mail->CharSet = 'UTF-8';

    $mail->Subject = $odemeType;
    $mail->Body    = $mail_template;
    $mail->AltBody = '';
    $mail->send();

    // clear this email address before continuing the loop
    $mail->clearAddresses();
}

Note that will clear only the to address, if you also use cc and bcc you may need to do

    //Clear all recipients (to/cc/bcc) for the next iteration
    $mail->clearAllRecipients();
  • Related