-2

I am just working with phpmailer. I would like to generate multiple messages and send them to multiple recipients. However, the generateMessage function() just send to the first recipient in recipient list. Here is my code, any helps is appreciate.

require_once("class.phpmailer.php");

set_time_limit(0);

$wh = implode("', '", $abc);
echo "aaa" . $wh;
//echo $email;
$db = DB::getInstance();
$query1 = $db->query("SELECT * FROM tablea WHERE Location IN ('$wh')");
$result1 = $query1->results();
$query2 = $db->query("SELECT * FROM tableb WHERE Location IN ('$wh')");
$result2 = $query2->results();
$query3 = $db->query("SELECT * FROM tablec");
$result3 = $query3->results();
foreach ($result3 as $b) {
  $username = $b->email;
  $password = $b->password;
  $Times = $b->P2_Time;
}
$minutePerDay = (24 * 60) / $Times;
echo $minutePerDay;
foreach ($result1 as $r) {
  $TimeP2SendE = $r->Timea;
  break;
}
foreach ($result2 as $r) {
  $TimeP2SendG = $r->Timea;
  break;
}
$currentTime = date('Y-m-d H:i:s');
$TimeDifferentE = (strtotime($currentTime) - strtotime($TimeP2SendE)) / 60;
$TimeDifferentG = (strtotime($currentTime) - strtotime($TimeP2SendG)) / 60;
if ($TimeDifferentE >= $minutePerDay or $TimeDifferentG >= $minutePerDay) {
  $mail = new PHPMailer();
  $mail->IsSMTP();
  $mail->Host = "smtp.gmail.com";
  $mail->Port = 465;
  $mail->SMTPAuth = true;
  $mail->SMTPSecure = 'ssl';
  $mail->Username = $username;
  $mail->Password = $password;
  $mail->AltBody = " ";
  $mail->From = $username;
  $mail->FromName = 'Noti';
  $mail->clearAddresses();
  $mail->AddAddress($email);
  $mail->Subject = $title;
  $mail->IsHTML(true);
  $mail->Body = '<html><body>';
  $mail->Body .= "<h3>Information  </h3>";
  $mail->Body .= '<table class="table table-border">';
  $mail->Body .= "</table>";
  $mail->Body .= "</body></html>";

  if (!$mail->Send()) {
    echo "Error sending: " . $mail->ErrorInfo;
  } else {
    echo "Letter is sent";
  }
}

I have run this function 4 times to send to 4 different recipients, however it just sends to the first recipient.

Nana Partykar
  • 10,175
  • 8
  • 43
  • 73
