Send custom email in Magento – Sometimes, you want to create a function that can send an email without using the built-in email feature of Magento. Let’s find out how to do that.
All things we need to to:
- Create an email template which is a html file.
- Declare that email template in config.xml file
- Build your own send email function.
Let’s do it step by step.
Contents
1. Create an email template.
Create file: /app/locale/en_US/template/email/yourmodulename/sample_email.html with simple content:
1 2 3 4 5 6 |
<div> Hello {name}, </div> <div> <p>{message}</p> </div> |
You can use your own template name and your store locale instead of “en_US”
2. Declare that email template in config.xml file.
1 2 3 4 5 6 7 8 9 10 11 |
<global> <template> <email> <yourmodulename_sample_template translate="label" module="yourmodulename"> <label>My custom module email template</label> <file>yourmodulename/sample_email.html</file> <type>html</type> </yourmodulename_sample_template> </email> </template> </global> |
3. Create your own send email function using the email template.
You can place it anywhere you want.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php function sendMyEmail(){ $store = Mage::app()->getStore(); $translate = Mage::getSingleton('core/translate'); $translate->setTranslateInline(false); // set neccessary variables' value $emailTemplateId = "yourmodulename_sample_template"; // the id you declared in config.xml file $receiverName = "Customer's Name"; $variablesInTemplate = array( 'name' => 'Mr.A','message' => 'Welcome to my store!' ) // send the email Mage::getModel('core/email_template')->sendTransactional( $emailTemplateId, $senderEmail, $receiverEmail, $receiverName, $variablesInTemplate, $store->getId() ); $translate->setTranslateInline(true); } |
You can review function ‘sendTransactional‘ of class ‘Mage_Core_Model_Email_Template‘ for details:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/** * Send transactional email to recipient * * @param int $templateId * @param string|array $sender sender information, can be declared as part of config path * @param string $email recipient email * @param string $name recipient name * @param array $vars variables which can be used in template * @param int|null $storeId * * @throws Mage_Core_Exception * * @return Mage_Core_Model_Email_Template */ public function sendTransactional($templateId, $sender, $email, $name, $vars=array(), $storeId=null) { //... } |