Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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();
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading