Custom email templates in Magento2
In this blog, we’ll discuss how we can create custom email templates and insert variables in email templates of magento2.
Declare email template
Create email_templates.xml inside Vendor/Module/etc/ folder.
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../Magento/Email/etc/email_templates.xsd">
<template id="custom_module_email_template" label="custom_module_email_template" file="custom_email.html" type="html" module="Blog_Management" area="frontend" />
</config>
Here,
Id is a unique identifier for email templates which we’ll use while declaring which email template we want to use while sending email.
label is a displayed name of an email template.
file is a html file in which is used to render html content for email templates.
module is used to define the vendor_module name in which we are creating this email template.
area is used to find email template files in adminhtml or frontend.
Create email template file
Now, create custom_email.html file inside Vendor/Module/view/frontend/email/ folder.
<!--@Subject Email Template @-->
<!--@vars
{"store url=\"\"":"Store Url",
"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image"}
@-->
<!--@styles
body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif; }
@-->
{{template config_path="design/email/header_template"}}
<p>{{trans "Hi "}} {{var customer_name}},</p>
<p>
{{trans "Thank You for Registering,"}}
{{trans "We will send You Link along with the Password for you to log in. Stay connected for updates."}}
</p>
{{var message}}
{{template config_path="design/email/footer_template"}}
trans is used before the text you want to translate while using a multilingual store.
We have to pass the variable values while sending email like this:-
$storeId = $this->storeManager->getStore()->getId();
$from = ['email' => $fromEmail, 'name' => $fromName];
$this->inlineTranslation->suspend();
$storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
$templateOptions = [
'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
'store' => $storeId
];
$templateId = 'custom_module_email_template'; // template id
$templateVars = array( //Create array to pass the variables
'store' => $this->storeManager->getStore(),
'customer_name' => 'Sakshi Bissa',
'message' => 'Thankyou.'
);
$transport = $this->transportBuilder->setTemplateIdentifier($templateId, $storeScope)
->setTemplateOptions($templateOptions)
->setTemplateVars($templateVars) // pass variables
->setFrom($from)
->addTo($toEmail)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
We can access these variables inside the html file using {{var customer_name}}. That's all.
Comments
Post a Comment