Advanced Transactional Email Templates

adv-email
In this tutorial, we are going to detail of email templates in magento i.e what all features magento offers inside an email template.

This tutorial is in continuation of a previous tutorial written on basics of email templates.
In the previous tutorial we saw how to create a new email template for a module and sending an email. In this email we will see all the directives and variable assignment method magento offers inside an email template.

Email Template Setup

I will repeat the steps explained in detail in the previous tutorial, to create a new email template.
First we will create our system configuration
system.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<sections>
        <customer>
        	<groups>
        		<account_share>
        			<fields>
        				<custom_template translate="label">
                            <label>Custom Email</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_email_template</source_model>
                            <sort_order>3</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </custom_template>
                        <custom_identity translate="label">
                            <label>Email Sender</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_email_identity</source_model>
                            <sort_order>4</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </custom_identity>
        			</fields>
        		</account_share>
        	</groups>
        </customer>
    </sections>
</config>

This will add two dropdown in the System -> Configuration -> Customer Configuration -> Account Sharing Options.

Magento Email Template Drop Down

Magento Email Template DropDown


config.xml
Next we will create our email template file i.e test.html inside app\locale\en_US\template\email\test.html.

<global>
    	<template>
            <email>
                <customer_account_share_custom_template translate="label" module="email">
                    <label>Custom Test Email</label>
                    <file>test.html</file>
                    <type>html</type>
                </customer_account_share_custom_template>
          	</email>
        </template>
</global>
<default>
        <customer>
            <account_share>
                <custom_identity>general</custom_identity>
                <custom_template>customer_account_share_custom_template</custom_template>
            </account_share>
        </customer>
</default>

PHP Code To Send Email

public function sendTestEmail($to,$name){
		$translate = Mage::getSingleton('core/translate');
		/* @var $translate Mage_Core_Model_Translate */
		$translate->setTranslateInline(false);

		$storeId = Mage::app()->getStore()->getId();

		Mage::getModel('core/email_template')
		->setDesignConfig(array('area' => 'frontend', 'store' => $storeId))
		->sendTransactional(
		Mage::getStoreConfig(self::XML_PATH_TEST_EMAIL, $storeId),
		Mage::getStoreConfig(self::XML_PATH_TEST_EMAIL_IDENTITY, $storeId),
		$to,
		$name,
		array('variable1'=>'Manish','object' => $this,'html'=>'manish<b>test</b>')
		);

		$translate->setTranslateInline(true);
	}

Magento offers many directive to pass dynamic information to email template, so we will see each directive below. All code related to directives is written in class Mage_Core_Model_Email_Template_Filter.

var Directive

This is used to access variable passed. Syntax for doing this
Type1

{{var variable1}}

This access the variable we passed in the array(‘variable1’=>’Manish’) in the sendTransactional() function. So the above code will print Manish in the email template.
Type2

{{var object.object_text}}

what this will do is call the function getObjectText() in object ‘object’. The object has been passed in the array() as

array('variable1'=>'Manish','object' => $this)

So in the same class from where the sendTransactional() is called, if we create a new method called getObjectText(), the value returned by this function will be shown in the email.

public function getObjectText(){
		return 'This is my text';
	}

Another extension of the above which is more commonly used is, suppose we have many variables to pass to an email template e.g the $_POST variable. So to do this in the array we will pass

array('object'=>new Varien_Object($_POST))

and in our email template we can access this by

{{var object.post_var1}}

Type3

{{var object.getName(true,'test')}}

Using this we can access the getName() function in the object ‘object’ and pass parameters as well. So if we create the function getName(), then the string returned will be displayed in the email.

public function getName($show,$name){
		if($show){
			return 'My Name is '.$name;
		}else{
			return 'My Name is manish';
		}
	}
depends Directive

depends is basically an if condition without else. Syntax is

{{depend object.shouldShow()}}
	Is Showing
{{/depend}}

The shouldShow() is a function created the object class. After the depend, we can call a function, or access a variable just like all the 3 types above.
e.g {{depend object.can_display}} , {{depend display}}

if Directive

if is same as depends, except it has an option for else condition as well.

{{if object.shouldShow2()}}
	Is Inside If
{{else}}
	Is Inside Else
{{/if}}
block Directive

This is used to directly include an entire block in the email template. Syntax is

{{block type='email/mail' object=$object}}

Here we calling the block class ‘email/mail’ and passed the block the variable $object.

<?php
class Excellence_Email_Block_Mail extends Mage_Core_Block_Template
{
	protected function _construct()
	{
		 $this->setTemplate('email/mail.phtml');
	}
}

and content of email/mail.phtml is

<?php
echo 'Content Of Template mail.phtml<br>';
echo 'Name Passed from EMail'.get_class($this->getObject());

