how to send email in magento 2 programmatically

How To Send Email In Magento 2 Programmatically

by Lily Tran

Magento 2 sending emails can help store owners so much when you want to keep relationships between them and the customers.

Keeping a long-lasting relationship between the stores and customers is necessary. Email is a standard method to help store owners contact and communicate information to their customers.

This article will give you How To Send Email In Magento 2 Programmatically.

How To Send Email In Magento 2 Programmatically: Full Steps

Email is a popular way for suppliers and customers to communicate. Email marketing allows you to communicate with your customers in order to promote your brand and increase sales.

Many Magento 2 extensions demand their own emails with specific templates, parameters, and conditions in addition to the normal email templates.

Step 1: Declare config module

Create etc/adminhtml/system.xml.

You can create a field to load the email template in the section and group 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">
    <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>

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

Step 2: 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>

In which:

  • Template ID: Your template ID you have created in Step 1.
  • Label: Your Label will show in the dropdown email.
  • File: Your email template file.
  • Type: Type of your email. module: Your module.
  • Area: Place your email in the module directory. view/frontend or view/adminhtml

>>> To learn more about customizing and configuring Magento 2 Email Templates, please read this blog: Magento 2 Email Templates: From A to Z

Step 3: Create Helper Email

Create 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());
        }
    }
}

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.

Step 4: Create Email by HTML

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 can also send Magento 2 emails through Events or use the Plugin to add emails.

Step 5: 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"/>
    </event>
</config>

Step 6: Create Observer to Send Email

Create 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();
    }
}

The Result

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

how to send email in magento 2 programmatically - the result

The result could be very great if you know the right way to do it. We hope that these simple methods for Magento 2 send email programmatically was helpful in achieving your goals.

>>> Facing email issues in Magento? Click here to learn how to fix them now! [Solved] Magento Not Sending Emails: How To Fix?

Conclusion

This is all about how to send email in Magento 2 programmatically. You can check other things in our blog to know more about Magento 2.

If you are a newbie and need to learn Magento 2 from the beginning, our blog can help: Complete Magento Tutorial For Beginners

In case you need customized solutions or technical guidance, BSS Commerce is here to ensure your success. Furthermore, we offer Magento 2 extensions to improve your store with FREE Installation – FREE 1-year Support and FREE Lifetime Update. Contact us today and let us help you overcome any challenges with expert support, available anytime.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.