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:

Was this article helpful?