1

I am trying to send a custom mail to vendor based on email address in one of the product attribute.

I have created following file

app/code/Company/ModuleName/view/frontend/layout/vendorinfo_order_email.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"
   label="Send Vendor Order Email" design_abstraction="custom">
   <update handle="vendorinfo_email_order_renderers"/>
   <body>
      <block class="Company\ModuleName\Block\Order\SendEmail" name="send_vendor_order_email"
         template="order/sendemail.phtml" cacheable="false">
         <block class="Magento\Framework\View\Element\RendererList" name="vendorinfo.email.order.renderers" as="renderer.list"/>
         <arguments>
            <argument name="renderer_list_name" xsi:type="string">vendorinfo.email.order.renderers</argument>
         </arguments>
      </block>
   </body>
</page>

I created renderer file

app/code/Company/ModuleName/view/frontend/layout/vendorinfo_email_order_renderers.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd" label="Email Creditmemo Items List" design_abstraction="custom">
    <body>
        <referenceBlock name="vendorinfo.email.order.renderers">
            <block class="Magento\Sales\Block\Order\Email\Items\Order\DefaultOrder" as="default" template="Magento_Sales::email/items/order/default.phtml"/>
        </referenceBlock>
    </body>
</page>

I created this sendemail.phtml

app/code/Company/ModuleName/view/frontend/templates/order/sendemail.phtml

<?php
//echo '1234';
$productDetail = $block->getProductDetail ();
$productVendor = $productDetail['productVendor'];
$orderId = $productDetail['orderId'];
$orderItemIds = $productDetail['orderItemId'];
$order = $block->getOrderDetails($orderId);
$orderItems = $order->getAllVisibleItems();

?>
<div class="table-wrapper order-items">
    <table class="data table table-order-items" id="my-orders-table">
        <thead>
            <tr>
                <th class="item-info">
                    <?= /* @escapeNotVerified */  __('Items'); ?>
                </th>
                <th class="item-qty">
                    <?= /* @escapeNotVerified */  __('Qty'); ?>
                </th>
                <th class="item-price">
                    <?= /* @escapeNotVerified */  __('Price'); ?>
                </th>
            </tr>
        </thead>
        <tbody>
<?php foreach ($orderItems as $_item): ?>
<?php
if ($_item->getParentItem()) {
    continue;
}
?>
        <tbody>
        <?= $block->getItemHtml($_item) ?>
        </tbody>
        <?php endforeach; ?>

        </tbody>
    </table>
</div>

I have created the following block

app/code/Company/ModuleName/Block/Order/SendEmail.php

<?php
namespace Company\ModuleName\Block\Order;

use Magento\Framework\View\Element\Template;

class SendEmail extends \Magento\Sales\Block\Items\AbstractItems
{
    protected $orderModel;
    protected $productModel;

    public function __construct(
        Template\Context $context
        ,\Magento\Sales\Model\Order $orderModel
        ,\Magento\Catalog\Model\Product $productModel
        , array $data = []
    )
    {
        $this->orderModel = $orderModel;
        $this->productModel = $productModel;
        parent::__construct($context, $data);
    }

    public function getOrderDetails($orderId){
        return $this->orderModel->load($orderId);
    }

    public function getProductInfo($productId){
        $product = $this->productModel->load($productId);
        $productArray = array();
        $productArray['name']=$product->getName();
        $productArray['sku']=$product->getSku();
        return $productArray;
    }
}

To trigger the email I have created following files

app/code/Company/ModuleName/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="send_order_email" label="Default Template" file="send_order_email.html" type="html" module="Company_ModuleName" area="frontend" />
</config>

Created send_order_email.html

app/code/Company/ModuleName/view/frontend/email/send_order_email.html

<!--@subject {{trans "[%full_name] You have been logged in successfully" full_name=$user.full_name}} @-->

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

<p>{{trans "Hello %full_name," full_name=$user.full_name}}</p>

{{layout handle="vendorinfo_order_email" product_detail=$user.product area="frontend"}}

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

