Ooooo sending emails in Magento is painful! Grrrrrr.

Or is it?

Firstly a use case.

I generate report data from cron and I need a simple way of sending the reports on email to a recipient. I do not want to use just the regular php mail() command. It is not reliable and I want it to fit within the Magento way of sending emails.

A popular Mandrill module that I use will also continue to work by making sure we use the in built magento email sending functions.

Okay, so first we need to declare our email so we can load it later on.

Assuming you already have a moduleā€¦

In app/code/[codePool]/[Vendor]/[ModuleName]/etc/config.xml:


Next, create the template file app/code/locale/en_US/template/email/custom/report.html and in it put;

{{var msg}}

That is all you need :)

Next is the mechanism to actually send the email. I favour putting this in a helper.

In app/code/[codePool]/[Vendor]/[ModuleName]/Helper/Email.php:


class [Vendor]_[ModuleName]_Helper_Email
    public function sendReport($subject, $msg)
        $emailTemplate  = Mage::getModel('core/email_template');
        /** @var Mage_Core_Model_Email_Template $emailTemplate */
        // send it
        return $emailTemplate->send('[email protected]', null, ['msg' => $msg]);

It is important that the string passed to ->loadDefault() matches the XML node in our config.xml.

How you generate the content is up to you. You just need to pass it to the template with ['msg' => $msg].



My reports tend to be generated in csv format and a required to be sent as an attachment to the email.

If the $msg part is already a csv formatted string you can simply add the following just before the sending of the email.

    ->createAttachment($msg, Zend_Mime::TYPE_OCTETSTREAM, Zend_Mime::DISPOSITION_ATTACHMENT, Zend_Mime::ENCODING_BASE64, 'sample.csv');

->createAttachment() automatically adds the created attachment to the email.

All createAttachment is really doing is constructing a Zend_Mime_Part object and calling ->addAttachment(). That means you cann construct your attachments and add them directly yourself if you have more complicated use cases.

  • magento
  • email

Like this post? Share it :)

Related Posts