search
top

Custom Email Templates in Magento

Hello,

I am explaining here the method for sending custom emails using the custom email templates with variables.

1) Create an email template from Admin-end > System > Transactional Emails, for example lets put this as Template Content

<!--@vars
{
"htmlescape var=$customer.name":"Customer Name",
"var customer.email":"Customer Email"
}
@-->
Dear {{htmlescape var=$customer.name}},<br/>
Your E-mail</strong>: {{var customer.email}}

2) Suppose the id of the template created is 3

3) Below code you can write in any view file (.phtml) or in any model or controller (.php) file


<?php
				$customer = Mage::getModel('customer/customer')->load(2); //suppose the customer whose data to be fetched is 2
                if(!empty($customer))
               	{
               		$mailTemplate = Mage::getModel('core/email_template');
        			/* @var $mailTemplate Mage_Core_Model_Email_Template */

        			$translate  = Mage::getSingleton('core/translate');

               		$templateId = 3; //template for sending customer data
               		$template_collection =  $mailTemplate->load($templateId);
					$template_data = $template_collection->getData();
					if(!empty($template_data))
       				{
       					$templateId = $template_data['template_id'];
       					$mailSubject = $template_data['template_subject'];      					

       					//fetch sender data from Adminend > System > Configuration > Store Email Addresses > General Contact
                 		$from_email = Mage::getStoreConfig('trans_email/ident_general/email'); //fetch sender email
						$from_name = Mage::getStoreConfig('trans_email/ident_general/name'); //fetch sender name

       					$sender = array('name'  => $from_name,
                  						'email' => $from_email);                  				

						$vars = array('customer'=>$customer); //for replacing the variables in email with data
						/*This is optional*/
					  	$storeId = Mage::app()->getStore()->getId();
					  	$model = $mailTemplate->setReplyTo($sender['email'])->setTemplateSubject($mailSubject);
					  	$email = $customer->getEmail();
					  	$name = $customer->getName();
       		   			$model->sendTransactional($templateId, $sender, $email, $name, $vars, $storeId);
	  	 				if (!$mailTemplate->getSentSuccess()) {
			                    throw new Exception();
	  	 				}
       					$translate->setTranslateInline(true);
       				}
               	}
?>

Hope this is helpful.



One Response to “Custom Email Templates in Magento”

Leave a Reply

top