Blog

How to Customize Magento 2 Email Templates Using PHTML for Dynamic Content

Magento 2 email templates are HTML files with directives such as {{var}}, {{depend}} and {{if}}. For logic these directives can’t express, a template can render a PHTML file through the {{block}} directive. This guide shows where the templates are, how their variables work and how to add a PHTML block. A separate section explains how form emails work in WebForms 4.

The example adds a note to Magento’s New Order email template that depends on the payment method the customer chose.

Introduction: Where Magento 2 Email Templates Are

A Magento email template comes from a module file, a theme override of that file or a copy saved in the admin. The store configuration decides which one is sent.

Default template files

Each module keeps its templates in view/frontend/email/. For example:

  • vendor/magento/module-sales/view/frontend/email/order_new.html — the New Order email.
  • vendor/magento/module-contact/view/frontend/email/submitted_form.html — the email of the default Contact Us form.
  • vendor/magento/module-email/view/frontend/email/header.html and footer.html — the header and footer that most emails include.

Don’t edit these files. A Composer update replaces them.

Copies in the admin

Go to Marketing > Communications > Email Templates, click Add New Template, select a template under Load Default Template and click Load Template. Edit the copy, name it and click Save Template.

The copy is used only after you select it in the configuration. For the New Order email, that is New Order Confirmation Template (and … for Guest) in Stores > Configuration > Sales > Sales Emails > Order.

Theme overrides

A theme can replace a template file. Copy it into your theme under the module’s name and the email folder, keeping the file name:

app/design/frontend/Vendor/theme/Magento_Sales/email/order_new.html

The override applies to every store view that uses the theme. Clean the cache after you add or change it.

Header and footer

Most templates start with {{template config_path="design/email/header_template"}} and end with the footer line of the same kind. To use your own header or footer, save a copy of Header or Footer in Email Templates. Then select it in Content > Design > Configuration: edit the store view, expand Transactional Emails and set Header Template or Footer Template. The same section holds the email logo.

Magento 2 Email Template Variables and Directives

A template prints data with directives in double curly braces. On a template’s page in Email Templates, Insert Variable... lists the variables that template offers, such as {{var order.increment_id}} in the New Order email or {{var data.comment}} in the Contact Us email.

{{var order_data.customer_name}}                  prints a value
{{trans "Thank you for your order"}}              prints translatable text
{{depend order_data.email_customer_note}}...{{/depend}}   prints the text only when the value is set
{{if shipping_msg}}...{{else}}...{{/if}}            the same, with an alternative
{{for item in items}}...{{/for}}                    repeats the text for each item of a list
{{customVar code=my_code}}                        a value from System > Other Settings > Custom Variables
{{layout handle="sales_email_order_items" order_id=$order_id area="frontend"}}   renders a layout handle
{{block class="..." template="..."}}             renders a block with a PHTML template

{{if}} and {{depend}} check whether a value is empty or not. They cannot compare one value with another, such as “payment method is bank transfer”. Magento’s filter also pairs a nested {{if}} with the wrong closing tag, so keep conditions one level deep. For anything more, use a PHTML file, as in the steps below.

Step-by-Step Guide to Customize Magento 2 Email Templates

1. Create a Custom Module

First, create a custom module to manage your customizations. For example, let's create a module named Vendor_CustomEmail.

app/code/Vendor/CustomEmail/
├── etc
│   └── module.xml
├── registration.php
└── view
    └── frontend
        └── templates
            └── email
                └── payment_note.phtml
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_CustomEmail',
    __DIR__
);
?>
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_CustomEmail" setup_version="1.0.0" />
</config>

2. Enable the Custom Module

Run the following commands to enable your new custom module:

php bin/magento module:enable Vendor_CustomEmail
php bin/magento setup:upgrade

If the store runs in production mode, also run php bin/magento setup:di:compile and php bin/magento setup:static-content:deploy.

3. Create the PHTML Template

Create the payment_note.phtml file that will render the dynamic content. The email template passes the order to it, and the file chooses a note by the payment method code.

<?php
/** @var \Magento\Framework\View\Element\Template $block */
$order = $block->getData('order');
$payment = $order ? $order->getPayment() : null;
$method = $payment ? (string)$payment->getMethod() : '';

switch ($method) {
    case 'banktransfer':
        $note = __('We ship your order as soon as your bank transfer arrives.');
        break;
    case 'checkmo':
        $note = __('We ship your order as soon as your check arrives.');
        break;
    case 'cashondelivery':
        $note = __('Please have the amount ready when the courier arrives.');
        break;
    default:
        $note = __('Thank you for your order. We will email you when it ships.');
        break;
}
?>
<p><?= $block->escapeHtml($note) ?></p>

4. Modify the Email Template

Add a {{block}} directive to the New Order template and pass the order to it. Use an admin copy (Marketing > Communications > Email Templates, Load Template with New Order) or a theme override of Magento_Sales/email/order_new.html, as described above. Put the line where the note should appear, for example under the greeting:

<!-- Other template content -->
{{block class="Magento\Framework\View\Element\Template" area="frontend" template="Vendor_CustomEmail::email/payment_note.phtml" order=$order}}
<!-- Other template content -->

Each parameter becomes data of the block: the PHTML file reads order=$order with $block->getData('order'). An admin copy must be selected in the configuration, as shown above.

5. Deploy and Test

Clean the cache:

php bin/magento cache:clean

Place a test order with Bank Transfer Payment or another payment method and open the confirmation email. The note should match the payment method.

Form Email Templates in WebForms 4

