Magento custom emails

Featured Image

Ever wanted to “just send the email” using the built in email features in Magento? Ever hit the wall trying to do something with Magento? OK, I know the answer to the other one, just had to ask :). Anyhow, sending the emails with Magento turned out to be a process of “just” a few hours of tracing Magento code.

I cant wait for smart comments like, “few hours, huh its so easy…”. Yea, thats the beauty of Magento… few hours of bashing your head against the wall while you are sipping the 4th cup of coffee until the solution hits you. Interesting do, just when you get the hang of it, Magento gets you this “have you tried this” attitude :).

What am I talking about? Scenario: I want to create email template named activecodeline_custom_email1.html, I want to pass few variables to it during runtime, I want to send emails programmaticaly. I dont want to create 56 lines of xml file just to call one template.

Here is how.

...
/*
 * Loads the html file named 'custom_email_template1.html' from
 * app/locale/en_US/template/email/activecodeline_custom_email1.html
 */ 
$emailTemplate  = Mage::getModel('core/email_template')
						->loadDefault('custom_email_template1');									
 
//Create an array of variables to assign to template
$emailTemplateVariables = array();
$emailTemplateVariables['myvar1'] = 'Branko';
$emailTemplateVariables['myvar2'] = 'Ajzele';
$emailTemplateVariables['myvar3'] = 'ActiveCodeline';
 
/**
 * The best part :)
 * Opens the activecodeline_custom_email1.html, throws in the variable array 
 * and returns the 'parsed' content that you can use as body of email
 */
$processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);
 
/*
 * Or you can send the email directly, 
 * note getProcessedTemplate is called inside send()
 */
$emailTemplate->send('john@someemail.com','John Doe', $emailTemplateVariables);
...

And here we go again, nothing without xml files :) -In order for above piece of code to work, you need to add an entry to your config.xml file like shown below.

...
<global>      
	<template>
		<email>
			<custom_email_template1 module="SampleModule1">
				<label>ActiveCodeline custom email module</label>
				<file>activecodeline_custom_email1.html</file>
				<type>html</type>
			</custom_email_template1>
		</email>
	</template>
</global>  
...

And lets not forget the email template itself, app/locale/en_US/template/email/activecodeline_custom_email1.html.

<!--@subject ActiveCodeline custom email module @-->
 
<div>
<h1>ActiveCodeline custom email example by Branko Ajzele</h1>
<p>Hi there {{var myvar1}} {{var myvar2}} from {{var myvar3}}. This is just some example template to test custom email module.</p>
</div>

Hope this was helpful. Cheers.

Interested in hiring us?

Have a chat with us. You would be surprised how small changes can make your business even more successful.


