Skip to content

Commit

Permalink
Support for console applications
Browse files Browse the repository at this point in the history
- Version 1.1
- Added support for yii console applications
- Added new examples
- Updated README
  • Loading branch information
vernes committed Feb 2, 2013
1 parent c802e34 commit fc83b55
Show file tree
Hide file tree
Showing 6 changed files with 149 additions and 21 deletions.
23 changes: 15 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,39 @@ Yii extension for sending emails with layouts using [PHPMailer](http://code.goog

* Based on latest PHPMailer (version 5.2.2 bundled)
* Supports Yii layouts and translation
* Supports web and console applications
* Send full HTML emails with embeded images
* Work with views like you usually do in Yii


## Installation
1. Copy YiiMailer folder to protected/extensions
2. Add 'ext.YiiMailer.YiiMailer' line to your imports in main yii config
2. Add 'ext.YiiMailer.YiiMailer' line to your imports in main and/or console yii config
3. Copy mail.php config file to protected/config
4. Create email layout file mail.php in protected/views/layouts/ (default path, can be changed in config)
5. Create all the views you want to use in protected/views/mail/ (default path, can be changed in config)
6. Put all images you want to embed in emails in images/mail/ (default path, can be changed in config)

## Usage

Instantiate YiiMailer in your controller controller and pass view and data array:
Instantiate YiiMailer in your controller or console command and pass view and data array:
<pre>
$mail = new YiiMailer('contact', array('message' => $model->body, 'name' => $model->name, 'description' => 'Contact form'));
$mail = new YiiMailer('contact', array('message' => 'Message to send', 'name' => 'John Doe', 'description' => 'Contact form'));
</pre>
or
<pre>
$mail = new YiiMailer();
$mail -> setView('contact');
$mail -> setData(array('message' => 'Message to send', 'name' => 'John Doe', 'description' => 'Contact form'));
</pre>
Layout is automatically set from config but you may override it with $mail->setLayout('layoutName')

Render HTML mail and set properties:
<pre>
$mail->render();
$mail->From = $model->email;
$mail->FromName = $model->name;
$mail->Subject = $model->subject;
$mail->From = '[email protected]';
$mail->FromName = 'John Doe';
$mail->Subject = 'Mail subject';
$mail->AddAddress(Yii::app()->params['adminEmail']);
</pre>
You may use all PHPMailer properties you would usually use.
Expand All @@ -46,6 +53,6 @@ if ($mail->Send()) {
}
</pre>

## Example
## Examples

View included example with standard yii contact form.
Two examples included: one for standard contact form in yii webb app and the other one for yii console app.
77 changes: 64 additions & 13 deletions YiiMailer.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
* @author Vernes Šiljegović
* @copyright Copyright (c) 2013 YiiMailer
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version 1.0, 2013-01-02
* @version 1.1, 2013-02-02
*/


Expand Down Expand Up @@ -93,12 +93,12 @@ private function setConfig($config)
* @param string $view View file
* @throws CException
*/
private function setView($view)
public function setView($view)
{
if($view!='')
{
if(!is_file(Yii::app()->controller->getViewFile($this->viewPath.'.'.$view)))
throw new CException('View '.$view.' not found');
if(!is_file($this->getViewFile($this->viewPath.'.'.$view)))
throw new CException('View "'.$view.'" not found');
$this->view=$view;
}
}
Expand All @@ -116,7 +116,7 @@ public function getView()
* Send data to be used in mail body
* @param array $data Data array
*/
private function setData($data)
public function setData($data)
{
$this->data=$data;
}
Expand All @@ -139,8 +139,8 @@ public function setLayout($layout)
{
if($layout!='')
{
if(!is_file(Yii::app()->controller->getViewFile($this->layoutPath.'.'.$layout)))
throw new CException('Layout '.$layout.' not found!');
if(!is_file($this->getViewFile($this->layoutPath.'.'.$layout)))
throw new CException('Layout "'.$layout.'" not found!');
$this->layout=$layout;
}
}
Expand All @@ -162,7 +162,7 @@ public function getLayout()
public function setViewPath($path)
{
if (!is_string($path) && !preg_match("/[a-z0-9\.]/i",$path))
throw new CException('Path '.$path.' not valid!');
throw new CException('Path "'.$path.'" not valid!');
$this->viewPath=$path;
}

Expand All @@ -183,7 +183,7 @@ public function getViewPath()
public function setLayoutPath($path)
{
if (!is_string($path) && !preg_match("/[a-z0-9\.]/i",$path))
throw new CException('Path '.$path.' not valid!');
throw new CException('Path "'.$path.'" not valid!');
$this->layoutPath=$path;
}

Expand All @@ -204,7 +204,7 @@ public function getLayoutPath()
public function setBaseDirPath($path)
{
if (!is_string($path) && !preg_match("/[a-z0-9\.]/i",$path))
throw new CException('Path '.$path.' not valid!');
throw new CException('Path "'.$path.'" not valid!');
$this->baseDirPath=$path;
}

Expand All @@ -217,13 +217,64 @@ public function getBaseDirPath()
return $this->baseDirPath;
}

