3

I have created custom module to send feedback as a email to admin. I have created feedback link. While clicking that link, It shows popup which contains form fields, After submitted form data submitted values are passed to controller, But after submitted the form it shows below error

1 exception(s): Exception #0 (Magento\Framework\Exception\MailException): Invalid sender data

Controller

<?php

namespace XXX\YYY\Controller\Feedback;

use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\Action;
use Magento\Framework\Controller\Result\JsonFactory;
use \Magento\Framework\App\Config\ScopeConfigInterface;

class Storefeedback extends Action
{

    const XML_PATH_EMAIL_TEMPLATE = 'feedbackmail/groupmail/email_template';
    const XML_PATH_EMAIL_IDENTITY = 'feedbackmail/groupmail/sender_email_identity';
    const XML_PATH_RECIPIENT_EMAIL = 'feedbackmail/groupmail/recipient_email';

    protected $scopeConfig;
    protected $messageManager;
    protected $_request;

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

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

    public function __construct(
    Context $context, JsonFactory $resultJsonFactory
    , ManagerInterface $messageManager
    , \Magento\Framework\App\Request\Http $request
    , \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
    , \Magento\Store\Model\StoreManagerInterface $storeManager
    , ScopeConfigInterface $scopeConfig
    )
    {
        $this->messageManager = $messageManager;
        $this->_request = $request;
        $this->_transportBuilder = $transportBuilder;
        $this->_storeManager = $storeManager;

        $this->resultJsonFactory = $resultJsonFactory;
        $this->scopeConfig = $scopeConfig;
        return parent::__construct($context);
    }

    public function execute()
    {


        $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
         $templateId = $this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE, $storeScope);

         $emailReceiverName = $this->scopeConfig->getValue(self::XML_PATH_EMAIL_IDENTITY, $storeScope);

         $recipientEmail = $this->scopeConfig->getValue(self::XML_PATH_RECIPIENT_EMAIL, $storeScope);

        $data = array();
        $postdata = $this->getRequest()->getParams();

//       print_r($postdata);
         $name = $postdata['name'];
         $email = $postdata['mail-id'];
         $suggestion = $postdata['selectname'];
         $comments = $postdata['comment'];
//       exit;
         $store = $this->_storeManager->getStore()->getId();
         $transport = $this->_transportBuilder
                ->setTemplateIdentifier($templateId);
     $transport->setTemplateOptions(['area' => 'frontend', 'store' => $store]);

        $transport->setTemplateVars(['name' => $name,
            'email' => $email,
            'suggestion' => $suggestion,
            'comments' => $comments]);

        $transport->setFrom($emailReceiverName)
        // you can config general email address in Store -> Configuration -> General -> Store Email Addresses
        $transport->addTo($recipientEmail);
       // exit;
        $transport = $transport->getTransport();
        //exit;
         try {
            $transport->sendMessage();
             $data['status'] = 'success';
             $data['msg'] = "Feedback has been successfully submitted";
        } catch (\Exception $e) {
            $data['status'] = 'error';
            $data['msg'] = $e->getMessage();
        }

        $resultJson = $this->resultJsonFactory->create();
        $resultJson->setData($data);
        return $resultJson;
    }

}

email template.xml

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

<table class="message-details">
    <tr>
        <td><b>{{trans "Name"}}</b></td>
        <td>{{var data.name}}</td>
    </tr>
    <tr>
        <td><b>{{trans "Email"}}</b></td>
        <td>{{var data.mail-id}}</td>
    </tr>
    <tr>
        <td><b>{{trans "Suggestion"}}</b></td>
        <td>{{var data.suggestion}}</td>
    </tr>
</table>
<p><b>{{trans "Comments"}}</b></p>
<p>{{var data.comment}}</p>

{{template config_path="design/email/footer_template"}}
  • Hi @Sri Could you please print sender parameter which those are you passing? – Pramod Kharade Dec 30 '17 at 5:34
  • 1
    Array ( [name] => John [mail-id] => john@gmail.com [suggestion] => on delivery [comment] => Good ) 1 exception(s): Exception #0 (Magento\Framework\Exception\MailException): Invalid sender data – Jaisa Dec 30 '17 at 6:16
  • I am passing submitted form data to controller, and need to send that data to email template – Jaisa Dec 30 '17 at 6:17
  • See the updated post @Pramod Kharade – Jaisa Dec 30 '17 at 6:20
  • This one will help for you magento.stackexchange.com/questions/144885/… – Jeeva Chezhiyan Dec 30 '17 at 6:38
3

Might be problem with this line: $transport->addTo($recipientEmail);

I have implemented in my project like this:

I have created on model class. you can create helper as well and I called email function in controller like below.

app/code/Custom/ProductApproval/Controller/Adminhtml/Grid/InlineEdit.php

    <?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of InlineEdit
 *
 * @author pramod
 */

namespace Custom\ProductApproval\Controller\Adminhtml\Grid;

use Magento\Cms\Api\PageRepositoryInterface as PageRepository;
use Magento\Framework\Controller\Result\JsonFactory;
use Custom\ProductApproval\Model\ProductApprovalFactory;
use Custom\ProductApproval\Model\ProductapprovalSend;

class InlineEdit extends \Magento\Backend\App\Action {

    /** @var PageRepository  */
    protected $pageRepository;

    /** @var JsonFactory  */
    protected $jsonFactory;
    protected $productRepository;
    protected $productapprovalFactory;
    protected $authSession;
    protected $productapprovalsend;
    protected $userFactory;
    protected $_productloader;