49 comments

  1. Not worked for me, but there is a great example in magento code: Mage/Contacts/controllers/IndexController.php see “postAction” function

    This example from magento code worked for me!

  2. I have followed the above guidelines to make a custom email template, but its not working could any one help? i am not getting any email on reciever@gmail.com
    I am sending an email from view.phtml
    my codings are as follows
    first i add in app/etc/config.xml within the tags of global i put following code

    <template>
            <email>
                <custom_email_template1 module="SampleModule1">
                    <label>ActiveCodeline custom email module</label>
                    <file>activecodeline_custom_email1.html</file>
                    <type>html</type>
                </custom_email_template1>
            </email>
        </template>

    then i add in my view.phtml

    $emailTemplate  = Mage::getModel('core/email_template')
                            ->loadDefault('custom_email_template1');
    $emailTemplateVariables = array();
    $emailTemplateVariables['customerName'] = $name;
    $emailTemplateVariables['orderNo'] = $rand;
    $emailTemplateVariables['address'] = $address;
    $emailTemplateVariables['city'] = $city;
    $emailTemplateVariables['phone'] = $phone;
    $emailTemplateVariables['mobile'] = $mobile;
    $emailTemplateVariables['productName'] = 'ActiveCodeline';
    $emailTemplateVariables['productSku'] = $sku;
    $emailTemplateVariables['comments'] = $comments;
    
    $processedTemplate = $emailTemplate->getProcessedTemplate($emailTemplateVariables);
    $emailTemplate->setSenderName('sender name');
    $emailTemplate->setSenderEmail('sender@gmail.com');
    $emailTemplate->send('reciver@gmail.com','John Doe', $emailTemplateVariables);

    i made a new email template file in app/locale/en_US/template/email/activecodeline_custom_email1.html
    with following code

    <!--@subject  {{var store.getFrontendName()}}: Invoice # {{var invoice.increment_id}} for Order # {{var order.increment_id}} @-->
    <!--@vars
    {"store url=\"\"":"Store Url",
    "var logo_url":"Email Logo Image Url",
    "var logo_alt":"Email Logo Image Alt",
    "htmlescape var=$order.getCustomerName()":"Customer Name",
    "var store.getFrontendName()":"Store Name",
    "store url=\"customer/account/\"":"Customer Account Url",
    "var invoice.increment_id":"Invoice Id",
    "var order.increment_id":"Order Id",
    "var order.billing_address.format('html')":"Billing Address",
    "var payment_html":"Payment Details",
    "var order.shipping_address.format('html')":"Shipping Address",
    "var order.shipping_description":"Shipping Description",
    "layout area=\"frontend\" handle=\"sales_email_order_invoice_items\" invoice=$invoice order=$order":"Invoice Items Grid",
    "var comment":"Invoice Comment"}
    @-->
    <!--@styles
    body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif; }
    @-->
    
    <body style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
    <div style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
    <table cellspacing="0" cellpadding="0" border="0" height="100%" width="100%">
    <tr>
        <td align="center" valign="top" style="padding:20px 0 20px 0">
            <!-- [ header starts here] -->
            <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                <tr>
                    <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
                </tr>
            <!-- [ middle starts here] -->
                <tr>
                    <td valign="top">
                        <h1 style="font-size:22px; font-weight:normal; line-height:22px; margin:0 0 11px 0;"">Hello, {{htmlescape var customerName}}</h1>
                        <p style="font-size:12px; line-height:16px; margin:0;">
                            Thank you for your order from {{var store.getFrontendName()}}.
                            Once your package ships we will send an email with a link to track your order.
                            If you have any questions about your order please contact us at <a href="mailto:{{config path='trans_email/ident_support/email'}}" style="color:#1E7EC8;">{{config path='trans_email/ident_support/email'}}</a> or call us at <span class="nobr">{{config path='general/store_information/phone'}}</span> Monday - Saturday, 10am - 8pm PST.
                        </p>
                        <p style="font-size:12px; line-height:16px; margin:0;">Your order confirmation is below. Thank you again for your business.</p>
                    </td>
                </tr>
                <tr>
                    <td>
                        <h2 style="font-size:18px; font-weight:normal; margin:0;">Your Order #{{var orderNo}}(Placed on {{var dateNtime}} PKT)</h2>
                    </td>
                </tr>
                <tr>
                    <td>
                        <table cellspacing="0" cellpadding="0" border="0" width="650">
                            <thead>
                                <tr>
                                    <th align="left" width="325" bgcolor="#EAEAEA" style="font-size:13px; padding:5px 9px 6px 9px; line-height:1em;">Billing Information:</th>
                                    <th width="10"></th>
                                    <th align="left" width="325" bgcolor="#EAEAEA" style="font-size:13px; padding:5px 9px 6px 9px; line-height:1em;">Payment Method:</th>
                                </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <td valign="top" style="font-size:12px; padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA; border-bottom:1px solid #EAEAEA; border-right:1px solid #EAEAEA;">
                                    {{var customerName}}<br>
                                    {{var address}}<br>
                                    {{var city}}<br>
                                    Phone:  {{var phone}}<br>
                                    Mobile: {{var mobile}}
                                </td>
                                <td>&nbsp;</td>
                                <td valign="top" style="font-size:12px; padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA; border-bottom:1px solid #EAEAEA; border-right:1px solid #EAEAEA;">
                                    <strong>Cash On Delivery</strong>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        <br/>
                        <table cellspacing="0" cellpadding="0" border="0" width="100%">
                            <thead>
                            <tr>
                                <th align="left" width="325" bgcolor="#EAEAEA" style="font-size:13px; padding:5px 9px 6px 9px; line-height:1em;">Shipping Information:</th>
                                <th width="10"></th>
                                <th align="left" width="325" bgcolor="#EAEAEA" style="font-size:13px; padding:5px 9px 6px 9px; line-height:1em;">Shipping Method:</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <td valign="top" style="font-size:12px; padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA; border-bottom:1px solid #EAEAEA; border-right:1px solid #EAEAEA;">
                                    {{var customerName}}<br>
                                    {{var address}}<br>
                                    {{var city}}<br>
                                    Phone:  {{var phone}}<br>
                                    Mobile: {{var mobile}}
                                    &nbsp;
                                </td>
                                <td>&nbsp;</td>
                                <td valign="top" style="font-size:12px; padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA; border-bottom:1px solid #EAEAEA; border-right:1px solid #EAEAEA;">
                                    Free Shipping - Free Delivery Across Pakistan, No Hidden Charges Delivery within 24-48 Hours Payment on Delivery by TCS.
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        <br/>
                        <table cellspacing="0" cellpadding="0" border="0" width="100%">
                            <thead>
                            <tr>
                                <th align="left" width="325" bgcolor="#EAEAEA" style="font-size:13px; padding:5px 9px 6px 9px; line-height:1em;">Item</th>
                                <th width="100" bgcolor="#EAEAEA" style="font-size:13px; padding:5px 9px 6px 9px; line-height:1em;">Sku</th>
                                <th width="100" bgcolor="#EAEAEA" style="font-size:13px; padding:5px 9px 6px 9px; line-height:1em;">Quantity</th>
                                <th align="left" width="135" bgcolor="#EAEAEA" style="font-size:13px; padding:5px 9px 6px 9px; line-height:1em;">Subtotal</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr>
                                <td valign="top" style="font-size:12px; padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA; border-bottom:1px solid #EAEAEA; border-right:1px solid #EAEAEA;">
                                    {{var productName}}
                                    &nbsp;
                                </td>
                                <td valign="top" style="font-size:12px; padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA; border-bottom:1px solid #EAEAEA; border-right:1px solid #EAEAEA;">
                                    {{productSku}}
                                    &nbsp;
                                </td>
                                <td valign="top" style="font-size:12px; padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA; border-bottom:1px solid #EAEAEA; border-right:1px solid #EAEAEA;">
                                    {{productQuantity}}
                                    &nbsp;
                                </td>
                                <td valign="top" style="font-size:12px; padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA; border-bottom:1px solid #EAEAEA; border-right:1px solid #EAEAEA;">
                                    {{productPrice}
                                </td>
                            </tr>
                            <tr>
                                <td>&nbsp;</td>
                                <td>&nbsp;</td>
                                <td>Subtotal</td>
                                <td>{{productPrice}}</td>
                            </tr>
                            <tr>
                                <td>&nbsp;</td>
                                <td>&nbsp;</td>
                                <td>Shipping & Handling</td>
                                <td>Rs. 0.00</td>
                            </tr>
                            <tr>
                                <td>&nbsp;</td>
                                <td>&nbsp;</td>
                                <td><strong>Grand Total</strong></td>
                                <td><strong>{{productPrice}}</strong></td>
                            </tr>
                            </tbody>
                        </table>
                        <p style="font-size:12px; margin:0 10px 10px 0;">{{var comment}}</p>
                    </td>
                </tr>
                <tr>
                    <td bgcolor="#EAEAEA" align="center" style="background:#EAEAEA; text-align:center;"><center><p style="font-size:12px; margin:0;">Thank you again, <strong>{{var store.getFrontendName()}}</strong></strong></p></center></td>
                </tr>
            </table>
        </td>
    </tr>
    </table>
    </div>
    </body>

    Kindly sort out my mistake
    thanks

  3. Works fine! However, how do I use it within the Transitional E-mails? I mean, want to create a e-mail template on the admin and use it with the code. How to?

  4. Thanks a lot for the great tutorial on Magento custom emails. This is very helpful for a newbie like me.

  5. Me too really Apprecialte Brian’s advice from 12-01-2012 at 22:15 . I was trying to resolve this issue from the past 1 week. I got it working.
    Thanks

  6. I really appreciate the guidance but you REALLY need to incorporate Brian’s advice from 12-01-2012 at 22:15 . This was a very odd bug to try to fix.

  7. Hi all,

    I want to apply this custom email block to my footer.phtml page for sending the custom email, can anyone help me…

    thanks
    Rishabh

  8. Hi , thank you for this great tutorial.Can you tell me How to integrate Freshbook – Magento ?

  9. I’m doing:

    $emailTemplate = Mage::getModel(‘core/email_template’)->loadDefault(‘send_to_requests_template’);
    $emailTemplate->setSenderName(“Some Name”);
    $emailTemplate->setSenderEmail(“some@mail.com”);
    $emailTemplate->setTemplateSubject($this_>__(“Some Subject!”));
    $emailTemplateVariables = array();
    $emailTemplateVariables[‘zip’] = “….”;
    $emailTemplate->send($request[‘email’], “Mike Old”, $emailTemplateVariables);

    but mail are never been delivered. I have checked the spam folder, nothing, I have checked the smtp settings from magento, nothing…. I’m doing smthg wrong?
    thx

  10. If you are having trouble with the Transactional Emails in Admin try removing the module attrubute in your config.xml. For example, if you’re using the sample code change line 5 from this:

    <custom_email_template1 module="SampleModule1">

    to this:

    <custom_email_template1>

    This solved the issue for me.

  11. The admin Transactional Email-s don’t work anymore definitly. Does anyone have solution for this?

    Thanks for the great article though, it works great, but this is the problem now.

  12. Oops pasted from wrong confix.xml:

    <global>
        <template>
            <email>
                <Optimise_Requestcallback module="optimise_requestcallback">
                    <label>Optimise RequestCallback</label>
                    <file>optimise_requestcallback.html</file>
                    <type>html</type>
                </Optimise_Requestcallback>
            </email>
        </template>
    </global>
  13. Thanks for the code. I’ve got one problem though. The email works and sends fine but now when I log into the backend and go to System > Transactional Emails > and click ‘Add new template’ the page seems to crash. The template dropdown gets rendered but with no options and everything after that fails to load.

    Just wondering if anyone else has had that problem?

    I think it could be down to my xml. I’m not sure what I have in the module=”” is correct. My module is in Local > Optimise > Requestcallback

    <global>
        <template>
            <email>
                <optimise_orderform module="Orderform">
                    <label>Optimise Orderform</label>
                    <file>optimise_orderform.html</file>
                    <type>html</type>
                </optimise_orderform>
            </email>
        </template>
    </global>
  14. [quote]
    H,
    I’ve tried to add a new Email Template file (activecodeline_custom_email1.html) to the folder “/app/locale/en_US/template/email” and use it according to the instructions here, but after I did that the New Email Template page in the admin area stoped working… It looks like the page start to load the templates to the
    Load default template- Template dropdown and have an error while doing that so the page stop there (I’m adding a print screen).

    Iv’e tried to delete the “activecodeline_custom_email1.html” file from “/app/locale/en_US/template/email” and clean the cache but it didn’t fixed the problem.

    How can I fix this?

    Buy the way – I’m using Magento ver. 1.4.0.1

    [/quote]

    True.
    Generates error_log

    [18-Aug-2011 07:14:01] PHP Fatal error: Class ‘Mage_SampleModule1_Helper_Data’ not found in /home/public_html/app/Mage.php on line 523

  15. Thanks for the awesome post! Do you know how I would add the Customer’s Company Name (from Billing Address) in an email template’s subject line?

  16. Great tutorial, but no emails are sent and no errors are generated.

    Any help would be appreciated. I’ve literally copied the code as is, no customization what so ever, just to check this solution works. I can provide code if need be.

    To point out, I’ve placed this within my own controller – e.g. email/enquiry/hello

  17. If you want to just change Email Subject as posted from subject field–

    – Go to System> Transactional Emails
    – Click your template to Edit
    – delete your static Email subject and replace with
    {{var data.subject}}

    Here, You should have field with name “subject”

  18. hi to all,
    i created a custom module in front end. any user can post what they thinking in mind about website.
    i used ur script the mail is not going…the final result will false.soo please help me…
    In that nothing is their just a using a mail function..no need to interact with the database..just a simple script..

  19. Hi,
    I followed this tuto, but still can’t get it work even if I add these lines
    $emailTemplate->setSenderName(‘Test’);
    $emailTemplate->setSenderEmail(‘somemail@domain.com’);
    $emailTemplate->setTemplateSubject(‘STATUS CHANGED’);
    How can I check if the operation is successful?

  20. It´s works for me!!
    BUUUUUUUUUUUUUUUUUT its required that u clear the cache even don´t use it via admin.

    execute “rm -fr var/cache/*”

    I worked 2 days in this problem! =/

    ps. Im sorry by my English.

  21. Wow! It’s the great tip I want!
    In the magento document is not good as this 1!
    before I spend 2 days to do sending email in magento and it’s not working!
    After I found this, I just spend 1 hour to do!

    Cheer,
    Rithy

  22. H,
    I’ve tried to add a new Email Template file (activecodeline_custom_email1.html) to the folder “/app/locale/en_US/template/email” and use it according to the instructions here, but after I did that the New Email Template page in the admin area stoped working… It looks like the page start to load the templates to the
    Load default template- Template dropdown and have an error while doing that so the page stop there (I’m adding a print screen).

    Iv’e tried to delete the “activecodeline_custom_email1.html” file from “/app/locale/en_US/template/email” and clean the cache but it didn’t fixed the problem.

    How can I fix this?

    Buy the way – I’m using Magento ver. 1.4.0.1

  23. It is silly to wait for “smart comments like, “few hours, huh its so easy…”” :) In the modern times we use internet and if we do not know something just ask Google :)

    This introduction is great clounade

  24. Great work Buddy.
    But I want to attach one pdf with this mail.:)

    How to do that ?
    Please help.

  25. As François Gueguen said before, you must use :

    $emailTemplate->setSenderName(‘NAME’);
    $emailTemplate->setSenderEmail(‘EMAIL@DOMAIN.com’);
    $emailTemplate->setTemplateSubject(‘STATUS CHANGED’);

    Because the function isValidForSend is called when executing the send() function.

  26. Nice tutorial, thank you!
    Can we use it as usual in Magento, I mean can we rewrite it from the administration panel for the different languages?

  27. i am using default template but the problem is i get mail but comments are not showing in that mail,
    how can i resolve the issue
    all details are mailing to me but comments are not in that mail
    hope u understood the problem i am having with mailing

  28. $emailTemplate->send(‘john@someemail.com’,’John Doe’, $emailTemplateVariables);

    send() config?

  29. ActiveCodeline custom email module
    activecodeline_custom_email1.html
    html

    xml?????

  30. Hi, thanks very much for your trick.
    I want to send an email from Order View Page in admin panel. I tried to use your trick, but it did not work. I am confused that which config.xml I should change. Please help me.

  31. François Gueguen is right, it does need the send name and sender email.
    I would like to know though if there is a way to get those details from magento

  32. Thank you for this tuto, but don’t you miss a

    $emailTemplate->setSenderName(‘my name’);
    $emailTemplate->setSenderEmail(‘my@email.com’);

    before to send?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.