I am calling the $this->transportBuilder->getTransport()->sendMessage(); from a controller in adminhtml. I'm getting following output

enter image description here

I'm getting the required output by not in proper format as I get in normal order email I get when order is placed.

UPDATE #1

Controller code to trigger email

app/code/Company/ModuleName/Controller/Adminhtml/Order/Index.php

<?php

namespace Company\ModuleName\Controller\Adminhtml\Order;

use Magento\Backend\App\Action;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Newsletter\Model\Template;
use Magento\Framework\Validator\EmailAddress;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Store\Model\StoreManagerInterface;

class Index extends \Magento\Backend\App\Action
{
    /**
     * @var TransportBuilder
     */
    protected $transportBuilder;

    /**
     * Validate Email Address
     *
     * @var \Magento\Framework\Validator\EmailAddress
     */
    protected $validatorEmail;

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

    /**
     * @param TransportBuilder $transportBuilder
     * @param StoreManagerInterface $storeManager
     * @param EmailAddress $validatorEmail
     */

    public function __construct(
        Action\Context $context,
        TransportBuilder $transportBuilder,
        StoreManagerInterface $storeManager,
        EmailAddress $validatorEmail
    )
    {
        parent::__construct($context);
        $this->validatorEmail = $validatorEmail;
        $this->storeManager = $storeManager;
        $this->transportBuilder = $transportBuilder;
    }

    public function execute()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance ();
        $orderModel = $objectManager->get ( 'Magento\Sales\Model\Order' );
        $productModel = $objectManager->get('Magento\Catalog\Model\Product');
        $order = $orderModel->load(26);

        $orderId = $order->getId();

        $orderItems = $order->getAllVisibleItems();
        $orderItemArray = array();
        $finalArray = array();
        foreach($orderItems as $orderItem){
            $productId = $orderItem->getProductId();
            $product = $productModel->load($productId);
            $productVendor = $product->getResource()->getAttribute('vendor_name')->getFrontend()->getValue($product);
//            $productVendor = $product->getVendorName();
            $orderItemArray['orderItemId'] = $orderItem->getId();
            $orderItemArray['productVendor'] = $productVendor;
            array_push($finalArray,$orderItemArray);
        }

        $tmp = array();

        foreach($finalArray as $arg)
        {
            $tmp[$arg['productVendor']][] = $arg['orderItemId'];
        }

        $output = array();

        foreach($tmp as $type => $labels)
        {
            $output[] = array(
                'orderId' => $orderId,
                'productVendor' => $type,
                'orderItemId' => $labels
            );
        }
        foreach($output as $o){
            // send email notification to the customer here
            $full_name = 'Test 111';

            $email = 'Test111@gmail.com';
            // checking email is valid then send email
            if ($this->validatorEmail->isValid($email)) {
                $customerObject = new \Magento\Framework\DataObject();

                $templateParams = [
                    'full_name' => $full_name,
                    'product' =>$o
                ];

                $customerObject->setData($templateParams);

                $this->transportBuilder->setTemplateIdentifier(
                    'send_order_email'
                )->setTemplateOptions(
                    [
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                        'store' => $this->storeManager->getStore()->getId(),
                    ]
                )->setTemplateVars(
                    ['user' => $customerObject]
                )->setFrom(
                    ['email' => 'Test123@gmail.com', 'name' => 'Test123']
                )->addTo(
                    $email,
                    $full_name
                );

                $transport = $this->transportBuilder->getTransport();

                try {
                    $transport->sendMessage();
                    $this->_redirect($this->_redirect->getRefererUrl());
                } catch (\Exception $e) {
                    \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug($e->getMessage());
                }
            }
        }

    }
}

Any idea why this happens?

  • can you show your controller code – MeenakshiSundaram R Nov 9 '17 at 6:56
  • I have updated the question with controller code – Nausif Nov 9 '17 at 7:09

Your Answer

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

Browse other questions tagged or ask your own question.