0

I had created the custom email template in that I declared the layout handle email template it is not working what can I do for it. I passed the data from the controller but the email is not coming with the data.

I create basic module VendorName/ModuleName inside that registration.php,module.xml,route.xml etc.

Custom Email Template

app\code\VendorName\RequestForQuote\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="VendorName_RequestForQuote_quote_email_template" label="Quote Request" file="quote" type="html" module="VendorName_RequestForQuote" area="frontend"/>

</config>

app\code\VendorName\RequestForQuote\view\frontend\email\quote.html

{{template config_path="design/email/header_template"}} <!-- pathe of template header-->

<table>
    <tr class="email-summary">
        <td>
            <h1 style="text-align:center">{{trans 'Request For Quote Mail'}}</h1>
            <h3>{{trans 'Requested Items'}}</h3>
            <p>{{trans 'Customer Name : <span class="no-link">%customer_names</span>' customer_names=$myvar1 |raw}}</p>
            <p>{{trans 'Customer Mail : <span class="no-link">%customer_email</span>' customer_email=$myvar2 |raw}}</p>
        </td>
        <td>
            {{layout handle="quote_quote_items" items=$items area="frontend"}}
        </td>
    </tr>
</table>

{{template config_path="design/email/footer_template"}} <!--footer of template-->

app\code\VendorName\RequestForQuote\Controller\Index\Index.php

<?php

namespace VendorName\RequestForQuote\Controller\Index;

use \Magento\Framework\App\Action\Context;
use \Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Contact\Model\ConfigInterface;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;

class Index extends \Magento\Framework\App\Action\Action {
    /** @var  \Magento\Framework\View\Result\Page */

    protected $resultPageFactory;
     /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /**
     * @var Context
     */
    private $context;

    /**
     * @var MailInterface
     */
    private $mail;

    /**
     * @var LoggerInterface
     */
    private $logger;
    /*** @param \Magento\Framework\App\Action\Context $context*/


     public function __construct(
        Context $context,
        ConfigInterface $contactsConfig,
        \Magento\Checkout\Model\Session $checkoutSession,
        PageFactory $resultPageFactory,
        MailInterface $mail,
        DataPersistorInterface $dataPersistor,
        LoggerInterface $logger = null
    ) {
        parent::__construct($context);
        $this->context = $context;
        $this->mail = $mail;
        $this->dataPersistor = $dataPersistor;
        $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);
        $this->resultPageFactory = $resultPageFactory;
        $this->_checkoutSession = $checkoutSession;
    }

    /**
     *
     * @return \Magento\Framework\View\Result\PageFactory
     */
    public function execute()
    {
         try {
            $this->sendEmail();
            $this->messageManager->addSuccessMessage(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $this->dataPersistor->clear('contact_us');
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->messageManager->addErrorMessage(
                __('An error occurred while processing your form. Please try again later.')
            );
            $this->dataPersistor->set('contact_us', $this->getRequest()->getParams());
        }
        $resultPage = $this->resultPageFactory->create();

        return $resultPage;
    }
    public function sendEmail()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); 

        $variablevalue1 = "Test";
        $variablevalue2 = "test@example.com";

        /* Here we prepare data for our email  */
        /* Receiver Detail  */
        $receiverInfo = [
            'name' => 'Reciver Name',
            'email' => 'reciver@email.com'
        ];


        /* Sender Detail  */
        $senderInfo = [
            'name' => 'Quote Requests',
            'email' => 'sender@email.com',
        ];



        /* Assign values for your template variables  */
        $emailTemplateVariables = array();
        $emailTempVariables['myvar1'] = $variablevalue1;
        $emailTempVariables['myvar2'] = $variablevalue2;
        $emailTempVariables['items'] = $cart->getQuote()->getAllItems();;


        /* We write send mail function in helper because if we want to 
           use same in other action then we can call it directly from helper */  

        /* call send mail method from helper or where you define it*/  
        $this->_objectManager->get('VendorName\RequestForQuote\Helper\Email')->yourCustomMailSendMethod(
              $emailTempVariables,
              $senderInfo,
              $receiverInfo
          );
    }
}

app\code\VendorName\RequestForQuote\Helper\Email.php

<?php
namespace VendorName\RequestForQuote\Helper;

/**
 * Custom Module Email helper
 */
class Email extends \Magento\Framework\App\Helper\AbstractHelper
{
    const XML_PATH_EMAIL_TEMPLATE_FIELD  = '';
    /* Here section and group refer to name of section and group where you create this field in configuration*/

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_scopeConfig;

    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * @var \Magento\Framework\Translate\Inline\StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;

    /**
     * @var string
    */
    protected $temp_id;

