2

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;
    }
}
4
  • Have yo test your email is working or not for order and other default feature? Commented Oct 26, 2016 at 12:33
  • Email is working for order as well as customer registration process. But Email is not working for custom module.
    – Murali Raj
    Commented Oct 26, 2016 at 12:34
  • Which error are display in log file? Commented Oct 26, 2016 at 12:37
  • There is no error related to emails in log file.
    – Murali Raj
    Commented Oct 26, 2016 at 12:44

1 Answer 1

1

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;   
        }
    }
}
6
  • i have tried your code. but scopeconfig is undefined error is coming.
    – Murali Raj
    Commented Nov 2, 2016 at 6:15
  • Hi, Dhiren. I have used your code and its working fine. Now I am trying to use the same code in another module, but its not working.
    – Murali Raj
    Commented Nov 4, 2016 at 9:36
  • Is that any error show when you used in another place? And above andwer help you, accept as solution so other can also get help. Commented Nov 7, 2016 at 4:34
  • When I am including construct function I am getting blank white screen(500 internal server error). When I removed the construct function code, then the code is working. I think construct function is problem. But I used the same construct function in other module.its working.
    – Murali Raj
    Commented Nov 7, 2016 at 5:43
  • 1
    Hi @Dhiren Vasoya, let me know how to preview the email before send in front end site
    – kamal
    Commented Feb 22, 2018 at 6:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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