HaiDang
  • 11
  • 3
  • why don't you add an array containing all the contacts, being from 1 contact to any number and looping the AddAddress function for each contact. – wayzz Aug 03 '17 at 10:26
  • From Where `$email` coming in this line `$mail->AddAddress($email);` ? – Nana Partykar Aug 03 '17 at 10:27
  • Possible duplicate of [PHPmailer - Multiple sending of e-mail](https://stackoverflow.com/questions/22316358/phpmailer-multiple-sending-of-e-mail) – Ankit Singh Aug 03 '17 at 10:29
  • I know how to create an array containing all the contacts, however in my case, I don't send same email for list of recipients, For example: email A to recipient A, email B to recipient B ...... And about recipients, I have to query with multi conditions to select a right recipients, so I write another function to select email, and after that I will call the function generateMessage with email I have found. I don't write all thing in 1 functions because when it runs, it take more than 10s and get timeout error. – HaiDang Aug 04 '17 at 04:17

2 Answers2

1

You could build an array of contact objects and loop the array to add each contact like such:

foreach($contacts as $contact){
    $mail->AddAddress($contact->email);
}

This will add each contact's email and build a mailing list.

For a custom body for each recipient I generally use the following method.

function sendEmail($email, $name, $body, $altBody = null) {
        $mail = new PHPMailer;
        $mail->IsSMTP();
        $mail->Host = "smtp.gmail.com";
        $mail->Port = 465;
        $mail->SMTPAuth = true;
        $mail->SMTPSecure = 'ssl';
        $mail->Username = $username;
        $mail->Password = $password;
        $mail->From = $username;
        $mail->FromName = 'Noti';
        $mail->clearAddresses();
        $mail->Subject = $title;
        $mail->IsHTML(true);
        $mail->addAddress($email, $name);     // Add a recipient    
        $mail->Body = $message;
        $mail->AltBody = $altBody;

        if (!$mail->send()) {
            error_log($mail->ErrorInfo);
            return false;
        } else {
            return true;
        }
    }

foreach($contacts as $contact){
    //create message here
    sendEmail($contact->email, $contact->name, $message);
}
wayzz
  • 584
  • 6
  • 23
  • If I would like to send the same email for a list recipients, I will use the method same as yours, however I have multiple different email body. For example, email A to recipient A, email B to recipient B,...... about more 10 times, so what should I do in this case? – HaiDang Aug 04 '17 at 04:12
  • The important thing is Multiple Different Email to Multiple Recipients, not same Email to Multiple Recipients. – HaiDang Aug 04 '17 at 04:38
  • @HaiDang Since you have a different body for each email recipient, you will have to send a different email for each recipient. In that case what I do is create a custom function accept a number of parameters (name, email, body) and loop the list of recipients and call the function each time. – wayzz Aug 04 '17 at 05:27
  • I did it at the begin, however phpmailer just send to the first recipient of the list. I also try to send post request by using ajax contain name, body, email to another php file to call phpmailer send function, I checked it run function many times, however just the first recipient get email – HaiDang Aug 04 '17 at 06:23
  • @HaiDang do you get any error messages in your log file? Cause I use this same function for all my projects and it always works successfully. – wayzz Aug 04 '17 at 06:30
  • I hope it return error, so I can fix it, but it not return any errors or anything else. I use some macro to debug, and I see that the function is call and send successfully with the first recipients, however from the second recipient the function does not run eventhough I call it, because it not returns any thing. Do I have close port or close SMTP or close something before call the generateMessage next time – HaiDang Aug 04 '17 at 06:40
  • @HaiDang can it be you are only returning 1 contact? thus the foreach only loops once. – wayzz Aug 04 '17 at 06:46
  • I have count the number of loop and I am sure that it not loops once, and I have inserted some echo commands before calling function for sure that generate function is called many times – HaiDang Aug 04 '17 at 06:54
  • But the echo commands in generate function not work from second recipient. – HaiDang Aug 04 '17 at 06:55
  • @HaiDang Please set $mail->SMTPDebug = 2; and echo the $mail->ErrorInfo maybe you will get a clearer picture of the error. – wayzz Aug 04 '17 at 07:12
  • SMTP -> FROM SERVER: 250-smtp.gmail.com at your service, [119.17.254.105] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8 SMTP -> FROM SERVER:250 2.1.0 OK w125sm444035iof.53 - gsmtp SMTP -> FROM SERVER:250 2.1.5 OK w125sm444035iof.53 - gsmtp SMTP -> FROM SERVER:354 Go ahead w125sm444035iof.53 - gsmtp SMTP -> FROM SERVER:250 2.0.0 OK 1501832010 w125sm444035iof.53 - gsmtp – HaiDang Aug 04 '17 at 07:35
  • @HaiDang have you enabled google to allow less secure apps to access your account?https://support.google.com/accounts/answer/6010255?hl=en – wayzz Aug 04 '17 at 07:38
  • It just report for the first recipient as I said before, – HaiDang Aug 04 '17 at 07:39
  • I also enabled google to allow less secure apps to access my account – HaiDang Aug 04 '17 at 07:44
0
    require_once("class.phpmailer.php");

    set_time_limit(0);

    $wh = implode("', '", $abc);
    echo "aaa" . $wh;
    //echo $email;
    $db = DB::getInstance();
    $query1 = $db->query("SELECT * FROM tablea WHERE Location IN ('$wh')");
    $result1 = $query1->results();
    $query2 = $db->query("SELECT * FROM tableb WHERE Location IN ('$wh')");
    $result2 = $query2->results();
    $query3 = $db->query("SELECT * FROM tablec");
    $result3 = $query3->results();
    $currentTime = date('Y-m-d H:i:s');
    foreach ($result3 as $b) {
      $username = $b->email;
      $password = $b->password;
      $Times = $b->P2_Time;
    }
    $minutePerDay = (24 * 60) / $Times;
    echo $minutePerDay;
    foreach ($result1 as $r) {
      $TimeP2SendE = $r->Timea;
      $TimeDifferentE = (strtotime($currentTime) - strtotime($TimeP2SendE)) / 60;
if($TimeDifferentE >= $minutePerDay){
    sendemail($username,$password,$email,$title);
}
    }
    foreach ($result2 as $r) {
      $TimeP2SendG = $r->Timea;
     if($TimeDifferentG >= $minutePerDay){
    sendemail($username,$password,$email,$title);
}
    }

public function sendEmail($username,$password,$email,$title){
 $mail = new PHPMailer();
  $mail->IsSMTP();
  $mail->Host = "smtp.gmail.com";
  $mail->Port = 465;
  $mail->SMTPAuth = true;
  $mail->SMTPSecure = 'ssl';
  $mail->Username = $username;
  $mail->Password = $password;
  $mail->AltBody = " ";
  $mail->From = $username;
  $mail->FromName = 'Noti';
  $mail->clearAddresses();
  $mail->AddAddress($email);
  $mail->Subject = $title;
  $mail->IsHTML(true);
  $mail->Body = '<html><body>';
  $mail->Body .= "<h3>Information  </h3>";
  $mail->Body .= '<table class="table table-border">';
  $mail->Body .= "</table>";
  $mail->Body .= "</body></html>";

  if (!$mail->Send()) {
    echo "Error sending: " . $mail->ErrorInfo;
  } else {
    echo "Letter is sent";
  }
}