CakePHP使用Shell cronjob的Email组件

Jas*_*ary 12 php email cakephp

我正试图从CakePHP shell发送一封电子邮件,就像你从Controller那样.

下面的大部分代码都是根据这篇关于面包店的日期文章和它的评论改编的.电子邮件正在发送,但该行$controller->set('result', $results[$i]);会抛出以下通知:

注意:未定义的属性:在第813行的/home/jmccreary/www/intranet.sazerac.com/cakephp/cake/libs/view/view.php中查看:: $ webroot

PHP注意:未定义的变量:结果在第2行的/home/jmccreary/www/intranet.sazerac.com/cakephp/app/views/elements/email/text/nea/task_reminder_it.ctp

所以我没有将任何变量传递给我的电子邮件视图.

我怎么能这样做,最好遵循Cake约定?

class NotificationShell extends Shell {
    var $uses = array('Employee', 'Task');

    function main() {
        // run if no action is passed
    }

    function nea_task_reminder() {
        // build Task to Employee relationship
        $this->Task->bindModel(array('belongsTo' => array('Employee' => array('className' => 'Employee', 'foreignKey' => 'object_id'))));
        $results = $this->Task->find('all', array('conditions' => array('application_id' => 1, 'completed_by_id' => 0), 'contain' => array('Employee' => array('Contact', 'Position'))));

        $count = count($results);
        if ($count) {
            App::import('Core', 'Controller');
            App::import('Component', 'Email');
            $controller =& new Controller();
            $email =& new EmailComponent();
            $email->startup($controller);

            // send email
            $email->from = Configure::read('Email.from');
            $email->to = 'jmccreary@whatever.com';
            $email->replyTo = 'no-reply@whatever.com';
            $email->template = 'nea/task_reminder_it';
            $email->sendAs = 'text';

            for ($i = 0; $i < $count; ++$i) {
                $email->subject = 'NEA Notification: Task Reminder for ' . $results[$i]['Employee']['Contact']['full_name'];
                $controller->set('result', $results[$i]);
                $email->send();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*nes 15

问题在于您初始化EmailComponent类的方式.如果你查看源代码,该startup()方法实际上没有一个正文,所以它什么都不做.您的控制器实际上没有分配给EmailComponent.问题不是$controller->set('results', ...);.你需要使用EmailComponent::initialize()而不是EmailComponent::startup().

$controller =& new Controller();
$email =& new EmailComponent(null);
$email->initialize($controller);
Run Code Online (Sandbox Code Playgroud)

资料来源:

  1. http://bakery.cakephp.org/articles/Jippi/2007/12/02/emailcomponent-in-a-cake-shell的评论部分
  2. EmailComponent :: startup()来源


Bra*_*och 13

如果您正在使用CakePHP 2.x,则可以EmailComponent完全抛弃并使用CakeEmail该类.

App::uses('CakeEmail', 'Network/Email');

class NotificationShell extends Shell {
    public function send() {
        $email = new CakeEmail();
    }
}
Run Code Online (Sandbox Code Playgroud)

这完全避免了在shell中加载组件的所有棘手问题.至少对于电子邮件.