Home >How to Send Email in Magento 2

How to Send Email in Magento 2

Currently, keeping the longlasting relationship between the stores and customer is extremely necessary. Email is a common method to help store owners keep contact and communicate information to their customers.

In this article, we will give you the way to create custom email by using email template and send email to any addresses.

Declare config module

Create etc/adminhtml/system.xml.

You can create field to load email template in section and group through by: app/code/Bss/EmailDemo/etc/adminhtml/system.xml.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
        <tab id="bss" translate="label" sortOrder="300">           
            <label><![CDATA[Bss Commerce]]></label>
        <section id="email" translate="label" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Bss Email Demo</label>
            <group id="demo" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Please Choose Your Email Template</label>
                <field id="template" translate="label" type="select" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Email Template</label>
                    <comment>Email template is chosen based on theme fallback when "Default" option is selected.</comment>

Please go BSS COMMERCE -> Bss Email Demo to see the result.

Declare Email Template

Create app/code/Bss/EmailDemo/etc/email_templates.xml.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">
<template id="email_demo_template" label="This is email demo" file="email_demo_template.html" type="html" module="Bss_EmailDemo" area="frontend"/>

In which:

  • Template id: Your template id you have create in Step 1.
  • Label: Your Label will show in dropdown email.
  • file: Your email template file.
  • type: Type of your email. module: Your module.
  • area: The place your email in the module directory. view / frontend or view / adminhtml

Create Helper Email

Create app/code/Bss/EmailDemo/Helper/Email.php.

namespace Bss\EmailDemo\Helper;

use Magento\Framework\App\Helper\Context;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Framework\Escaper;
use Magento\Framework\Mail\Template\TransportBuilder;

class Email extends \Magento\Framework\App\Helper\AbstractHelper
    protected $inlineTranslation;
    protected $escaper;
    protected $transportBuilder;
    protected $logger;

    public function __construct(
        Context $context,
        StateInterface $inlineTranslation,
        Escaper $escaper,
        TransportBuilder $transportBuilder
    ) {
        $this->inlineTranslation = $inlineTranslation;
        $this->escaper = $escaper;
        $this->transportBuilder = $transportBuilder;
        $this->logger = $context->getLogger();

    public function sendEmail()
        try {
            $sender = [
                'name' => $this->escaper->escapeHtml('Test'),
                'email' => $this->escaper->escapeHtml('humorgodfather9x02@gmail.com'),
            $transport = $this->transportBuilder
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                    'templateVar'  => 'My Topic',
        } catch (\Exception $e) {

In which:

  • $sender: The sender’s information (‘name’: sender’s name and ‘email’: sender’s email)
  • setTemplateIdentifier(’email_demo_template’): email_demo_template is ID of template email mentioned in Step 1 and 2.
  • setTemplateVars: The information or variable in your email.
  • addTo(‘testmagento321@gmail.com’): You can fill in the recipient’s email here.

Create Email by html

Create app/code/Bss/EmailDemo/view/frontend/email/email_demo_template.html.

{{template config_path="design/email/header_template"}}
    <tr>{{trans "Wellcome To: %templateVar." templateVar=$templateVar}}</tr>
{{template config_path="design/email/footer_template"}}

You can also send emails through Events or use the Plugin to add emails.

Catch Event

To test the email function, we test through the capture of the customer_register_success event when the customer registers the account successfully.

Create app/code/Bss/EmailDemo/etc/frontend/events.xml.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="customer_register_success">
        <observer name="bss_email_customer_register" instance="Bss\EmailDemo\Observer\CustomerRegisterObserver"/>

Create Observer to Send Email

Create app/code/Bss/EmailDemo/Observer/CustomerRegisterObserver.php.

namespace Bss\EmailDemo\Observer;

use Magento\Framework\Event\ObserverInterface;
use Bss\EmailDemo\Helper\Email;

class CustomerRegisterObserver implements ObserverInterface
    private $helperEmail;
    public function __construct(
        Email $helperEmail
    ) {
        $this->helperEmail = $helperEmail;
    public function execute(\Magento\Framework\Event\Observer $observer)
        return $this->helperEmail->sendEmail();

The Result

After the account is registered successfully, email will be sent automatically to the customer. Please take a look at the image as below.

< Previous Post
Next Post >
Nguyen Tan Thanh
+ posts