How to send email programmatically with email template in Magento 1

Sending email programmaticallyis a very common need when you are developing a Magento site or a Magento extension. With the API provided, it is quit easy.  Let’s go over a couple essential steps when we send email programmatically in Magento.

Step 1. Load the Email Template Module

Step 2. Load a Email Template from File or Database

If we have a email template saved as a file in app/locale directory, use the code below to load it.

If you create a email template via Magento back-end and saved it to the database, you can use the code below.

Step 3. Prepare the Variables Used in the Email Template

Prepare the variable array. These variables will be used in the email template. Below is an example, where we retrieved the customer name and email from context, and then store them in an array which will be passed to the email template.

Step 4. Prepare for Sender info

Since we are using email template, subject is already set in the template. Next we will need to provide the sender information. Use the code below to set sender name and sender email.

You can also load the sender info from a previous saved config in the database, e.g. code below loads name and email from general contact which you can manage from Magento backend.

Step 5. Set Recipient and Send

The lasts step is set the recipient of the email, and then send it!

This approach uses an existing email template whether it is created from Magento back-end, or stored as a template. In my future posts, we will also discuss how to create an email template programmatically upon sending an email, or send emails using queue.