    /**
    * @param Magento\Framework\App\Helper\Context $context
    * @param Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    * @param Magento\Store\Model\StoreManagerInterface $storeManager
    * @param Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
    * @param Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
    */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
    ) {
        $this->_scopeConfig = $context;
        parent::__construct($context);
        $this->_storeManager = $storeManager;
        $this->inlineTranslation = $inlineTranslation;
        $this->_transportBuilder = $transportBuilder; 
    }

    /**
     * Return store configuration value of your template field that which id you set for template
     *
     * @param string $path
     * @param int $storeId
     * @return mixed
     */
    protected function getConfigValue($path, $storeId)
    {
        return $this->scopeConfig->getValue(
            $path,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $storeId
        );
    }

    /**
     * Return store 
     *
     * @return Store
     */
    public function getStore()
    {
        return $this->_storeManager->getStore();
    }

    /**
     * Return template id according to store
     *
     * @return mixed
     */
    public function getTemplateId($xmlPath)
    {
        return $this->getConfigValue($xmlPath, $this->getStore()->getStoreId());
    }

    /**
     * [generateTemplate description]  with template file and tempaltes variables values                
     * @param  Mixed $emailTemplateVariables 
     * @param  Mixed $senderInfo             
     * @param  Mixed $receiverInfo           
     * @return void
     */
    public function generateTemplate($emailTemplateVariables,$senderInfo,$receiverInfo)
    {
        $template =  $this->_transportBuilder->setTemplateIdentifier('VendorName_RequestForQuote_quote_email_template')
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND, /* here you can defile area and
                                                                                 store of template for which you prepare it */
                        'store' => $this->_storeManager->getStore()->getId(),
                    ]
                )
                ->setTemplateVars($emailTemplateVariables)
                ->setFrom($senderInfo)
                ->addTo($receiverInfo['email'],$receiverInfo['name']);
        return $this;        
    }

    /**
     * [sendInvoicedOrderEmail description]                  
     * @param  Mixed $emailTemplateVariables 
     * @param  Mixed $senderInfo             
     * @param  Mixed $receiverInfo           
     * @return void
     */
    /* your send mail method*/
    public function yourCustomMailSendMethod($emailTemplateVariables,$senderInfo,$receiverInfo)
    {
        $this->temp_id = $this->getTemplateId('VendorName_RequestForQuote_quote_email_template');
        $this->inlineTranslation->suspend();    
        $this->generateTemplate($emailTemplateVariables,$senderInfo,$receiverInfo);    
        $transport = $this->_transportBuilder->getTransport();
        $transport->sendMessage();        
        $this->inlineTranslation->resume();
    }

}

app\design\frontend\VendorName\ChildTheme\VendorName_RequestForQuote\layout\quote_quote_items.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" layout="1column">
    <body>
        <referenceBlock name="page.main.title" remove="true" />
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="Quote Page" template="VendorName_RequestForQuote::quoteItems.phtml" />
        </referenceContainer>
    </body>
</page>

app\design\frontend\VendorName\market_child\VendorName_RequestForQuote\templates\quoteItems.phtml

<?php
    $_items = $block->getItems();
    $om = \Magento\Framework\App\ObjectManager::getInstance();
    $storeManager = $om->create('\Magento\Store\Model\StoreManagerInterface');
    $thumbNail =  $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product';
    $productRepository = $storeManager = $om->create('\Magento\Catalog\Api\ProductRepositoryInterface');
    $totalAmount = 0;
?>
<div class="block block-dashboard-orders">
    <div class="block-title order"><strong>Quote Products</strong></div>
    <div class="block-content">
        <div class="table-wrapper orders-recent">
            <table class="data table table-order-items history">
                <thead>
                    <tr>
                        <th class=" col ">Sl.no</th>
                        <th class=" col ">Product Name</th>
                        <th class=" col ">Quantity</th>
                        <th class=" col ">Product Type</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $counter = 0;
                    <?php foreach ($_items as $_item): ?>
                        <?php $_product = $productRepository->getById($_item->getProductId()); ?>
                        <tr>
                            <td>
                                <?php $product_image_url =  $thumbNail . $_product->getThumbnail();?>
                                <img id='image' src="<?php echo $product_image_url; ?>" style='border-width:0px;height:80px;width:80px;'>
                            </td>
                            <td>
                                <a href="<?php echo $block->getBaseUrl() . $_item->getProduct()->getUrlKey(); ?>">
                                    <p class="product-name"><?php echo $block->escapeHtml($_item->getName()) ?></p>
                                </a>
                                <p class="sku">
                                    <b><?php /* @escapeNotVerified */ echo  __('SKU') . ' : '  ?></b>
                                    <a href="<?php echo $block->getBaseUrl() . $_item->getProduct()->getUrlKey(); ?>">
                                        <?php echo $block->escapeHtml($_item->getSku()); ?>
                                    </a>
                                </p>
                                <p class="sku">
                                    <b><?php /* @escapeNotVerified */ echo  __('Available Store') . ' : '  ?></b>
                                    <?php echo $block->escapeHtml($_product->getAvailableStore()); ?>
                                </p>
                            </td>
                            <td class="item-qty">
                                <span><?php echo $_item->getQtyOrdered() ?></span>
                            </td>
                            <td class="item-price">
                                <span><?php echo $_item->getOriginalPrice() ?></span>
                            </td>
                            <td class="item-price">
                                <span><?php echo $_item->getQtyOrdered() * $_item->getOriginalPrice() ?></span>
                            </td>
                            <?php
                            $tAmount = $_item->getQtyOrdered() * $_item->getOriginalPrice();
                            $totalAmount += $tAmount;
                            ?>
                        </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

