Magento – layout handle not working in custom email

ce-1.7.0.2email-templateslayouttransactional-mail

trying to send email programmaticaly with order items grid using {{layout handle="sales_email_order_items" order=$order}} but its not working. {{htmlescape var=$order.getCustomerName()}} show customer name properly.

what is missing?

following is code for email and 29 is id of template in which {{layout handle="sales_email_order_items" order=$order}} is mentioned.

Mage::app()->getLocale()->emulate($storeId);
$SalesOrder = Mage::getModel("sales/order")->load($requestParams['order_id']);
$storeEmail = Mage::getStoreConfig('trans_email/ident_custom1/email');
$storeName =  Mage::getStoreConfig('trans_email/ident_custom1/name');
$recvEmail = $CustomerName;
$recvName =  $email;
$templateId = 29;
//set data to use in array
$edata['comment'] = $ResultData->URL;
$edata['order'] = $SalesOrder;
//Core email sending code
$emailTemplate = Mage::getModel('core/email_template')->
                    addBcc('abc@example.com')->
                    sendTransactional($templateId);
$emailTemplate->getProcessedTemplate($edata);
$emailTemplate->setSenderEmail($storeEmail);
$emailTemplate->setSenderName($storeName);
$emailTemplate->setType('html');
$emailTemplate->send($recvEmail,$recvName,$edata);

Thanks in advance.

Note: If you know any good tutorial on sending email programmatically with ordered item grid. please tell me.

Best Answer

I had the exact same problem, but was able to fix it by using store emulation.

It turned out the design package was incorrect. The email was being built using the adminhtml package instead of the frontend, even though I set "area=frontend" in the {{layout}}. That didn't help.

Before sending the email, you should add:

// Start store emulation process
$appEmulation = Mage::getSingleton('core/app_emulation');
$initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId);

And after sending you should restore the original environment:

// Stop store emulation process
$appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);

Be careful to reset the environment at the end, since the design model is a singleton, it may give unexpected results later on. You should put the email sending in try-catch, and restore afterwards. Don't let an exception prevent your from restoring the environment.

Related Topic