Sending emails in Magento 2 can help store owners in a big way when it comes to keeping relationships between customers. Although emails are a traditional communication method, yet work really well for contacting and sending information to customers. This write-up will give you all information on not only creating custom emails using a template but also sending them to any address of your choice without any hassle. Let’s start and get to know the whole nine yards of the process of send emails in Magento 2.
Guide to Send Emails in Magento 2
Suppliers and customers frequently communicate via email. You can engage with your customers using email marketing to promote your business and boost sales.
In addition to the standard email templates, many Magento 2 extensions also require their emails with unique templates, settings, and requirements. However, there are certain steps you need to follow for creating and sending emails in Magento 2. Let’s check them out one by one.
Declare Config Module
Make system.xml available in etc/adminhtml.
To load the email template in a section and organize it by app/code/Bss/EmailDemo/etc/adminhtml/system.xml, you can create a field.
<?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[Bss Commerce]]></label>
</tab>
<section id=”email” translate=”label” sortOrder=”20″ showInDefault=”1″ showInWebsite=”1″ showInStore=”1″>
<class>separator-top</class>
<label>Bss Email Demo</label>
<tab>bss</tab>
<resource>Bss_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>
Once done, check the results.
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”/>
</config>
Here’s the description for your information
- Your template ID, which you created in Step 1.
- Label: Your Label will be visible in the email dropdown.
- file: The template for your emails.
- type: The email format. module: your module.
- area: Put your email in the directory for the module. view / frontend or view / adminhtml
The next step you need to follow is:
Create Helper Email
This can be done by app/code/Bss/EmailDemo/Helper/Email.php.
<?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
) {
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(‘testmagento321@gmail.com’)
->getTransport();
$transport->sendMessage();
$this->inlineTranslation->resume();
} catch (\Exception $e) {
$this->logger->debug($e->getMessage());
}
}
}
Here’s the description for your information
- ‘Name’ is the sender’s name, and ‘Email’ is the sender’s email, therefore $sender is the sender’s information.
- setTemplateIdentifier(’email_demo_template’): The email template stated in Steps 1 and 2 has an ID of email_demo_template.
- setTemplateVars: Your email’s data or variables.
- addTo(‘testmagento321@gmail.com’): The recipient’s email can be entered here.
You can also create emails in Magento 2 using HTML. The next section will show you the whole process.
Steps to Create Email by HTML in Magento 2
Create app/code/Bss/EmailDemo/view/frontend/email/email_demo_template.html.
{{template config_path=”design/email/header_template”}}
<table>
<tr>{{trans “Wellcome To: %templateVar.” templateVar=$templateVar}}</tr>
</table>
{{template config_path=”design/email/footer_template”}}
You may also send emails using Events or add emails by using the Plugin.
Test Event
When a customer successfully registers an account, it is needed to capture the customer_register_success event to test the email function.
For making this done, 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”/>
</event>
</config>
Need to Create an Observer for Sending Emails
You can do this by creating: app/code/Bss/EmailDemo/Observer/CustomerRegisterObserver.php.
<?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();
}
}
Final Outcome
As soon as you complete the account registration process successfully, the email you want to send to your customers will prove to be successful, means will be sent. Results are assured if all the steps would be followed by you in the right manner.
How to Test Mails in Magento 2
Just in case you want to check whether your emails are hitting the customers’ inboxes without any flaws, here’s what you need to do:
Testing should follow any changes to the code responsible for sending emails and any new email configuration. If not, you run the danger of sending broken links, inaccurate purchase confirmations, and notifications of unsuccessful payments when they went through.
You can try using Mailtrap Email Sandbox for conducting a safe email testing process. The Mailtrap Email Sandbox is made to record all SMTP traffic from development and staging environments, automate test flows, look for spam in email content, and assess HTML and CSS. It will provide you with everything you need to examine and troubleshoot your emails without also harassing the receivers.
In a Nutshell
Here ends our guide on how to create and send emails in Magento 2 programmatically. If things are still not going in your favor and you want additional assistance, feel free to contact our experts at the time you fancy!
Those looking to know about adding a free shipping bar to their Magento 2 must check our guide on How to Add Magento 2 Free Shipping Bar.
2 Comments