Sending Multiple Mails In PHP Mailer

18,132

Solution 1

I am using almost same script, but I also set this:

while(...)
{
  $mail = new PHPMailer(); //reset class instance to new one
  .....
  $mail->From = $fromAddress;   
  $mail->FromName = $fromAddress;
  $mail->AddAddress($toAdress);
  ....
}

.... - same code as you have

Solution 2

AddAddress() simply adds a new address to the end of an array of addresses. If you want to send individual emails, per-address, you'll have to clear that list on each iteration, e.g.

for(...) {
   $mail->AddAddress(...);
   $mail->send();
   $mail->ClearAddresses();  // <---you need this line.
}

If a single user is receiving multiple emails, then you'd need some code to detect when you've already sent one, e.g.:

$sent = array();
for(...) {
   if (isset($sent[$email[$i]])) {
      continue; // check if sent already, skip if so
   }
   ...
   if ($mail->send()) {
     $sent[$email[$i]] = true; // flag address as already sent
   }
}

Solution 3

Code example is here

$mail = new PHPMailer();

$body = file_get_contents('contents.html');

$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 25;
$mail->Username = '[email protected]';
$mail->Password = 'yourpassword';
$mail->setFrom('[email protected]', 'List manager');
$mail->addReplyTo('[email protected]', 'List manager');

$mail->Subject = "PHPMailer Simple database mailing list test";

//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
$mail->msgHTML($body);
//msgHTML also sets AltBody, so if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';

//Connect to the database and select the recipients from your mailing list that have not yet been sent to
//You'll need to alter this to match your database
$mysql = mysql_connect('localhost', 'username', 'password');
mysql_select_db('mydb', $mysql);
$result = mysql_query("SELECT full_name, email, photo FROM mailinglist WHERE sent = false",   $mysql);
while ($row = mysql_fetch_array($result)) {
      $mail->addAddress($row['email'], $row['full_name']);
      $mail->addStringAttachment($row['photo'], 'YourPhoto.jpg'); //Assumes the image data is stored in the DB

      if (!$mail->send()) {
         echo "Mailer Error (" . str_replace("@", "&#64;", $row["email"]) . ') ' . $mail->ErrorInfo . '<br />';
         break; //Abandon sending
      } else {
            echo "Message sent to :" . $row['full_name'] . ' (' . str_replace("@", "&#64;", $row['email']) . ')<br />';
            //Mark it as sent in the DB
            mysql_query(
             "UPDATE mailinglist SET sent = true WHERE email = '" . mysql_real_escape_string($row['email'], $mysql) . "'"
            );
      }
      // Clear all addresses and attachments for next loop
      $mail->clearAddresses();
      $mail->clearAttachments();
}
Share:
18,132
Amit Nandan Periyapatna
Author by

Amit Nandan Periyapatna

BY DAY: Software Developer at HomeSpotter developing Real Estate data solutions for clients in the USA and Canada. BY NIGHT: Open Source Web Application Developer who loves to explore new technologies and features among the vast array of free frameworks. HOBBIES: Badminton, BOOK WORM and Foodie!

Updated on June 04, 2022

Comments

  • Amit Nandan Periyapatna
    Amit Nandan Periyapatna almost 2 years

    I have been writing a trigger that mails an email using PHP mailer. The problem with the code is that it is sending multiple mails to a single recipient. I even tried using the function singleTo but even that didn't seem to work.

    $mail = new PHPMailer();
    
    for($i = 0; $i <= sizeof($emailid); $i++)   {
        $mail->WordWrap = 50;                              
        $mail->IsHTML(true);                                 
        $mail->SingleTo = true;
        $mail->AddAddress($emailid[$i],$name[$i]);
        $mail->Subject = 'Some Subject';
        $mail->Body    = "Some Body";
        $mail->AltBody = "Some Body";
    
        $errornumber[$i] = 1;
    
        if(!$mail->Send()) {
           $errorinfo[$i] = $mail->ErrorInfo;
           $errornumber[$i] = 0;
        }
    }