Magento 2 – Custom Email for Custom Module

emailmagento2module

I am trying to send emails from my custom module. But its not working.

1.) Created Email template with following path,

app/code/module/namespace/view/frontend/email/myemail.phtml

<!--@subject MY EMAIL SUBJECT HERE @-->
{{template config_path="design/email/header_template"}} 
<table><tr class="email-intro"><td>
 <p class="greeting">{{trans "%myname," customer_name=$data.myname}}</p>
 <p class="greeting">{{trans "%myemail," customer_email=$data.myemail}}</p>
 </td></tr></table>
{{template config_path="design/email/footer_template"}}

2.) Declared email template in xml file.

app/code/module/namespace/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="mymodule_email_template" label="Email Form" file="myemail.html" type="html" module="Jute_Ecommerce" area="frontend"/>
</config>

3.) In my controller file,

public function execute()
{
    $post = $this->getRequest()->getPostValue(); 
    $this->inlineTranslation->suspend();
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $customerSession = $objectManager->create('Magento\Customer\Model\Session');

    try {
        $postObject = new \Magento\Framework\DataObject();
        $post['myname'] = $customerSession->getCustomer()->getName(); //Loggedin customer Name
        $post['myemail'] = $customerSession->getCustomer()->getEmail(); 

        //Loggedin customer Email
        $postObject->setData($post);

        $myname = $post['myname'];
        $myemail = $post['myemail'];

        $sender = [
            'name' => $this->_escaper->escapeHtml($myname),
            'email' => $this->_escaper->escapeHtml($myemail),
        ];

        $sentToEmail = $this->scopeConfig->getValue('trans_email/ident_support/email',ScopeInterface::SCOPE_STORE);
        $sentToname = $this->scopeConfig->getValue('trans_email/ident_support/name',ScopeInterface::SCOPE_STORE);

        $senderToInfo = [
            'name' => $this->_escaper->escapeHtml($sentToname),
            'email' => $this->_escaper->escapeHtml($sentToEmail),
        ];

        $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; 
        $transport = $this->_transportBuilder
            ->setTemplateIdentifier('mymodule_email_template') // My email template
            ->setTemplateOptions( [
                'area' => \Magento\Framework\App\Area::AREA_FRONTEND, // this is using frontend area to get the template file if admin then \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE
                'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
            ])
            ->setTemplateVars(['data' => $postObject])
            ->setFrom($sender)
            ->addTo($senderToInfo)
            ->addBcc($senderBcc)
            ->getTransport();

        $transport->sendMessage();

        $this->inlineTranslation->resume();
        $this->messageManager->addSuccess(__('Thanks'));

        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setRefererOrBaseUrl();
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setRefererOrBaseUrl();

        return $resultRedirect;
    } catch (\Exception $e) {
        $this->inlineTranslation->resume();
        $this->messageManager->addError(__('Try again'));

        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setRefererOrBaseUrl();
        return $resultRedirect;
    }
}

Best Answer

I am used the following code to send email in my custom extension. And it working fine.

namespace [Vender]\[Extension]\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use \Magento\Framework\Mail\Template\TransportBuilder;
use \Magento\Framework\Translate\Inline\StateInterface;
use Psr\Log\LoggerInterface;

class Sendmail extends \Magento\Framework\App\Action\Action
{
    const XML_PATH_EMAIL_ADMIN_QUOTE_SENDER = 'Email Sender';
    const XML_PATH_EMAIL_ADMIN_QUOTE_NOTIFICATION = 'Your Template Path';
    const XML_PATH_EMAIL_ADMIN_NAME = 'Sender Name';
    const XML_PATH_EMAIL_ADMIN_EMAIL = 'Receiver Email';

    protected $inlineTranslation;
    protected $transportBuilder;
    protected $_logLoggerInterface;

    public function __construct(
    Context $context,
    StateInterface $inlineTranslation,
    TransportBuilder $transportBuilder,
    LoggerInterface $logLoggerInterface,
    array $data = [])
    {
        $this->inlineTranslation = $inlineTranslation;
        $this->transportBuilder = $transportBuilder;
        $this->_logLoggerInterface = $logLoggerInterface;
        parent::__construct($context,$data);
    }


    public function execute()
    {
        try
        {

            // Send Mail
            $this->inlineTranslation->suspend();
            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $transport = $this->transportBuilder
               ->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_ADMIN_QUOTE_NOTIFICATION, $storeScope))
               ->setTemplateOptions(
                    [
                        'area' => 'frontend',
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                    ]
                )
               ->setTemplateVars([
                    'var1'  => 'Value',
                    'var2'  => 'Value'
                ])
               ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_ADMIN_QUOTE_SENDER, $storeScope))
               ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_ADMIN_EMAIL, $storeScope))
               ->getTransport();
            $transport->sendMessage();
            $this->inlineTranslation->resume();
        } catch(\Exception $e){
            $this->_logLoggerInterface->debug($e->getMessage());
            exit;   
        }
    }
}
Related Topic