Looking to know how to send emails in Magento 2? Check this all-inclusive guide and learn all about programmatically sending emails in Magento 2
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.
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.
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.
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
The next step you need to follow is:
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
You can also create emails in Magento 2 using HTML. The next section will show you the whole process.
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.
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>
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();
}
}
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.
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.
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.
Responsive design means a design that fits all screen display sizes. The truth is that…
Shopify, the e-commerce giant, has revolutionized the way businesses operate online. From small startups to…
Are you bothered by Shopify variant images not working issue? Check this how-to guide and…
eCommerce alcohol sales in 16 markets are expected to increase by over a third, reaching…
Google Search Console to discontinue Product Results Report Feature. Get the latest updates on changes…
Why Shopify is bad for eCommerce’! Shopify is used by thousands of businesses worldwide, but…
View Comments
Your insightful points have truly captivated a new reader like me. I thoroughly enjoyed your post on How to Send Emails in Magento. It's clear that your content is not only valuable but also leaves a lasting impression. As a new follower, I'm eager to explore more of your recent posts. Do you have any specific recommendations or updates related to the topic you discussed a few days ago? I'm looking forward to more of your certain and enlightening insights!
Thank you so much for your positive feedback! We're thrilled to hear that you found our post on 'How to Send Emails in Magento 2' valuable. Your enthusiasm as a new reader means a lot to us. We're constantly working to provide insightful and helpful content. If you have any specific topics or questions you'd like us to cover in the future, feel free to let us know. We appreciate your support and look forward to bringing you more engaging and informative posts in the days ahead!