Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the email component from a model in CakePHP?

Tags:

php

cakephp

I have a very simple model. I want to add a send email routine to on of the methods for the model:

$this->Email->delivery = 'smtp';
$this->Email->template = 'default';
$this->Email->sendAs = 'text';     
$this->Email->from    = 'email';
$this->Email->to      = 'email';
$this->Email->subject = 'Error';

I've tried putting

App::import('Component', 'Email');

at the top, to no avail. The error I get is:

Fatal error: Call to undefined method stdClass::send() in E:\xampp\htdocs8080\app\models\debug.php on line 23

Any ideas?

I'm running CakePHP 1.2

like image 975
Justin Avatar asked Nov 23 '08 19:11

Justin


People also ask

How can I send email in cakephp 3?

use Cake\Mailer\Email; After you've loaded Email , you can send an email with the following: $email = new Email('default'); $email->from(['[email protected]' => 'My Site']) ->to('[email protected]') ->subject('About') ->send('My message');

How can I send email in cakephp 2?

Sending messages quickly Example: CakeEmail::deliver('[email protected]', 'Subject', 'Message', array('from' => '[email protected]')); This method will send an email to [email protected], from [email protected] with subject Subject and content Message. The return of deliver() is a CakeEmail instance with all configurations set.


1 Answers

even if it is not best practice, you actually can use the EmailComponent in a model, but you need to instanciate it (in the Models there is no automatic Component loading) and you need to pass it a controller. The EmailComponent relies on the Controller because of the connection it needs to the view, for rendering email templates and layouts.

With a method like this in your model

function sendEmail(&$controller) {
    App::import('Component', 'Email');
    $email = new EmailComponent();
    $email->startup($controller);
}

You can use it in your Controller like this:

$this->Model->sendEmail($this);

(omit the & in the method signature if you're on PHP5)

like image 71
nanoman Avatar answered Sep 28 '22 23:09

nanoman