I'm trying to create an email component/model that will add an email to the database (with certain fields like, to, from, subject, message, created, modified, etc).
AFTER the data has been sucessfully saved (which it currently does), I'd like to actually send the message.
I figure this would be easiest with an afterSave() function, but I cannot get the email to send.
Here is some relevant code:
Email Model
<?php
class Email extends AppModel {
var $name = 'Email';
var $displayField = 'subject';
function afterSave() {
$this->Email->to = $this->data['Email']['email'];
$this->Email->subject = $this->data['Email']['subject'];
$this->Email->replyTo = $this->data['Email']['email'];
$this->Email->from = 'Private Message <' . $this->data['Email']['email'] . '>';
//$this->Email->template = 'simple_message';
$this->Email->send($this->data['Email']['email_text']);
}
}
add.ctp for email
<div class="universities form">
<?php echo $this->Form->create('Email');?>
<fieldset>
<legend><?php __('Add Email'); ?></legend>
<?php
echo $this->Form->input('subject');
echo $this->Form->input('email_text');
echo $this->Form->hidden('email', array('value' => $this->params['named']['contact_email']));
echo $this->Form->hidden('user_from', array('value' => $this->Session->read('User.id')));
echo $this->Form->hidden('created', array('value' => date("Y-m-d")));
echo $this->Form->hidden('modified', array('value' => date("Y-m-d")));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true));?>
</div>
Controller save code:
function add() {
if (!empty($this->data)) {
$this->Email->create();
// pr($this->data);
// die;
if ($this->Email->save($this->data)) {
$this->Session->setFlash(__('The email has been saved', true));
} else {
$this->Session->setFlash(__('The email could not be saved. Please, try again.', true));
}
}
}
Error I am getting on trying to send:
Fatal error: Call to undefined method stdClass::send() in /Users/[USER]/Sites/example_app/app/models/email.php on line 14
New Controller Code:
function add() {
if (!empty($this->data)) {
$this->Email->create();
// pr($this->data);
// die;
if ($this->Email->save($this->data)) {
$this->Session->setFlash(__('The email has been saved', true));
function _sendMail() {
$this->Email->to = $this->data['Email']['email'];
$this->Email->subject = $this->data['Email']['subject'];
$this->Email->replyTo = $this->data['Email']['email'];
$this->Email->from = 'Private Message <' . $this->data['Email']['email'] . '>';
$this->Email->sendAs = 'text'; //Send as 'html', 'text' or 'both' (default is 'text')
$email->send();
}
$this->_sendMail();
} else {
$this->Session->setFlash(__('The email could not be saved. Please, try again.', true));
}
}
}