Magento 2 send custom email programmatically

Magento 2 send custom email

Hello reader, In this article, we are going to send a custom email template, after creating a form, on submission of that form we will send form information by sending a custom email.

This email will use custom email template.

Email is a way to communicate with customers and suppliers or vice-versa

The below files are required to send a custom email

Make sure your emails working on your server

Step 1: Declare the email template in email_templates.xml file Under app/code/Myvendor/Customemail/etc directory

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">

 <template id="customemail_email_template" label="Email Form" file="customemail.html" type="html" module="Myvendor_Customemail" area="frontend"/>     

</config>

Note : Here we have declared our email template “customemail.html” with id “customemail_email_template”.
Now let’s create an actual email template HTML file.

Step 2: Create customemail.html under app/code/Myvendor/Customemail/view/frontend/email directory

<!--@subject Sending email from my custom module @-->
 
{{template config_path="design/email/header_template"}}
<table>
     <tr class="email-intro">
         <td>
         Email: {{var email}}
         </td>
         <td>
         Name: {{var name}}
         </td>
     </tr>
 </table>
 
{{template config_path="design/email/footer_template"}}

Step 3: Our form is submitting data to post action so let’s create Post.php under app/code/Myvendor/Customemail/Controller directory

<?php
namespace Myvendor\Customemail\Controller\Index;
 
use Zend\Log\Filter\Timestamp;
use Magento\Store\Model\StoreManagerInterface;
 
class Post extends \Magento\Framework\App\Action\Action
{
    const XML_PATH_EMAIL_RECIPIENT_NAME = 'trans_email/ident_support/name';
    const XML_PATH_EMAIL_RECIPIENT_EMAIL = 'trans_email/ident_support/email';
     
    protected $_inlineTranslation;
    protected $_transportBuilder;
    protected $_scopeConfig;
    protected $_logLoggerInterface;
    protected $storeManager;
     
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Psr\Log\LoggerInterface $loggerInterface,
        StoreManagerInterface $storeManager
        array $data = []
         
        )
    {
        $this->_inlineTranslation = $inlineTranslation;
        $this->_transportBuilder = $transportBuilder;
        $this->_scopeConfig = $scopeConfig;
        $this->_logLoggerInterface = $loggerInterface;
        $this->messageManager = $context->getMessageManager();
        $this->storeManager = $storeManager;
         
        parent::__construct($context);
         
         
    }
     
    public function execute()
    {
        $post = $this->getRequest()->getPost();
        
        // Get form data in $post veriable

        try
        {
            // Send Mail 
            $this->_inlineTranslation->suspend();                  

            // Email sender Name and Email address             
            $sender = [
                'name' => $post['name'],
                'email' => $post['email']
            ];
             
            $sentToEmail = $this->_scopeConfig ->getValue('trans_email/ident_general/email',\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
             
            $sentToName = $this->_scopeConfig ->getValue('trans_email/ident_general/name',\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
             
             
            // customemail_email_template  is a template id define in email_templates.xml file
             
            $transport = $this->_transportBuilder
            ->setTemplateIdentifier('customemail_email_template')
            ->setTemplateOptions(
                [
                    'area' => 'frontend',
                    'store' => $this->storeManager->getStore()->getId()
                ]
                )
                ->setTemplateVars([
                    'name'  => $post['name'],
                    'email'  => $post['email']
                ])
                ->setFromByScope($sender)
                ->addTo($sentToEmail,$sentToName)
                //->addTo('[email protected]','info')
                ->getTransport();
                 
                $transport->sendMessage();
                 
                $this->_inlineTranslation->resume();
                $this->messageManager->addSuccess('Email sent successfully');
                $this->_redirect('your url');
                 
        } catch(\Exception $e){
            $this->messageManager->addError($e->getMessage());
            $this->_logLoggerInterface->debug($e->getMessage());
            exit;
        }         
         
    }
}

Run Below commands

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento c:f

Related Post : Create enquiry form in Magento 2

Like us on Facebook and Linkedin for more updates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top