Skip to main content

Send emails using cronjob in Magento

Hi All !! While working on one of my project client ask me to create a cronjob which send emails to customers. Firstly, I thought it might be difficult but it was so easy. In this post we will learn it. Suppose package name is 'MyPackage' and module name is 'MyModule. MyModule is in local directory.

Following are the files on which we have to work:
1) app/code/local/MyPackage/MyModule/etc/config.xml
2) app/code/local/MyPackage/MyModule/etc/system.xml
3) app/code/local/MyPackage/MyModule/Model/Observer.php
4) app/locale/en_US/template/email/<custom_email_template>

Step 1:
1) File Name:  app/code/local/MyPackage/MyModule/etc/config.xml
Add below code inside config tag



<config> 
<crontab>
    <jobs>
        <your_cronjob_code>
            <schedule>
                <cron_expr>* * * * *</cron_expr>
            </schedule>
            <run>
                <model>MyModule/observer::MyFunction</model>
            </run>
            </your_cronjob_code>
    </jobs>
</crontab>
</config>

Here <schedule> tag shows time interval for cronjob to run.
<cron_expr>15, 30, 45 * * * *</cron_expr> means cron will run at every 15 minutes interval.
<model>MyModule/observer::MyFunction</model> means that whatever action we want to perform we can put it in MyModule's observer file. In that file MyFunction named function will have logic we want to perform.
Now we have to define which email template will be used for this cron. Add below code inside <global> tag.
       

<config>

    <global>

        <template>


            <email>
                <customer_product_email_question_notify_template translate="label" module="MyModule">
                    <label>My Email Template Label</label>
                    <file><custom_email_template></file>
                    <type>html</type>
                </customer_product_email_question_notify_template>
            </email>
        </template>
    </global>
 </config>
2) File Name: app/code/local/MyPackage/MyModule/etc/system.xml
       

<?xml version="1.0"?>
<config>
    <sections>
        <customer translate="label" module="MyModule">
            <groups>
                <product_email translate="label">
                    <label>My Product Email Label</label>
                    <frontend_type>text</frontend_type>
                    <sort_order>5</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>0</show_in_website>
                    <show_in_store>0</show_in_store>
                    <fields>
                        <custom_email_template translate="label">
                            <label>My Product Email Label</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_email_template>
                    </fields>
                </product_email>
            </groups>
        </customer>
    </sections>
</config>
Now we have defined cronjob and custom email template for our cronjob.
We have to create the MyFunction, this function will have our logic which we want to run on cron run.

3) File Name: app/code/local/MyPackage/MyModule/Model/Observer.php
       
Class MyPackage_MyModule_Model_Observer  extends Mage_Cron_Model_Observer
{
    const XML_PATH_EMAIL_TEMPLATE = 'MyModule/product_email/email_template';   
    /*
     *function already defined in config.xml
     */
    public function MyFunction()
    {
        $translate = Mage::getSingleton('core/translate');
        /* @var $translate Mage_Core_Model_Translate */
        $translate->setTranslateInline(false);
        $mailTemplate = Mage::getModel('core/email_template');

        $this->_resource = Mage::getSingleton('core/resource')->getConnection('core_write');
        $result = $this->_resource->fetchAll("SELECT QUERY");

        foreach ($result as $recipient) {
            if($recipient['email']!= '') {
            $mailTemplate->setDesignConfig(array('area'=>'frontend', 'store'=>Mage::app()->getStore()->getId()))
                ->sendTransactional(
                    Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, Mage::app()->getStore()->getId()),                    Mage::getStoreConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_IDENTITY,Mage::app()->getStore()->getId()),
                    $recipient['email'],
                    null,
                    array(  'customer'  =>null )
                );
            }
        } 


4) File Name: app/locale/en_US/template/email/<custom_email_template>
We have to create a custom template file. We will use that template file at the time of assigning email template.

Now cron is ready and we can set the time interval as per requirement.

Author: Mohit Verma
 

Comments

  1. Check your freelancer bid for this project

    https://www.freelancer.in/projects/php/Magento-Expert-Needed-for-Interview.html

    and contact me on amit12arora@gmail.com

    ReplyDelete

Post a Comment

Popular posts from this blog

Add Products to cart Programmatically in Magento

Sometimes we need to add products into cart programmatically in controller. Below is the code which you can use to add product to cart.   1) For Simple Products If you are working in magento controller and wants to add a simple product programmatically then here is the code: Suppose our product id value stored in $productId.         // Below code will create instance of cart         $cart = Mage::getModel('checkout/cart');         // This will initialize cart         $cart->init();         // Get the product collection by passing product id         $productCollection = Mage::getModel('catalog/product')->load($productId); This product collection will be required as we have to pass it at the time of adding product to cart. For adding the product we have to call addProduct() function. In this function we have to pass two parameters first is productcollection and second is an array. This array contains product id and quantity which we are going

Magento Multiple Store Setup

Many times we need to create multiple stores in magento website. In magento we create different stores to make it more local. We can access different stores using below ways: 1) Domain (e.g. www.store1.com and www.store2.com) 2) Subdomain (e.g. store1.mystore.com and store2.mystore.com) 3) Folder (e.g. mystore.com/store1/ and mystore.com/store2/) Its all upto to you which way you prefer. For all these we need to follow below steps: Step 1: Add new Magento store: It might be possible that both store have different  catalogue so to manage this. We need to make two different Base Categories. To create a new base category follow below steps: Log in to your Magento admin panel. Go to Catalog -> Manage Categories . If you want both your websites to share same “ Default Category ”, select it by clicking on it on the left. Or click Add Root Category to create a new root category different from the existing one. Once the category is selected, under the General

Quick Order Placement Form

If we want to place fast and quick order. We want to list all the product along with their categories  and price. For achieving this goal we have to follow these steps: 1) Create Template File : Create a template  file at /app/design/frontend/default/blanco/template/catalog/product/list_fast_order.phtml which will the list of all products along with their categories and Price listing. 2) Edit Layout : Before this we have to add the phtml file in catalog.xml file. 3) Get Result :  In list_fast_order.phtml file we have to show the product category wise /*assume we want to get all products of category id 5 */ $catid_1 = 5; /*we are loading all the products from category id 5 */ $_category = Mage::getModel('catalog/category')->load($catid_1); $subs = $_category->getAllChildren(true); /* Use for loop for making result array */ $result = array(); foreach($subs as $cat_id) { $category = new Mage_Catalog_Model_Category();