5

I want to send an email with CakeEmail to multiple addresses (email address of the people who sign up in my website).

Here is my code I use :

public function send($d){
    $this->set($d);
    if($this->validates()){
        App::uses('CakeEmail','Network/Email');

        $users = $this->User->find('all');

        $this->set($tests);
        foreach($users as $user)
        {
            $tests .= '"'.$user['User']['email'].'",';
        }

        $mail = new CakeEmail();
        $mail
            ->to(array($tests)) 
            ->from(array('test2@test.fr' => 'Hello'))
            ->subject('ALERTE')
            ->emailFormat('html')
            ->template('ouverture')->viewVars($d);
            return $mail->send();

        }

    else{
        return false;
    }

    }

And here's my error :

Invalid email : ""test@test.com","test@test.fr","
rohidjetha
  • 63
  • 1
  • 1
  • 6
  • 2
    Where from the docs did you get that you can separate emails with comas? I see the option is [an array](http://api.cakephp.org/2.3/class-CakeEmail.html#_to), with the different emails as new array values, did you tried that? – Nunser Apr 29 '14 at 17:29
  • There's no need to edit the solutions into your question - these are already visible in the answers. – lethal-guitar Apr 30 '14 at 09:05
  • Thanks, it's my first time sorry – rohidjetha Apr 30 '14 at 09:21

2 Answers2

12

Try

$tests = array();
foreach($users as $user)
{
    $tests[] = $user['User']['email'];
}

$mail = new CakeEmail();
$mail->to($tests) 
     ->from(array('test2@test.fr' => 'Hello'))
     ->subject('ALERTE')
     ->emailFormat('html')
     ->send('Your message here');
evuez
  • 3,257
  • 4
  • 29
  • 44
Indrajeet Singh
  • 2,958
  • 25
  • 25
3

Try

$mail = new CakeEmail();

foreach($users as $user) {
    $mail->addTo($user['User']['email']);
}

$mail->from(array('test2@test.fr' => 'Hello'))
     ->subject('ALERTE')
     ->emailFormat('html')
     ->template('ouverture')->viewVars($d);
return $mail->send();
cornelb
  • 6,046
  • 3
  • 19
  • 30