So this is how we can call an entire block inside an email template and pass parameters to that block as well.

layout Directive

layout directive is used to load an entire layout structure in the email template. In the block directly we could only load one single block, but if we want to load multiple block and child blocks, we need to use the layout directive.

{{layout handle="email_test_layout" object=$object area='frontend'}}

in our layout file we will put in the code

<email_test_layout>
    	<block type='core/template' name='parent' template='email/testblock.phtml'>
    		<block type='core/template' template='email/testblock2.phtml' name='child' />
    	</block>
    </email_test_layout>

and code in our phtml file would be
email/testblock.phtml

<?php
echo 'Test BLock 1'; 
echo $this->getChildHtml('child');
echo $this->getObject()->getName();

email/testblock2.phtml

<br>
<?php
echo 'Test Block 2';

as you can see we can load very complex blocks and html structure using this.

skin Directive

This is used to get skin url of an image or any file inside the skin folder.

{{skin url='images/logo_email.gif'}}

this gives output http://127.0.0.1/magento16/skin/frontend/default/default/images/logo_email.gif

media Directive

This is used to get url of any file inside media folder
{{media url=’Untitled.png’}}
this gives output http://127.0.0.1/magento16/media/Untitled.png

store Directive

This is used to get any url inside a store, for an controller action.

{{store url='email' _query='k=1' test=213}}

this gives output

http://127.0.0.1/magento16/index.php/email/index/index/test/213/?k=1

htmlescape Directive

As the name suggests, it escapes the html characters.

{{htmlescape var=$html}}
config Directive

This is used to access information from System -> Configuration

{{config path='trans_email/ident_support/email'}}
custom variable Directive

This is used to access any custom variable if you have created any. You can create custom variable from System -> Custom Variables. This is a new feature introduced after magento 1.4.

{{customvar code="test123"}}

This is will return the html or plain text value of the custom variable with code ‘test1234′. Plain Text or HTML is decided based on the type of email.

protocol Directive
{{protocol}}

this will display http or https depending on the current site URL.

Default Subject Of Email

To set a default subject for the email template, we need to add this to our email template html file

This will act as the default subject.

Styling of Template

If you want to add styling to the email template do it inside, . e.g

Error... Unable to load download template. Search single-download-template.tpl in your plugin folder!

I think these is an exhaustive list of the directives, except the ‘includeDirective’. I couldn’t understand how to use this directive so didn’t include it in this blog, so if some know how to use this let me know and i will add this to the blog.
  • Manan Patel1989

    how to use this in magento to send emails ???need more info… how can i creat email themes

  • Bilar

    Firstly, great tutorial, thanks for sharing. When talking about layout directive you mentioned “in our layout file we will put in the code”. I’m not clear on where the layout file would be located for this module. Please can you explain?

  • Bilar

    Firstly, great tutorial, thanks for sharing. When talking about layout directive you mentioned “in our layout file we will put in the code”. I’m not clear on where the layout file would be located for this module. Please can you explain?

  • saneojseje

    Wow! Thank you so much for this Manish! Now I understand!

  • syle

    In Order email, i want to be a link with product, on ordered product.

  • Marc

    Hi,

    I create new email to send cart to the client, I created a new handle and declare it in the layout.xml but it is never read… this section doesn’t appear in the mail
    {{layout area=”frontend” handle=”abandonnedcarts_email_cart” quote=$quote}}in layout.xml of my theme
        

           
     
               
           
           
    best regards and thank for your excellent postMarc

  • Rand

    Thanks so much, I found this information to be very pertinent and it certainly helped me solve my problem.

  • Rick Buczynski

    Very helpful. Not many places I’ve searched could answer my questions about directives as you have. Thanks!

  • http://www.facebook.com/vinciane.tjong Vinciane Zhang

    {{layout handle=”email_test_layout” object=$object area=’frontend’}} not working in model file.. while I use it in controller Action it work perfectly.. don’t know why.. anyone can help me?
    Thx before :)

  • http://www.facebook.com/quangthieu.bk Quang Thieu

    Thank you for your sharing. It’s very helpful for me

  • SNH

    Hi, great article and finally some advanced stuff. Now: we are trying to setup a new extension that creates some values to access in email templates. So via system.xml we create a config path {{config path=’snh/emailsettings/headerlogo’}}. Now we can access these variables from email and newsletter templates.

    But!! they are not available from custom variables. And our template calls several custom variables that contain config path variables. So a variable within a variable. Somehow this does not always work. So I thought I would use method 3 described in your article to create a new model/object that I can access to get the config settings.

    Have a look @ https://github.com/seansan/SNH_EmailSettings

    But what am I doing wrong here? IT is not working