    /**
     * @var Magento\Framework\Stdlib\DateTime\TimezoneInterface
     */
    protected $_timezoneInterface;

    public function __construct(
    \Magento\Backend\App\Action\Context $context, PageRepository $pageRepository, JsonFactory $jsonFactory, ProductApprovalFactory $productapprovalFactory, \Magento\Backend\Model\Auth\Session $authSession, ProductapprovalSend $productapprovalsend, \Magento\User\Model\UserFactory $userFactory, \Magento\Catalog\Model\ProductFactory $_productloader, \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezoneInterface
    ) {
        parent::__construct($context);
        $this->pageRepository = $pageRepository;
        $this->jsonFactory = $jsonFactory;
        $this->productapprovalFactory = $productapprovalFactory;
        $this->authSession = $authSession;
        $this->productapprovalsend = $productapprovalsend;
        $this->userFactory = $userFactory;
        $this->_productloader = $_productloader;
        $this->_timezoneInterface = $timezoneInterface;
    }

    /**
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute() {
        /** @var \Magento\Framework\Controller\Result\Json $resultJson */
        $resultJson = $this->jsonFactory->create();
        $error = false;
        $messages = [];
        $postItems = $this->getRequest()->getParam('items', []);
        $user = $this->authSession->getUser();

        $user_id = $user->getUserId();
        foreach ($postItems as $post_key => $post_value) {
            $data = array();
            $data['remarks'] = $post_value['remarks'];
            $data['product_information'] = $post_value['entity_id'];
            $data['product_status'] = $post_value['product_status'];

            if (!($this->getRequest()->getParam('isAjax') && count($postItems))) {
                return $resultJson->setData([
                            'messages' => [__('Please correct the data sent.')],
                            'error' => true,
                ]);
            }

            $productId = $post_value['entity_id'];
            $product = $this->_productloader->create()->load($productId);

            $today_date = $this->_timezoneInterface->date()->format('Y-m-d H:i:00');
            // $live_date = '';
            // $dateTime = $product->getGoLiveDateTime();
            // $hour = $product->getGoLiveDateHours();
            // $mins = $product->getGoLiveDateMinutes();
            // if($dateTime){
            //     $dateTime = explode(' ', $dateTime);
            //     $date = $dateTime[0];
            //     $live_date = $date." ".$hour.":".$mins.":00";
            // }
            $live_date = $product->getGoLiveDateTime();
            $live_date = $this->_timezoneInterface->date($live_date)->format('Y-m-d H:i:00');

            if (strtotime($live_date) >= strtotime($today_date)) {

                $this->productapprovalFactory->create()->addProductsInline($postItems);

                $product_log = $this->_objectManager->create('\Custom\ProductApproval\Model\ProductLog');
                $data['user_id'] = $user_id;
                $product_log->setData($data);
                $product_log->save();
                $user = $this->userFactory->create()->load($user_id);
                $this->productapprovalsend->productApprovalMail($data['product_information'], $data['remarks'], $data['product_status'], $user->getEmail());
            } else {
                return $resultJson->setData([
                            'messages' => [__('Go Live date has been passed.')],
                            'error' => true
                ]);
            }
        }

        return $resultJson->setData([
                    'messages' => $messages,
                    'error' => $error
        ]);
    }

}

app/code/Custom/ProductApproval/Model/ProductapprovalSend.php

    <?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Custom\ProductApproval\Model;

/**
 * Description of ProductapprovalSend
 *
 * @author pramod
 */
use Magento\Framework\Mail\Template\TransportBuilder;

class ProductapprovalSend {

    //put your code here
    protected $productRepository;

    public function __construct(
    TransportBuilder $transportBuilder, \Magento\Catalog\Model\ProductRepository $productRepository, \Magento\User\Model\UserFactory $userFactory
    ) {
        $this->transportBuilder = $transportBuilder;
        $this->productRepository = $productRepository;
    }

    public function execute() {

    }

    public function productApprovalMail($product_information, $remarks, $product_status, $useremail) {
        $product = $this->productRepository->get($product_information);
        $report = array(
            'sku' => $product_information,
            'name' => $product->getName(),
            'product_status' => $product_status,
            'remarks' => $remarks
        );

        $postObject = new \Magento\Framework\DataObject();
        $postObject->setData($report);

        $transport = $this->transportBuilder
                ->setTemplateIdentifier('productapproval_status_template')
                ->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_ADMINHTML, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID])
                ->setTemplateVars(['data' => $postObject])
                ->setFrom(['name' => 'Goshop Product Approval', 'email' => 'pramodblazeclan@gmail.com'])
                ->addTo([trim($useremail)])
                ->getTransport();
        $transport->sendMessage();
    }

}

app/code/Custom/ProductApproval/view/adminhtml/email/productapproval_status_template.html

<!--@subject {{trans "Products Approval Status Update "}} @-->

<!--@styles
body,td { color:red; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif; }
@-->

<p><b>Product Sku:</b> {{var data.sku|raw}}</p>
<p><b>Product Name:</b> {{var data.name|raw}}</p>
<p><b>Remarks:</b> {{var data.remarks|raw}}</p>
<p><b>Product Approval Status:</b> {{var data.product_status|raw}}</p>

hope so you will get some extend an idea .

  • 1
    Thanks @Pramod Kharade for the answer. I've set my email template in the same manner and it's working fine. – Parth Thakkar Jan 2 '18 at 5:13

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.