How to send a multiple emails at a time in cakephp

AnNaMaLaI picture AnNaMaLaI · Jun 2, 2011 · Viewed 13.4k times · Source

I need to send multiple emails at a time, can any one have example? or any idea ? I need to send mail to all my site users at a time (Mail content is same for all)

Currently i using following code in a for loop

        $this->Email->from     = '<[email protected]>';
        $this->Email->to       =  $email;
        $this->Email->subject  =   $subject ;
        $this->Email->sendAs   = 'html'; 

Answer

Tim picture Tim · Jun 2, 2011

I think you have 2 possibilities:

foreach

Let's assume you have a function mail_users within your UsersController

function mail_users($subject = 'Sample subject') {
    $users = $this->User->find('all', array('fields' => array('email'));
    foreach ($users as $user) {
        $this->Email->reset();
        $this->Email->from     = '<[email protected]>';
        $this->Email->to       =  $user['email'];
        $this->Email->subject  =  $subject ;
        $this->Email->sendAs   = 'html';
        $this->Email->send('Your message body');
    }
}

In this function the $this->Email->reset() is important.

using BCC

function mail_users($subject = 'Sample subject') {
    $users = $this->User->find('all', array('fields' => array('email'));
    $bcc = '';
    foreach ($users as $user) {
        $bcc .= $user['email'].',';
    }
    $this->Email->from     = '<[email protected]>';
    $this->Email->bcc      = $bcc;
    $this->Email->subject  = $subject;
    $this->Email->sendAs   = 'html';
    $this->Email->send('Your message body');
}

Now you can just call this method with a link to /users/mail_users/subject

For more information be sure to read the manual on the Email Component.