Sending Emails with Templates Real Easy in Magento (with attachments)
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…
Next, create the template file
app/code/locale/en_US/template/email/custom/report.html and in it put;
That is all you need :)
Next is the mechanism to actually send the email. I favour putting this in a helper.
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() 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.
Like this post? Share it :)