Earlier versions of this guide used WebForms 3: a Magento email template selected in the form’s settings and the variable {{var result.subject.value}}. WebForms 4 works differently, and the steps above don’t apply to its form emails.

Notifications per form

Each form has its own emails, called notifications: Content > WebForms > Manage Forms, the form’s name, then Notifications. Each notification has:

  • a Trigger: the event that sends it, such as Form Submitted or Submission Status Changed;
  • a Recipient Source, such as fixed addresses, a store address, the person who submitted the form or the contact the visitor chose in the form;
  • optional Conditions, so it goes out only for some answers.
Three WebForms 4 notification cards with their trigger, recipients, subject and one condition: Service is Delivery and assembly

The Notifications section of a form: when each email is sent, to whom, and under which condition.

See Notification triggers and Recipients and conditions.

Merge tags instead of template variables

You write the subject and the text in the notification’s Message section, with Content Source set to Standard Content. The {..} button inserts merge tags. A few of them:

  • {{var field:subject}} — the visitor’s answer in the field with the field code subject. This replaces {{var result.subject.value}}.
  • {{var all_fields}} — a table of all answers.
  • {{var reference}} — the submission’s reference number.
  • {{depend field:message}}...{{/depend}} — prints the text in between only when the field has an answer.
The Message section of a WebForms 4 notification: Content Source set to Standard Content, Subject and Preheader with merge tag buttons, and the message editor with merge tags

The Message section with Standard Content, the subject and the text with merge tags.

The full list is in the Merge tags reference. The steps are in Writing email content.

Magento template code in Advanced Content

Content Source has a second choice, Advanced Content, for Magento’s own email template code. It runs through Magento’s filter, so directives of a Magento email template, such as {{template config_path="design/email/header_template"}}, work there. Keep in mind:

  • Only admins whose role includes Write Advanced Notification Content see it.
  • Some tags from the {..} menu print nothing in Advanced Content. Check them in the Preview, which needs a real submission here.
  • The email gets no WebForms design and no plain-text copy.

Email layout and upgrades from WebForms 3

A copy saved in Marketing > Communications > Email Templates has no effect on WebForms 4 emails. The frame around a notification with Standard Content comes from a template file, and you change it with a theme override: app/design/frontend/Vendor/theme/MageMe_WebForms/email/wrapper/thread.html. The copy must keep {{var body_slot}} exactly once, because the message replaces it.

On an upgrade from WebForms 3, each notification that used a Magento email template gets that template’s text. A customized template becomes Advanced Content with the same text. After the upgrade, open each form’s notifications and check the ones that still refer to a WebForms 3 template (legacy_template) before you switch on Deliver Notifications. See Email template overrides.

Conclusion

Directives cover printing values and checking whether a value is set. When an email must compare values, a {{block}} directive with a PHTML file in your own module does the work. In WebForms 4, form emails are written in each notification with merge tags.

Key Takeaways

  • Three places for a template — the module file, an admin copy selected in the configuration, or a theme override.
  • Directives for simple cases — {{var}}, {{depend}}, {{if}} and {{for}} print and repeat values but don’t compare them.
  • PHTML for logic — the {{block}} directive passes template variables to a PHTML file in your module.
  • WebForms 4 notifications — per-form emails with triggers, recipients, conditions and merge tags; layout through a theme override.

Frequently Asked Questions (FAQ)

help_outline Why should I customize Magento 2 email templates? expand_more

The default templates are generic. A custom template can carry your store's design and the details your customers need, such as a note about the payment method or delivery.

help_outline Where are Magento 2 email templates located? expand_more

The default templates are HTML files in each module's view/frontend/email folder, for example vendor/magento/module-sales/view/frontend/email/order_new.html. Copies you edit in the admin are stored in the database under Marketing > Communications > Email Templates. A theme overrides a file at a path such as app/design/frontend/Vendor/theme/Magento_Sales/email/order_new.html.

help_outline How do variables work in Magento 2 email templates? expand_more

The var directive prints a value, such as the order number. The depend and if directives print text only when a value is set, and the for directive repeats text for each item of a list. On a template page in Email Templates, Insert Variable lists the variables that template offers.

help_outline What is the benefit of using a PHTML file for email templates? expand_more

The if and depend directives check whether a value is empty or not. They cannot compare one value with another. A PHTML file runs PHP, so it can compare values, for example choose a note by payment method, and use any data of the objects the template passes to it.

help_outline How do I create a custom module in Magento 2? expand_more

Creating a custom module in Magento 2 involves setting up the necessary file structure, including the registration.php and module.xml files. This module serves as the foundation for your customizations.

help_outline How do I enable my custom module in Magento 2? expand_more

Run php bin/magento module:enable Vendor_CustomEmail, then php bin/magento setup:upgrade. In production mode, also run setup:di:compile and setup:static-content:deploy.

help_outline How can I test my customized email template? expand_more

Clean the cache, then trigger the email in your store, for example place a test order. Check the received email to make sure the dynamic content matches your PHTML template.

help_outline Can I use this method for other email templates in Magento 2? expand_more

Yes, for Magento's own email templates: add the block directive to the template and pass the variables that template offers. Form emails in WebForms 4 work differently: they are written in the notification with merge tags.

help_outline How do I change the email of a form in WebForms 4? expand_more

Go to Content > WebForms > Manage Forms, click the form's name, click Notifications and click the notification's name. Write the subject and the text in the Message section and insert answers with merge tags. Choosing a Magento email template for a form was a WebForms 3 setting.