How To Send Email In Magento 2?

How To Send Email In Magento 2?

Keeping a healthy working relationship between stores owners and customer essential in business. The only way to build this relationship is by maintaining contact and communication with customers. Emails allow us to do that.

This article will help you send an email in Magento 2.

Let’s begin!

Step 1: Declaring Config Module

The first step is to create config.xml. You can create a field to load the email template in:

app/code/HostAdvice/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">
    <system>
        <tab id="bss" translate="label" sortOrder="300">           
            <label><![CDATA[HostAdvice]]></label>
        </tab>
        <section id="email" translate="label" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
            <class>separator-top</class>
            <label>HostAdvice Email Demo</label>
            <tab>hostadvice</tab>
            <resource>HostAdvice_EmailDemo::config_emaildemo</resource>
            <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>
                    <source_model>Magento\Config\Model\Config\Source\Email\Template</source_model>
                    <comment>Email template is chosen based on theme fallback when "Default" option is selected.</comment>
                </field>            
            </group>
        </section>
    </system>
</config>

Step 2: Declaration of Email Template

The next step is to create email_templates.xml file in:

app/code/HostAdvice/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="HostAdvice_EmailDemo" area="frontend"/>
</config>

In this case, check the following details:

  • Template ID: The template ID created in the first step.
  • Label: Indicates the label that will appear on the drop-down menu of your email.
  • file: The template file of your email.
  • area: Location of your email in the module files.
  • type: email type in your module.

Step 3: Creating a Helper Email

Now create a helper email in:

app/code/HostAdvice/EmailDemo/Helper/Email.php.

<?php
namespace HostAdvice\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
    ) {
        parent::__construct($context);
        $this->inlineTranslation = $inlineTranslation;
        $this->escaper = $escaper;
        $this->transportBuilder = $transportBuilder;
        $this->logger = $context->getLogger();
    }

    public function sendEmail()
    {
        try {
            $this->inlineTranslation->suspend();
            $sender = [
                'name' => $this->escaper->escapeHtml('Test'),
                'email' => $this->escaper->escapeHtml('humorgodfather9x02@gmail.com'),
            ];
            $transport = $this->transportBuilder
                ->setTemplateIdentifier('email_demo_template')
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                    ]
                )
                ->setTemplateVars([
                    'templateVar'  => 'My Topic',
                ])
                ->setFrom($sender)
                ->addTo('testmagento@gmail.com')
                ->getTransport();
            $transport->sendMessage();
            $this->inlineTranslation->resume();
        } catch (\Exception $e) {
            $this->logger->debug($e->getMessage());
        }
    }
}

In this case, take note of the following:

  • $sender: Represents the sender’s information including the name and email.
  • setTemplateVars: Indicates your email’s information.
  • setTemplateIdentifierr(’email_demo_template’): Is the template email ID discussed in step one and two.
  • addTo (‘testmagento@gmail.com’): Enter the email of the recipient here.

Step 4: Creating Email Template through html

Create email_template.html in:

app/code/HostAdvice/EmailDemo/view/frontend/email/email_demo_template.html.

{Error in template processing}
<table>
    <tr>{{trans "Wellcome To: %templateVar." templateVar=$templateVar}}</tr>
</table>
{Error in template processing}

Emails can be sent through Events or simply use a Plugin to add the emails.

Step 5: Testing Email Function

To test whether the email is functioning, we will capture the customer_register_success event. That is when the customer’s account was successfully registered.

This can be created in:

app/code/HostAdvice/EmailDemo/etc/frontend/events.xml.

You should have an output like this:

<?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="ha_email_customer_register" instance="HostAdvice\EmailDemo\Observer\CustomerRegisterObserver"/>
    </event>
</config>

Step 6: Creating Observer for Sending Email

Create the observer in:

app/code/HostAdvice/EmailDemo/Observer/CustomerRegisterObserver.php.

The output should be like this:

<?php
namespace HostAdvice\EmailDemo\Observer;

use Magento\Framework\Event\ObserverInterface;
use HostAdvice\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();
    }

After the account is successfully registered, the customer should receive an email as shown in the screenshot below:

Conclusion

That’s it! These simple steps should help you send an Email successfully in Magento 2. We hope this information was useful in helping you achieve what you want.

Good Luck!

 

Check out these top 3 Magento hosting services:

Kamatera
£3.13 /mo
Starting price
Visit Kamatera
Rating based on expert review
  • User Friendly
    3.5
  • Support
    3.0
  • Features
    3.9
  • Reliability
    4.0
  • Pricing
    4.3
Hostinger
£2.34 /mo
Starting price
Visit Hostinger
Rating based on expert review
  • User Friendly
    4.7
  • Support
    4.7
  • Features
    4.8
  • Reliability
    4.8
  • Pricing
    4.7
FastComet
£1.40 /mo
Starting price
Visit FastComet
Rating based on expert review
  • User Friendly
    4.7
  • Support
    5.0
  • Features
    4.8
  • Reliability
    4.5
  • Pricing
    5.0

How To Integrate Google Adwords and Google Analytics with Magento?

This guide will help you setup Google Adwords and Google Analytics in Magento to
2 min read
Idan Cohen
Idan Cohen
Marketing Expert

How to Create Bundle Products in Magento 2

This is an easy-to-follow tutorial written to help you create a bundle product o
2 min read
Idan Cohen
Idan Cohen
Marketing Expert

How To Create a Custom Widget In Magento 2

This tutorial is compiled to help you create custom widgets in Magento to enable
3 min read
Michael Levanduski
Michael Levanduski
Expert Hosting Writer & Tester

How to Create a New Magento Theme

This tutorial will help you create a new theme in your Magento store.
3 min read
Michael Levanduski
Michael Levanduski
Expert Hosting Writer & Tester
HostAdvice.com provides professional web hosting reviews fully independent of any other entity. Our reviews are unbiased, honest, and apply the same evaluation standards to all those reviewed. While monetary compensation is received from a few of the companies listed on this site, compensation of services and products have no influence on the direction or conclusions of our reviews. Nor does the compensation influence our rankings for certain host companies. This compensation covers account purchasing costs, testing costs and royalties paid to reviewers.
Click to go to the top of the page
Go To Top