如何使用CakePHP中的模型中的电子邮件组件?

Jus*_*tin 6 php cakephp

我有一个非常简单的模型.我想在模型的方法上添加一个发送电子邮件例程:

$this->Email->delivery = 'smtp';
$this->Email->template = 'default';
$this->Email->sendAs = 'text';     
$this->Email->from    = 'email';
$this->Email->to      = 'email';
$this->Email->subject = 'Error';
Run Code Online (Sandbox Code Playgroud)

我试过试试

App::import('Component', 'Email');
Run Code Online (Sandbox Code Playgroud)

在顶部,无济于事.我得到的错误是:

致命错误:在第23行的E:\ xampp\htdocs8080\app\models\debug.php中调用未定义的方法stdClass :: send()

有任何想法吗?

我正在运行CakePHP 1.2

nan*_*man 19

即使这不是最佳实践,您实际上可以在模型中使用EmailComponent,但是您需要实例化它(在模型中没有自动组件加载)并且您需要将其传递给控制器​​.EmailComponent依赖于Controller,因为它需要与视图连接,用于呈现电子邮件模板和布局.

在您的模型中使用这样的方法

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

您可以在控制器中使用它,如下所示:

$这 - >模型 - > sendEmail($本);

(如果您使用的是PHP5,请省略方法签名中的&)


Ser*_*gei 10

好吧,你做错了.您应该在AppController中放置电子邮件发送例程:

function _sendMail($to,$subject,$template) {
    $this->Email->to = $to;
    // $this->Email->bcc = array('secret@example.com'); // copies
    $this->Email->subject = $subject;
    $this->Email->replyTo = 'noreply@domain.com';
    $this->Email->from = 'MyName <noreply@domain.com>';
    $this->Email->template = $template;
    $this->Email->sendAs = 'text'; //Send as 'html', 'text' or 'both' (default is 'text')
    $this->Email->send();
}
Run Code Online (Sandbox Code Playgroud)

然后在任何控制器中使用它,如下所示:

$this->_sendMail($this->data['User']['email'],'Thanks for registering!','register');
Run Code Online (Sandbox Code Playgroud)

并且不要忘记放置

var $components = array('Email');
Run Code Online (Sandbox Code Playgroud)

在控制器中,您正在使用_sendMail函数.

  • 谢谢!"请输入至少10个字符." 是一个愚蠢的要求. (2认同)

Ran*_*ndy 7

CakePHP 2.0具有可在任何地方使用的新CakeEmail类:

http://book.cakephp.org/2.0/en/core-utility-libraries/email.html