Monday, February 17, 2014

How to send email in Magento and add custom template to it

While creating a local module you may sometimes required to add the send mail functionality on success of your task.
Below is the code and description on how to create a send mail and loading it with a custom template..
 
As my module is based on sending a mail on successfully creating a duplicate order. So I am adding my code in the model folder when the duplicate order is created.

Step1:
At location app/code/local/Namespace/Module/Model/order.php

Add the following code:
//Here I am passing the order object and a payment object as my requirements is to show the product and price details
 public function sendMail(Varien_Object $order, Varien_Object $paymentObj) {

        $email = $order->getCustomerEmail();
        $fName = $order->getCustomerFirstname();
        $lName = $order->getCustomerLastname();

        $customerNote = $order->getCustomerNote();
        $paymentmethod = $paymentObj->getMethod();
      
        try {

            $storeObj = Mage::getModel('core/store')->load($order->getStoreId());
            $customerEmailId = $email;
            $customerFName = $fName;
            $customerLName = $lName;

            //load the custom template to the email 
            $emailTemplate = Mage::getModel('core/email_template')
                    ->loadDefault('custom_template');
           
            // it depends on the template variables
            $emailTemplateVariables = array();
            $emailTemplateVariables['order'] = $order;
            $emailTemplateVariables['store'] = $storeObj;
            $emailTemplateVariables['payment_html'] = $method;
      

            $emailTemplate->setSenderName('Magento');
            $emailTemplate->setSenderEmail('sender.com');
            $emailTemplate->setType('html');
            $emailTemplate->setTemplateSubject('Add a subject');
            $emailTemplate->send($customerEmailId, $customerFName . $customerLName, $emailTemplateVariables);
            return true;
        } catch (Exception $e) {
            $errorMessage = $e->getMessage();
            return $errorMessage;
        }
    }
 
Step2:
At location app/code/local/Namespace/Module/etc/config.xml, add the following block of code
<config>
   <global>
       <template>
            <email>
                <custom_template  module="modulename">
                    <label>any desired  name</label>
                    <file>custom_template.html</file>  // this specifies the path where the custom template is located
                    <type>html</type>
                </custom_template>
            </email>
        </template>
     </global>
</config>
 
Step3:
At location app/locale/template/email/sales
Place your custom template file

Note: If your template file is at location app/locale/template/email, then in your config change the code:         <file>custom_template.html</file>
 

No comments:

Post a Comment