phpoopemail

How to send 2 emails


I'm trying to send emails to users who are registered on my site(like newsletter).
The problem is: I have e.g. 5 users and when I am sending email to them only the first user get email and another 4 get nothing.

 <?php
  public function sendEmail($name,$email,$text) {
   $users = $this->_mysqli->get("user",array("TRUE"));

   $headers = 'From: '.$email."\n"; 
   $headers .= 'Date: '.gmdate('D, d M Y H:i:s', time())."\n";  
   foreach($users as $user) {

 $sended = mail($user["email"],'Contact from example.com',$name.' with email    address: '.$email.' has contacted you: '.$text,$headers); 

    if($sended) {
     return true;
    }
  } 
 }
?>

Thank you for your help
I am using OOP


Solution

  • The problem is here:

    foreach($users as $user) {
    
        $sended = mail(...);     
        if($sended) {
         return true;
        }
    } 
    

    You have a loop, but you leave it at the first cycle, when it succeeded.

    I think you need this:

     <?php
      public function sendEmail($name,$email,$text) {
       $users = $this->_mysqli->get("user",array("TRUE"));
    
       $headers = 'From: '.$email."\n"; 
       $headers .= 'Date: '.gmdate('D, d M Y H:i:s', time())."\n";  
       foreach($users as $user) {
    
          $sended = mail($user["email"],'Contact from example.com',$name.' with email    address: '.$email.' has contacted you: '.$text,$headers); 
    
          if(!$sended) {
             return false;
          }
      } 
      return true;
     }
    ?>