How to send email programmatically in Magento
Sometimes you may find yourself having to send an email after a particular action has occurred. For example, you have a custom extension allowing you to add a product to a list of favorites and would like to email the users that their list has been updated. While working with Magento, I have found myself having to do this often. In this tutorial, I’ll go through on how to programmatically send email in Magento.
First, I start by creating the email template that will be used to send out. In this example, let’s assume that our email template is named “Favourite Email”, and let’s say that this email template includes two variable: user_name and product_name.
Now, the first step is to load our email template:
$templateId = “Fav Email”; $emailTemplate = Mage::getModel('core/email_template')->loadByCode($templateId);
Then, I create an array that will contain these two values:
$vars = array(‘user_name’ => $userName, ‘product_name’ => $productName);
If you’d like to view the processed template before sending the email, you print the following function:
Otherwise, the next steps would be to set the email sender information. In this example I am pulling in our sending info from the Magento store email address configuration under the general contact tab:
$emailTemplate->setSenderEmail(Mage::getStoreConfig('trans_email/ident_general/email’, $storeId)); $emailTemplate->setSenderName(Mage::getStoreConfig('trans_email/ident_general/name', $storeId));
And finally, I send out the email:
Sending emails in Magento is a fairly straightforward process.