Pages

Wednesday, May 16, 2012

(CakePHP)(cron job shell script) Send email automatically

This blog post describe how to set email alert to your cakephp website.
For send email automatically you have to write a shell script to your web site. In cakephp we write in the app\vendors\shells folder. I wrote my.php to send email.
In app\vendors\shells\ my.php i wrote
<?php

class MyShell extends Shell {

    var $uses = array('Client');

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

        $this->Controller = & new Controller();
        $this->Email = & new EmailComponent(null);
        $this->Email->initialize($this->Controller);
        $this->Controller->ext = '.php';

        $start_date = date("Y-m-d");
        $end_date = date('Y-m-d', strtotime('+31 days'));
        $host_and_maintain_end_within_month = $this->Client->find('all', array('conditions' => array(array('Hosting_end_date between ? and ?' => array($start_date, $end_date)))));
        $this->Controller->set('clients', $host_and_maintain_end_within_month);

        $this->Email->to = 'tomail@gmail.com';  // $email[0]['User']['email'];
        $this->Email->subject = 'Expire Date Information '. $start_date;
        $this->Email->sendAs = 'html';
        $this->Email->template = 'alert';//template in app\views\elements\email\html\alert.ctp 
        $this->Email->smtpOptions = array(
            'port' => '465',
            'timeout' => '30',
            'host' => 'ssl://smtp.gmail.com',
            'username' => 'frommail@gmail.com',
            'password' => 'frompassword',
        );
        $this->Email->delivery = 'smtp';
        $this->Email->send();
    }

}
?> 

3 comments:

  1. what version of cake were you using? I am using your code, but with Cake 1.3.6 and i cannot get my variable to pass over to the template. Any ideas?

    Even if i say:
    $this->Controller->set('test','string');
    and next line say
    $this->out($this->Controller->test);

    that doesnt even work.

    ReplyDelete
  2. My friend if you see the path : you can undrestand it is for cakephp1.3

    ReplyDelete
  3. how to check if it is already working?

    ReplyDelete