Search code examples
phpmysqlemailsmtpphpmailer

send different messages to different email accounts using SMTP PHPMailer


I want to send different messages to different email accounts fetched from my Database, The email can be up to 100 emails fetched from Database and messages must be different for each email account, I tried this Code But unfortunately it sends one message to the first user only. What I made wrong in this code please help me, Thank you.

<?php
  use PHPMailer\PHPMailer\PHPMailer; 
  use PHPMailer\PHPMailer\Exception;  
  require 'class/src/Exception.php'; 
  require 'class/src/PHPMailer.php'; 
  require 'class/src/SMTP.php'; 
            $mail = new PHPMailer();
            $mail->isSMTP();
            $mail->Host     = 'mail.company.com';
            $mail->SMTPAuth = true;
            $mail->Username = '[email protected]';
            $mail->Password = '****************';
            $mail->SMTPSecure = 'ssl';
            $mail->Port     = 465;
            $mail->SMTPKeepAlive = true;
            $mail->setFrom('[email protected]', 'CompanyName');
            $mail->Subject = "Common Header of all of the Emails";
   $fetch_data = $conn->query("SELECT name, email FROM db_table WHERE status = 'Active'");
   foreach ($fetch_data as $fetched_data) {
   $name = $fetched_data['name'];
   $email = $fetched_data['email'];
  //========================= SEND IN FOREACH LOOP =========================>
            $mail->isHTML(true);
            $mail->CharSet = 'UTF-8';
            $mail->addAddress($email, $name);
            $mail->Body = " <h3>Hi $name,</h3><h4>Congrats!</h4>";
            $mail->send();
            $mail->ClearAllRecipients();  //  $mail->clearAddresses(); NOT WORKING
}
  ?>

Solution

  • Suggestion for debugging.

    <?php
    
    $fetch_data = $conn->query("SELECT name, email FROM db_table WHERE status = 'Active'");
    print_r($fetch_data); // Do you have all row you need
       foreach ($fetch_data as $fetched_data) {
       print_r($fetched_data); // Do you have all row you need
       $name = $fetched_data['name'];
       $email = $fetched_data['email'];
      //========================= SEND IN FOREACH LOOP =========================>
                $mail->isHTML(true);
                $mail->CharSet = 'UTF-8';
                $mail->addAddress($email, $name);
                $mail->Body = " <h3>Hi $name,</h3><h4>Congrats!</h4>";
                $mail->send();
                $mail->ClearAllRecipients();  //  $mail->clearAddresses(); NOT WORKING
    }