Sending emails programmatically in Magento

Posted by Pixafy Team

Sometimes you may find yourself having to send an email after a particular action has occurred. For example, you have a custom module that allows you to add a product to a list of favorites and would like to email the user that their list has been updated. While working with Magento, I have found myself having to do this often. After consulting with my fellow developers, I found out how to send emails programmatically in Magento.

We first start out by creating the email template that you are going to be sending out. In this example, we will assume our email template is named “Fav Email”, and let’s say that this email template consists of two variable: user_name and product_name.  The first step is to load our email template:

$templateId = “Fav Email”;

$emailTemplate = Mage::getModel('core/email_template')->loadByCode($templateId);

Then, we 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 we are 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, we send out the email:

$emailTemplate->send($receiveEmail,$receiveName, $vars);

As you can see, sending emails in Magento is a fairly straightforward process.