/**
* Find the view file for the given view name
* @param string $viewName Name of the view
* @return string The file path or false if the file does not exist
*/
public function getViewFile($viewName)
{
//In web application, use existing method
if(isset(Yii::app()->controller))
return Yii::app()->controller->getViewFile($viewName);
//resolve the view file
//TODO: support for themes in console applications
if(empty($viewName))
return false;

$viewFile=Yii::getPathOfAlias($viewName);
if(is_file($viewFile.'.php'))
return Yii::app()->findLocalizedFile($viewFile.'.php');
else
return false;
}

/**
* Render the view file
* @param string $viewName Name of the view
* @param array $viewData Data for extraction
* @return string The rendered result
* @throws CException
*/
public function renderView($viewName,$viewData=null)
{
//resolve the file name
if(($viewFile=$this->getViewFile($viewName))!==false)
{
//use controller instance if available or create dummy controller for console applications
if(isset(Yii::app()->controller))
$controller=Yii::app()->controller;
else
$controller=new CController(__CLASS__);

//render and return the result
return $controller->renderInternal($viewFile,$viewData,true);
}
else
{
//file name does not exist
throw new CException('View "'.$viewName.'" does not exist!');
}

}

/**
* Generates HTML email, with or without layout
*/
public function render()
{
//render body
$body=Yii::app()->controller->renderPartial($this->viewPath.'.'.$this->view, $this->data, true);
$body=$this->renderView($this->viewPath.'.'.$this->view, $this->data);
if($this->layout)
{
//has layout
Expand All @@ -241,9 +292,9 @@ public function render()
* @param string $message Email message
* @param string $basedir Path for images to embed in message
*/
public function MsgHTMLWithLayout($message, $basedir = '')
protected function MsgHTMLWithLayout($message, $basedir = '')
{
$this->MsgHTML(Yii::app()->controller->renderPartial($this->layoutPath.'.'.$this->layout, array('content'=>$message,'data'=>$this->data), true), $basedir);
$this->MsgHTML($this->renderView($this->layoutPath.'.'.$this->layout, array('content'=>$message,'data'=>$this->data)), $basedir);
}

}
34 changes: 34 additions & 0 deletions example/protected/commands/CronCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
class CronCommand extends CConsoleCommand
{
public function getHelp()
{
echo "Some cron job";
}

public function run($args)
{
//Do some cron processing...
$cronResult="Cron job finished successfuly";

$mail = new YiiMailer();
//use "cron" view from views/mail
$mail->setView('cron');
$mail->setData(array('message' => $cronResult, 'name' => get_class($this), 'description' => 'Cron job', 'mailer' => $mail));
//render HTML mail, layout is set from config file or with $mail->setLayout('layoutName')
$mail->render();
//set properties as usually with PHPMailer
$mail->From = '[email protected]';
$mail->FromName = 'Console application';
$mail->Subject = $cronResult;
$mail->AddAddress('[email protected]');
//send
if ($mail->Send()) {
$mail->ClearAddresses();
echo 'Mail sent successfuly';
} else {
echo 'Error while sending email: '.$mail->ErrorInfo;
}
echo PHP_EOL;
}
}
27 changes: 27 additions & 0 deletions example/protected/config/console.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?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',
'import'=>array(
'ext.YiiMailer.YiiMailer',
),
// application components
'components'=>array(
'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),
// uncomment the following to use a MySQL database
/*
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=testdrive',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
*/
),
);
2 changes: 2 additions & 0 deletions example/protected/views/mail/contact.php
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<p>Message from <?php echo $name . ': ' . $message ?></p>

<p>You may change the content of this page by modifying the following two files:</p>
<ul>
<li>View file: <tt><?php echo __FILE__; ?></tt></li>
Expand Down
7 changes: 7 additions & 0 deletions example/protected/views/mail/cron.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<p>Message from <?php echo $name . ': ' . $message ?></p>

<p>You may change the content of this page by modifying the following two files:</p>
<ul>
<li>View file: <tt><?php echo __FILE__; ?></tt></li>
<li>Layout file: <tt><?php echo $mailer->getViewFile($mailer->getLayoutPath() . '.' . $mailer->getLayout()); ?></tt></li>
</ul>

0 comments on commit fc83b55

Please sign in to comment.