Magento2 How to send emails with custom email templates

Sometimes we have a requirement like to send out our custom email notifications with custom defined email template format. To customize this need, we have explained below how we can achive this task.

Let's see how we can create our custom module extension for this purpose.

Step 1: Create our module registration php file as registration.php.

Location: app/code/Magemeta/SendMail/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magemeta_SendMail',
    __DIR__
);

Location: app/code/Magemeta/SendMail/etc/module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Magemeta_SendMail" setup_version="1.0.0">
</module>
</config>

Step 2: Create our custom email_templates.xml file to declare and assign the test_template.html email template.

Location: app/code/Magemeta/SendMail/etc/email_templates.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">
    <template id="magemeta_email_email_template" label="Test Email" file="test_template.html" type="html" module="Magemeta_SendMail" area="frontend"/>
</config>

Step 3: Create our custom test_template.html file to define email content.

Location: app/code/Magemeta/SendMail/view/frontend/email/test_template.html

<!--@subject {{trans "You've been sent from %store_name" store_name=$store.getFrontendName() |raw}} @-->
{{template config_path="design/email/header_template"}}
<p>This is our custom email with {{ var emailMsg}}</p>
{{template config_path="design/email/footer_template"}}

Step 4: Create admin custom system configuration to select our email template.

Location: app/code/Magemeta/SendMail/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="magemeta" translate="label" sortOrder="200">
            <label>Magemeta</label>
        </tab>
        <section id="magemeta" showInDefault="1" showInStore="1" showInWebsite="1" sortOrder="10" 
        translate="label">
            <label>Magemeta</label>
            <tab>magemeta</tab>
            <resource>Magemeta_SendMail::magemeta_sendemail</resource>
            <group id="email" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" 
            showInStore="1">
                <label>Email Options</label>
                <field id="recipient_email" translate="label" type="text" sortOrder="10" showInDefault="1" 
                showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Send Emails To</label>
                    <validate>validate-email</validate>
                </field>
                <field id="sender_email" translate="label" type="select" sortOrder="20" showInDefault="1" 
                showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Email Sender</label>
                    <source_model>Magento\Config\Model\Config\Source\Email\Identity</source_model>
                </field>
                <field id="email_template" translate="label comment" type="select" sortOrder="30" 
                showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Email Template</label>
                    <comment>Email template chosen based on theme fallback when "Default" option is 
                    selected.</comment>
                    <source_model>Magento\Config\Model\Config\Source\Email\Template</source_model>
                </field>
            </group>
        </section>
    </system>
</config>

Step 5: Create admin access control list xml to define the custom email resource.

Location: app/code/Magemeta/SendMail/etc/acl.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Magento_Backend::stores">
                    <resource id="Magento_Backend::stores_settings">
                        <resource id="Magento_Config::config">
                            <resource id="Magemeta_SendMail::magemeta_sendemail" title="magemeta"/>
                        </resource>
                    </resource>
                </resource>                
            </resource>
        </resources>
    </acl>
</config>


Step 6: Create our custom helper file to send emails.

Location: app/code/Magemeta/SendMail/Helper/Sendmail.php

<?php

namespace Magemeta\SendMail\Helper\Sendmail;

use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\Action;

/**
 * Class Sendmail
 * @package Magemeta\SendMail\Helper\Sendmail
 */
class Sendmail extends Action
{
/**
     * Recipient email config path
     */
    const XML_PATH_EMAIL_RECIPIENT = 'magemeta/email/recipient_email';

    /**
     * Sender email config path
     */
    const XML_PATH_EMAIL_SENDER = 'magemeta/email/sender_email';

    /**
     * Email template config path
     */
    const XML_PATH_EMAIL_TEMPLATE = 'magemeta/email/email_template';


    /**
     * @var StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * @var StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var TransportBuilder
     */
    protected $_transportBuilder;

    /**
     * Sendmail constructor
     * @param StoreManagerInterface $storeManager
     * @param StateInterface $inlineTranslation
     * @param TransportBuilder $transportBuilder
     */
    public function __construct(
        StoreManagerInterface $storeManager,
        StateInterface $inlineTranslation,
        TransportBuilder $transportBuilder
    )
    {
        $this->storeManager = $storeManager;
        $this->inlineTranslation = $inlineTranslation;
        $this->transportBuilder = $transportBuilder;
    }

    public function sendEmail()
    {
    $emailMsg = 'This is test email content';
        $emailTempVariables['emailMsg'] = $emailMsg;
        $this->inlineTranslation->suspend();
        try {
            $transport = $this->transportBuilder
                ->setTemplateIdentifier(self::XML_PATH_EMAIL_TEMPLATE)
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                        'store' => $this->storeManager->getStore()->getId()
                    ]
                )
                ->setTemplateVars($emailTempVariables)
                ->setFrom(self::XML_PATH_EMAIL_SENDER)
                ->addTo(self::XML_PATH_EMAIL_RECIPIENT)
                ->getTransport();

            $transport->sendMessage();
        } catch (\Exception $e) {
            echo $e->getMessage();
        } finally {
            $this->inlineTranslation->resume();
        }
    }
}

This is about the custom email sending module customization.
Hope this is helpful guys!

 

Leave a Reply