Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5489

Magento2 Email From Header set twice Error in Custom Module Fixed

$
0
0

In Magento2 Email process when you will try to send email in loop you will get this error From Header set twice in most of the cases.

I have described here that how to solve this issue in our custom Magento2 Modules.

1. Create a custom TransportBuilder Class used to send the email which extends the Default
\Magento\Framework\Mail\Template\TransportBuilder Class.

Ex: File: Webkul\CustomModule\Model\Mail\TransportBuilder.php

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomModule
 * @author    Webkul
 * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

namespace Webkul\CustomModule\Model\Mail;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
     /**
     * Clears the sender from the mail
     *
     * @return Zend_Mail Provides fluent interface
     */
    public function clearFrom()
    {
        //$this->_from = null;
        $this->message->clearFrom('From');
        return $this;
    }

    public function clearSubject()
    {
        $this->message->clearSubject();
        return $this;
    }

    public function clearMessageId()
    {
        $this->message->clearMessageId();
        return $this;
    }

    public function clearBody()
    {
        $this->message->setParts([]);
        return $this;
    }

    public function clearRecipients()
    {
        $this->message->clearRecipients();
        return $this;
    }

    /**
     * Clear header from the message
     *
     * @param string $headerName
     * @return Zend_Mail Provides fluent inter
     */
    public function clearHeader($headerName)
    {
        if (isset($this->_headers[$headerName])){
            unset($this->_headers[$headerName]);
        }
        return $this;
    }
}

And now try to send Email. I have used the custom Helper Class you can paste this code wherever you need.

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomModule
 * @author    Webkul
 * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

namespace Webkul\CustomModule\Helper;

use Magento\Customer\Model\Session;

/**
 * Webkul Marketplace Helper Email.
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    const XML_PATH_EMAIL_CUSTOM_EMAIL = 'custom_config/email/custom_email_template';

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

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

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

    /**
     * @param Magento\Framework\App\Helper\Context              $context
     * @param Magento\Framework\ObjectManagerInterface          $objectManager
     * @param Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param Webkul\CustomModule\Model\Mail\TransportBuilder  $transportBuilder
     * @param Magento\Store\Model\StoreManagerInterface         $storeManager
     * @param Session                                           $customerSession
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Webkul\CustomModule\Model\Mail\TransportBuilder $transportBuilder,
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        parent::__construct($context);
        $this->_inlineTranslation = $inlineTranslation;
        $this->_transportBuilder = $transportBuilder;
        $this->_objectManager = $objectManager;
        $this->_storeManager = $storeManager;
    }

    /**
     * Return store configuration value.
     *
     * @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.
     *
     * @return mixed
     */
    public function getTemplateId($xmlPath)
    {
        return $this->getConfigValue($xmlPath, $this->getStore()->getStoreId());
    }

    public function sendEmail()
    {
        $template = $this->getTemplateId(self::XML_PATH_EMAIL_CUSTOM_EMAIL); //your email template Id
        //sending Email in Loop
        for ($i=0; $i < 5 ; $i++) {
            $this->_inlineTranslation->suspend();
            $_transportBuilder = $this->_transportBuilder;
            // clear previous data first.
            $_transportBuilder->clearFrom();
            $_transportBuilder->clearSubject();
            $_transportBuilder->clearMessageId();
            $_transportBuilder->clearBody();
            $_transportBuilder->clearRecipients();
            $_transportBuilder->setTemplateIdentifier($template)
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                        'store' => $this->_storeManager->getStore()->getId(),
                    ]
                )
                ->setTemplateVars(['myname' => 'John Doe', 'country' => 'India'])
                ->setFrom(['email' => 'myemail@example.com', 'name' => 'John Doe'])
                ->addTo('sender@example.com', 'Sender');
            try {
                $transport = $_transportBuilder->getTransport();
                $transport->sendMessage();

                $this->_inlineTranslation->resume();
            } catch (\Exception $e) {
               echo $e->getMessage();
            }
        }
    }
}

Viewing all articles
Browse latest Browse all 5489

Trending Articles