PR

[CakePHP] メール送信(Shell版)

pc.casey.jp » CakePHPでメール送信(標準版) :
https://pc.casey.jp/archives/2087

の続き。前回テストしたそれを、Shellから実行してみる。ただし、相変わらず日本語は使えるようにはしてない。

まず一発目のつまずきとしてcompornentsがshellでは使えないんだった。参考文献によると以下のようにすると良いらしい。

まずClassに入る前にインポートする

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

スポンサードリンク

それと、特別な意味を持つstartupを使う

 function startup(){
   $this->controller = new Controller();
   $this->Email = new EmailComponent($this);
   $this->Email->startup($this->controller);
  }

が、エラー連発

  • Notice: Undefined property: EmailComponent::$Controller in /home/ *SakuraAccount* /cake125/cake/libs/controller/components/email.php on line 362
  • Notice: Trying to get property of non-object in /home/ *SakuraAccount* /cake125/cake/libs/controller/components/email.php on line 362
  • Notice: Undefined property: EmailComponent::$Controller in /home/ *SakuraAccount* /cake125/cake/libs/controller/components/email.php on line 369
  • Notice: Trying to get property of non-object in /home/ *SakuraAccount* /cake125/cake/libs/controller/components/email.php on line 369
  • Notice: Undefined property: View::$webroot in /home/ *SakuraAccount* /cake125/cake/libs/view/view.php on line 755

更に調べると、以下のようにすると良いらしいことがわかった。正しいかどうかわからないけど、エラーは出なくなったので。。。

 function startup(){
   $this->controller =& new Controller();
   $this->Email =& new EmailComponent(null);
   $this->Email->initialize($this->controller);
  }

抜粋すると以下のような感じ。

<?php
 App::import('Core', 'Controller');
 App::import('Component', 'Email');

class ServerStatusesShell extends Shell {

 var $uses = null;

 function startup(){
  $this->controller =& new Controller();
  $this->Email =& new EmailComponent(null);
  $this->Email->initialize($this->controller);
 }

 function main(){ 
    $msg = array();
    $this->_sendMail($msg);   
 }

 function _sendMail($msg = array()){
  $this->Email->from    = 'foo';
  $this->Email->to      = 'foo';
  $this->Email->subject = 'test';
  $this->Email->template= 'template_name';

  $this->Email->sendAs  = 'text';
  $this->Email->delivery= 'smtp';
  $this->Email->smtpOptions = array(
   'port'  => '25', // 25, 587
   'timeout' => '30',
   'host'  => 'host',
   'username' => 'foo@host',
   'password' => 'PASSWORD'
  );

  $this->controller->set('msg', $msg);

  $this->Email->send();
  $this->Email->reset();  
 }
}
?>

参考文献

コメント