Features

Screenshots

Module Homepage
Module Homepage
Spool List
Spool List
Spool View
Spool View
Spool Preview
Spool Preview
Template List
Template List
Template View
Template View
Template Preview
Template Preview

Installation

Please download using ONE of the following methods:

Composer Installation

All requirements are automatically downloaded into the correct location when using composer. There is no need to download additional files or set paths to third party files.

Get composer:

curl http://getcomposer.org/installer | php

Install latest release OR development version:

php composer.phar require cornernote/yii-email-module:*            // latest release
php composer.phar require cornernote/yii-email-module:dev-master    // development version

Add the vendor folder to the aliases in your yii configuration:

return array(
    'aliases' => array(
        'vendor' => '/path/to/vendor',
    ),
);

Manual Installation

Download the latest release or development version and move the email folder into your protected/modules folder.

In addition the following are required:

Configuration

Alias

Add the email folder to the aliases in your yii configuration:

return array(
    'aliases' => array(
        'email' => '/path/to/vendor/cornernote/yii-email-module/email',
    ),
);

EmailModule

Add EmailModule to the modules in your yii configuration.

Minimum configuration:

return array(
    'modules' => array(
        'email' => array(
            'class' => 'email.EmailModule',
            'adminUsers' => array('admin'),
        ),
    ),
);

Full configuration:

return array(
    'modules' => array(
        'email' => array(
            // path to the EmailModule class
            'class' => 'email.EmailModule',

            // The ID of the CDbConnection application component. If not set, a SQLite3
            // database will be automatically created in protected/runtime/email-EmailVersion.db.
            'connectionID' => 'db',

            // Whether the DB tables should be created automatically if they do not exist. Defaults to true.
            // If you already have the table created, it is recommended you set this property to be false to improve performance.
            'autoCreateTables' => true,

            // The layout used for module controllers.
            'layout' => 'email.views.layouts.column1',

            // Defines the access filters for the module.
            // The default is EmailAccessFilter which will allow any user listed in EmailModule::adminUsers to have access.
            'controllerFilters' => array(
                'emailAccess' => array('email.components.EmailAccessFilter'),
            ),

            // A list of users who can access this module.
            'adminUsers' => array('admin'),

            // The path to YiiStrap.
            // Only required if you do not want YiiStrap in your app config, for example, if you are running YiiBooster.
            // Only required if you did not install using composer.
            // Please note:
            // - You must download YiiStrap even if you are using YiiBooster in your app.
            // - When using this setting YiiStrap will only loaded in the menu interface (eg: index.php?r=menu).
            'yiiStrapPath' => '/path/to/vendor/crisu83/yiistrap',
        ),
    ),
);

EEmailManager

Add EEmailManager to the components section in your yii configuration.

Minimum configuration:

return array(
    'components' => array(
        'emailManager' => array(
            'class' => 'email.components.EEmailManager',
            'fromEmail' => 'webmaster@your.dom.ain',
        ),
    ),
);

Full configuration:

return array(
    'components' => array(
        'emailManager' => array(
            // path to the EEmailManager class
            'class' => 'email.components.EEmailManager',

            // Path to the SwiftMailer lib folder.
            // Only required if you did not install using composer.
            'swiftMailerPath' => '/path/to/vendor/swiftmailer/swiftmailer/lib',

            // Path to the Mustache src folder.
            // Only required then templateType is set to "db".
            // Only required if you did not install using composer.
            'mustachePath' => '/path/to/vendor/mustache/mustache/src',

            // Default from email address.
            'fromEmail' => 'webmaster@your.dom.ain',

            // Default from name.
            // If unset the application name is used.
            'fromName' => null,

            // Template type, can be one of: php, db.
            'templateType' => 'php',

            // When templateType=php this is the path to the email views.
            // You may copy the default templates from email/views/emails.
            'templatePath' => 'application.views.emails',

            // List of template parts that will be rendered.
            'templateFields' => array('subject', 'heading', 'message'),

            // The default layout to use for template emails.
            'defaultLayout' => 'layout_default',

            // The default transport to use.
            // For this example you can use "mail", "smtp" or "anotherSmtp".
            'defaultTransport' => 'mail',

            // A list of email transport methods, for example:
            //    array(
            //         'transport_name_or_id' => array(
            //            // the class name of the Swift_Transport subclass
            //            'class' => 'Swift_Transport',
            //            // set Swift_Transport::property1 to "my value"
            //            'property1' => 'my value',
            //            // call Swift_Transport::setProperty2("my value")
            //            'setters' => array(
            //                'property2' => 'my value',
            //            ),
            //        ),
            //    )
            'transports' => array(

                // mail transport
                'mail' => array(
                    // can be Swift_MailTransport or Swift_SmtpTransport
                    'class' => 'Swift_MailTransport',
                ),

                // smtp transport
                'smtp' => array(
                    // if you use smtp you may need to define the host, port, security and setters
                    'class' => 'Swift_SmtpTransport',
                    'host' => 'localhost',
                    'port' => 25,
                    'security' => null,
                    'setters' => array(
                        'username' => 'your_username',
                        'password' => 'your_password',
                    ),
                ),

                // another smtp transport
                'anotherSmtp' => array(
                    'class' => 'Swift_SmtpTransport',
                    'host' => 'localhost',
                    'port' => 25,
                    'security' => null,
                    'setters' => array(
                        'username' => 'another_username',
                        'password' => 'another_password',
                    ),
                ),
                
                // gmail smtp transport
                'gmailSmtp' => array(
                    'class' => 'Swift_SmtpTransport',
                    'host' => 'smtp.gmail.com',
                    'port' => 465,
                    'security' => 'ssl',
                    'setters' => array(
                        'username' => 'username@gmail.com',
                        'password' => 'password',
                    ),
                ),
            ),

        ),
    ),
);

