Search code examples
phpsqlemailphpmailer

Phpmailer - Unique email attachments


I am trying to send multiple emails with unique attachment. Currently, I am successful in sending multiple emails to different addresses from the databases.

PROBLEM: Whenever I send emails, each email sent has multiple attachments.

WHAT SHOULD BE: An email should have 1 unique attachment only. Like, [email protected] should have abc.pdf attached, [email protected] should have bnm.pdf attached, and etc.

So far, I have the code below. Maybe it's in my loop that cause the problem, or something. Please comment if you have an idea. Thanks.

$email = "select si.email_address, sr.control_no  
            from sa_student si
            left join sa_result sr on sr.control_no = si.control_no
            where schoolyear = '2013'
           ";

if ($p_address=mysql_query($email))
{ 

  while($row = mysql_fetch_array($p_address))
  {

   $mail->AddAddress($row['email_address']);

   $mail->AddAttachment("fpdf/pdf_reports/docu/".$row['control_no'].".pdf");

   }

$mail->Send();

$mail->ClearAllRecipients();

$mail->ClearAttachments();

}

Solution

  • You have to move the clear and send methods into your while loop:

    $email = "select si.email_address, sr.control_no  
            from sa_student si
            left join sa_sase_result sr on sr.control_no = si.control_no
            where schoolyear = '2013'
           ";
    
    if ($p_address=mysql_query($email))
    { 
       while($row = mysql_fetch_array($p_address))
       {
           $mail->AddAddress($row['email_address']);
           $mail->AddAttachment("fpdf/pdf_reports/docu/".$row['control_no'].".pdf");
           $mail->Send();
           $mail->ClearAllRecipients();
           $mail->ClearAttachments();
       }
    }