Accessing Custom Email Templates in Magento
Working with email templates is an essential part of managing your e-commerce store on the Magento platform. In this article, we’ll guide you through accessing and using custom email templates created by the admin panel within a custom module.
Understanding Magento’s Email Template System
Before diving into the code, let’s briefly understand how Magento handles transactional emails:
- Email Templates: The admin creates these in the backend (“Transactional Emails” section) under Stores > Configuration.
- Template IDs: Each template has a unique identifier (e.g.,
sales_email_order_template). - Email Sending: When an event triggers an email (like a new order), Magento uses the template ID to send the content.
Retrieving the Email Template
To access your custom email template within a module, you’ll need to use Magento’s core functionality:
-
Get the template ID: You already have this from when you created the template in the admin panel (e.g.,
sales_email_order_template). -
Use Magento’s
Mage_Core_Model_Email_Templatemodel:
public function sendEmail()
{
$templateId = 'sales_email_order_template'; // Replace with your template ID
$sender = array(
'name' => 'Admin Name',
'email' => 'admin@yourdomain.com',
);
$recipient = array(
'name' => 'John Doe',
'email' => 'john.doe@example.com'
);
/** @var Mage_Core_Model_Email_Template $mailTemplate */
$mailTemplate = Mage::getModel('core/email_template');
// Get the template content
$templateContent = $mailTemplate->load($templateId)->getText();
// Send the email
$mailTemplate->sendMail($sender['email'], $recipient['email'],
$sender['name'], 'Your Subject Here', $templateContent);
}
Customizing Email Templates
If you need to modify the template content programmatically, you can use the following approach:
-
Load the template: Use Magento’s
Mage_Core_Model_Email_Templatemodel. -
Get the HTML and text contents:
public function loadAndModifyTemplate()
{
$templateId = 'sales_email_order_template';
/** @var Mage_Core_Model_Email_Template $mailTemplate */
$mailTemplate = Mage::getModel('core/email_template');
// Load the template
$mailTemplate->load($templateId);
// Get the HTML and text contents (which you can modify)
$htmlContent = $mailTemplate->getHtmlTemplate();
$textContent = $mailTemplate->getText();
// Modify content here, for example:
$modifiedText = str_replace('{{order.name}}', 'Modified Name', $textContent);
// Save the modified content
$mailTemplate->setText($modifiedText);
$mailTemplate->save();
}
Conclusion
Accessing and using Magento’s custom email templates within a module requires understanding how Magento manages these resources. By leveraging the Mage_Core_Model_Email_Template model, you can retrieve existing templates, send emails using them, or even modify their content programmatically.
Remember to always ensure that your code adheres to Magento’s best practices and standards for optimum performance and security.