Command Map

To use the commands that are included with yii-email-manager, add the following to the commandMap section of your yiic configuration:

return array(
    'commandMap' => array(
        'emailSpool' => 'email.commands.EmailSpoolCommand',
    ),
);

Usage

Simple Usage

Yii::app()->emailManager->email('user@dom.ain', 'test email', '<b>Hello</b> <i>World<i>!');

Using Templates

To send more complex emails you will need to use Email Templates.

You will first need to follow the instructions in extending EEmailManager.

Component

Create a new component in components/EmailManager.php:

<?php
Yii::import('email.components.EEmailManager');
class EmailManager extends EEmailManager {

    public $defaultSendNow = false;

    public function sendUserWelcome($user) {
        // build the message from the templates and layouts
        $template = 'user_welcome';
        $templateParams = array(
            'user' => $user,
        );
        $message = $this->buildTemplateMessage($template, $templateParams, 'layout_fancy');

        // get the message
        $swiftMessage = Swift_Message::newInstance($message['subject']);
        $swiftMessage->setBody($message['message'], 'text/html');
        //$swiftMessage->addPart($message['text'], 'text/plain');
        $swiftMessage->setFrom($this->fromEmail, $this->fromName);
        $swiftMessage->setTo($user->email, $user->name);

        // send the email
        if ($this->defaultSendNow)
            return Yii::app()->emailManager->deliver($swiftMessage);

        // or spool the email
        $emailSpool = $this->getEmailSpool($swiftMessage, $user);
        $emailSpool->priority = 10;
        $emailSpool->template = $template; // save template for logging and debugging purposes
        $emailSpool->transport = 'smtp'; // send using smtp
        return $emailSpool->save(false);
    }
}

PHP Templates

Subject views/emails/example/subject.php:

<?php echo 'hello' . $user->name;

Heading views/emails/example/heading.php:

<?php echo 'Hi there ' . $user->name . ', Welcome to My Application';

Message views/emails/example/message.php:

<?php echo 'Here is an <b>awesome</b> email!';

DB Templates

Subject

hello {{user.name}}

Heading

Hi there {{user.name}}, Welcome to My Application

Message

Here is an <b>awesome</b> email!

Sending the Email

Now you can send an email like this:

$user = User::model()->findByPk(123);
Yii::app()->emailManager->sendUserWelcome($user);

Sending Spooled Emails

You can send the spooled emails using the yiic command:

yiic emailSpool

Automatically Sending

Setup lockrun for overlap protection. This allows a cron job that will run every minute, with no risk of a new process starting if an existing process is running.

Add the following to your crontab:

* * * * * /usr/local/bin/lockrun --idempotent --lockfile=/path/to/app/runtime/emailSpool.lock -- /path/to/yiic emailSpool loop > /dev/null 2>&1

Extending EEmailManager

Before extending you should check the available configuration options. In many occasions you can configure the EEmailManager class to behave as you require.

If you wish to extend for more complex functionality, you can simply update the class path in your yii config to point to your own EmailManager class, all the other configuration options will still be available:

return array(
    'components' => array(
        'emailManager' => array(
            // path to the EmailManager class
            'class' => 'application.components.EmailManager',
        ),
    ),
);

For example, to make the app available to all templates and layouts, you can override buildTemplateMessage():

class EmailManager extends EEmailManager {
    public function buildTemplateMessage($template, $viewParams = array(), $layout = 'layout_default') {
        $viewParams['app'] = Yii::app();
        return parent::buildTemplateMessage($template, $viewParams, $layout);
    }
}

In your PHP templates, you can use:

<?php echo 'My app, with ID=' . $app->id . ' is named ' . $app->name . '!';

In your DB mustache templates, you can use:

My app, with ID={{app.id}} is named {{app.name}}!

Frequently Asked Questions

Each of the template parts is rendered (subject, heading and message), and then those parts become variables in the layout.

This allows features such as:

  • Consistent pretty message layouts
  • Your templates remain light with no need for any layout code
  • Easily change email layouts, for example, send the same email template in December with an xmas layout
  • Ability to prepend/append to the subject or heading at a more global level (for example if you want your site name in every email subject, you can set your layout subject to {{contents}} - My Application

For an example, let's take a look at a layout and template for a subject part:

TEMPLATE SUBJECT

Welcome {{user.username}}

LAYOUT SUBJECT

{{contents}} - My Application

GENERATED SUBJECT

Welcome cornernote - My Application

As you can see, the contents in the layout gets replaced by the parsed template subject.

No, these variables will be created internally based on your the 3 parts of the template (subject, heading and message), which will be passed into the layout.

In your layout you should use the variable {{content}} or $content to refer to the corresponding template output.

Note: Due to the rendering order:

  • {{subject}} and {{heading}} are available in the layout message,
  • {{subject}} is available in the layout header,
  • no internal variables are available in the layout subject.

Mustache replaces {{double_curly_braces}} with the htmlencoded value of the variable. You should use {{{tripple_culry_braces}}} if your variable contains HTML code.