Thanks In Advance

5
  • please show your system.xml file code also for more information
    – Msquare
    Mar 16, 2020 at 12:21
  • @Msquare i didn't include any system.xml file
    – Sabareesh
    Mar 16, 2020 at 12:29
  • I used system.xml for email sending, if you used then i will help you
    – Msquare
    Mar 16, 2020 at 13:00
  • @Msquare i don't know about system.xml can you explain or educate about it
    – Sabareesh
    Mar 16, 2020 at 13:21
  • i add link for understanding system.xml and add code to send email please check and inform me it' helps you ?
    – Msquare
    Mar 24, 2020 at 6:11

1 Answer 1

2

learn about system.xml click here link-1 and Link-2

I follow Magento Default way to send email.

app\code\VendorName\RequestForQuote\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="requestforquote" translate="label" sortOrder="201">
            <label>Request For Quote</label>
        </tab>
        <section id="quoterequest" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
            <class>separator-top</class>
            <label>Request For Quote System</label>
            <tab>requestforquote</tab>
            <resource>VendorName_RequestForQuote::quoterequest_config</resource>
            <!-- for Email Configuration -->
            <group id="email_setting"
                   translate="label"
                   type="text"
                   sortOrder="20"
                   showInDefault="1"
                   showInWebsite="1"
                   showInStore="1">
                <label>Email Configuration</label>
                <field id="quest_email"
                       translate="label"
                       type="select"
                       sortOrder="50"
                       showInDefault="1"
                       showInWebsite="1"
                       showInStore="1">
                    <label>Select Request For Quote Template</label>
                    <source_model>Magento\Config\Model\Config\Source\Email\Template</source_model>
                </field>
            </group>
        </section>
    </system>
</config>

now create email_templates.xml

app\code\VendorName\RequestForQuote\etc

email_templates.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:Magento:module:Magento_Email:etc/email_templates.xsd">
    <template id="quoterequest_email_setting_quest_email" label="Request For Quote" file="quote.html" type="html" module="VendorName_RequestForQuote" area="frontend"/>
</config>

here template id is define must be like this sectionID_groupID_fieldID which read from system.xml

now we create quote.html which define in email_templates.xml

app\code\VendorName\RequestForQuote\view\frontend\email

quote.html

{{template config_path="design/email/header_template"}} 

<h1> Email come add your content </h1>

{{template config_path="design/email/footer_template"}} 

app\code\VendorName\RequestForQuote\Helper

Email.php

<?php

namespace VendorName\RequestForQuote\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Store\Model\ScopeInterface;

class Email extends AbstractHelper
{

    const XML_PATH_EMAIL_TEMPLATE_FIELD = 'quoterequest/email_setting/quest_email';

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\Message\ManagerInterface $messageManager
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->_storeManager = $storeManager;
        $this->_transportBuilder = $transportBuilder;
        $this->messageManager = $messageManager;
    }

    public function setStoreScope()
    {
        return ScopeInterface::SCOPE_STORE;
    }

    public function getEmailTemplteName()
    {
        return $this->scopeConfig->getValue(static::XML_PATH_EMAIL_TEMPLATE_FIELD, $this->setStoreScope());
    }

    public function sendEmail($emailTemplateVariables, $senderInfo, $receiverInfo)
    {
        $store = $this->_storeManager->getStore()->getId();
        try {
            $transport = $this->_transportBuilder->setTemplateIdentifier($this->getEmailTemplteName())
                ->setTemplateOptions(['area' => 'frontend', 'store' => $store])
                ->setTemplateVars($emailTemplateVariables)
                ->setFrom($senderInfo)
                ->addTo($receiverInfo['email'], $receiverInfo['name']);
            $transport = $this->_transportBuilder->getTransport();
            $transport->sendMessage();
        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage()(__('Email send fail'));
        }
    }
}

here you have to must pass value like this

$emailTemplateVariables must be array

$senderInfo = "sender email"

$receiverInfo must be array

$receiverInfo = [];

$receiverInfo['email'] = "receiver email";

$receiverInfo['name'] = "receiver name";

now you can call any where sendEmail() method to send email.

I Hope This Helps You.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.