Send email reminder with Cronjob in yii1

I need to implement a reminder to notify by email, I have read about cronjobs, but I still don’t know how to implement this with yii 1.

Hello, you can launch Yii console applications by creating console controllers in ‘commands’ directory.

class TestCommand extends CConsoleCommand
{
   public function actionFoo( $args ) { echo "Hello World\n"; }
}

that you can run with :
php -f yiic.php test foo

Hi! yes, i can do it, but when call my database, the command not work.

 class CronjobCommand extends CConsoleCommand{

	public function actionNotificarJustificativo(){
		Justificativo::model()->test();
	}

}

and in justificativo::model

    public function test(){
        	echo Justificativo::model()->findAll();

        }

I need work with database for send emails.

and in command:

The configuration file used in console mode is different from the one used for Web Application (console.php versus main.php maybe) : check the configuration file you are using.
One strange thing, that was fixed in Yii next versions is that you must declare a variable $config before invoking Yii console engine :

$config = __DIR__.'/config/console.php';
echo "*** config: $config\n";
require_once( 'yiic.php' );

where would this variable go, $config? in CronjobCommand maybe?

$config = __DIR__.'/config/console.php';
 echo "*** config: $config\n";
 require_once( 'yiic.php' );

In the yiic.php bootstrap file, should be in protected directory (CronJob.php is too late !)
Another weird stuff: there are 2 yiic.php files, the other one is in the framework.

Você é brasileiro ?

No dude, i’m Chilean, thanks for the answers but i can’t see how to resolve this. :frowning:

Are you using SQLite ? That would explain the ‘file not found’ error you are getting.
What do you have in your yiic file ?
Can you also print your database configuration as actionNotificarJustificativo() sees it, maybe with sthing like this:
echo Yii::app()->db->connectionString;
echo Yii::app()->db->userName;

Dude!! finally i can conect to my database, now i try to send an email but i have problems with the configuration i think.


thanks again for your answers!!!

Hello Eduardo, I have a similar situation, I want to send emails automatically when a date stored in the database approaches. Can you show your solution? I think it would be very helpful for others like me who are trying to do something similar and are still new to the framework. Thanks in advance and apologies for my English.

Hi Ronni! first of all you should configure the console.php

    <?php

// This is the configuration for yiic console application.
// Any writable CConsoleApplication properties can be configured here.
return array(
	'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
	'name'=>'My Console Application',

	// preloading 'log' component
	'preload'=>array('log'),
	//Importar lo que se debe usar para el cronjob en este caso envio de email por medio de un modelo.
	'import' => array(
        'application.models.*',
        'ext.yii-mail.YiiMailMessage',
        'application.extensions.*',
    ),

	// application components
	'components'=>array(
		/*'db'=>array(
			'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
		),*/
		// uncomment the following to use a MySQL database
		//Configuracion de database para conectarse desde consola
		'db' => array(
            'connectionString' => 'mysql:host=127.0.0.1;dbname=sistemaICI_2',
            'emulatePrepare' => true,
            'username' => 'usuarioICI_2',
            'password' => '1jtn8500',
            'charset' => 'utf8',
        ),
        'mail' => array(
            'class' => 'ext.yii-mail.YiiMail',
            'transportType' => 'smtp',
            'transportOptions' => array(
                'host' => 'smtp.gmail.com',
                'encryption' => 'ssl',
                'username' => 'portalactividadtitulacionici@gmail.com',
                'password' => 'adt2019!',
                'port' => 465,
            /* 'host' => 'smtp.ubiobio.cl',
              'encryption' => 'tls',
              'username' => 'sitiowebici',
              'password' => 'ponLubod.',
              'port' => 587, */
            ),
            'viewPath' => 'application.views.mails',
        ),
        //El request es necesario para mandar el email por cronjob, ingresar información del servidor
        'request' => array(
			    'hostInfo' => 'http://localhost',
			    'baseUrl' => '',
			    'scriptUrl' => '',
			),
		'log'=>array(
			'class'=>'CLogRouter',
			'routes'=>array(
				array(
					'class'=>'CFileLogRoute',
					'levels'=>'error, warning',
				),
			),
		),
	)

later you should make a commands folder and in the folder create CronjobCommand.php, in this file you should implements the logic.

<?php 
class CronjobCommand extends CConsoleCommand{

/*
	Para utilizar el Cronjob, hay que configurar de manera adecuada el archivo console.php, esto se configura según el servidor en el que esté alojada la aplicación.

	para ejecutar y probar este comando se debe escribir lo siguiente en consola:

	php yiic conjob notificarJustificativo

	Para que este código se ejecute cada cierto tiempo, hay que configurar crontab, hay que escribir lo siguiente en consola:

	crontab -e
	
	Luego de eso se abre un fichero en el que se debe configurar el tiempo de ejecucion del código.

	30 07 * * * php /dirección/de/la/aplicacion/sistemaICI/protected/yiic cronjob notificarJustificativo

	ejemplo: 30 07 * * * php /opt/lampp/htdocs/sistemaICI/protected/yiic cronjob notificarJustificativo

	Lo que hacen los primeros numeros, es que todos los días a las 07:30 de la mañana se ejecutará este código.
	El recordatorio será enviado si, el o los justificativos han sido revisados entre 6 y 14 días despues de su creacion.
	Para configurar el tiempo correctamente ingresar a https://crontab.guru/ y ver cómo hacerlo.

*/

	public function actionNotificarJustificativo(){

		Justificativo::model()->recordatorio();

	}

}

 ?>

later you should config cronjob with the next steps

To use the Cronjob file, the console.php must be properly configured, this is configured according to the server where the application is hosted.

to run and test this command you must type the following in console:

php yiic conjob notify Justification

For this code to be executed every so often, you have to configure crontab, you have to write the following in console:

crontab -e

After that a file is opened in which the code execution time must be configured.

30 07 * * * php / address / of / the / application / system ICI / protected / yiic cronjob notify Justification

example: 30 07 * * * php / opt / lampp / htdocs / sistemaICI / protected / yiic cronjob notifyJustificativo

What the first numbers do is that every day at 07:30 in the morning this code will be executed.
The reminder will be sent if the supporting document (s) have been reviewed between 6 and 14 days after its creation.
To set the time correctly, go to https://crontab.guru/ and see how to do it.

I hope it helps you, good luck!

1 Like

Thank you very much for such a quick response. I’m going to transfer it to my project. Then I’ll tell you how it went :slightly_smiling_face:

1 Like

Excellent guide. Works correctly. I made small variations to work with the phpmailer extension and windows task scheduler. Thank you very much for your help Eduardo. :ok_hand:

Nice! Good job Ronni.
Happy coding.

1 Like