Magento 2 – How to Send Order Confirmation Email Template

email-templatesmagento2order-emailsales-order

I am trying to send an order email confirmation with adding extra attributes values to Admin, But it's not working for me.

Here I have 2 Email templates.

1) It's a default email template

2) Customized email template

First one is the default, and it will send Magento by default.

For the second one I tried below code, it's printing as it is table format.

<?php

namespace ABCSolutions\AvailableStore\Observer;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Store\Model\StoreManagerInterface;


class AfterPlaceOrderObserver implements \Magento\Framework\Event\ObserverInterface{


    /**
     * Store model manager
     *
     * @var StoreManagerInterface
     */
    protected $storeManager;

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

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

    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $_productLoader;

    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var \Magento\Sales\Model\Order
     */
    protected $_order;

    /**
     * @var \Magento\Sales\Model\OrderNotifier
     */
    protected $_orderNotifier;

    /**
     * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
     * @param ProductRepositoryInterface $productRepository
     * @param StoreManagerInterface $storeManager
     * @param \Magento\Sales\Model\Order $order
     * @param \Magento\Sales\Model\OrderNotifier $orderNotifier
     */
    public function __construct(
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        //\Magento\Catalog\Model\ProductFactory $_productLoader
        ProductRepositoryInterface $productRepository,
        StoreManagerInterface $storeManager,
        \Magento\Sales\Model\Order $order,
    \Magento\Sales\Model\OrderNotifier $orderNotifier
    ){
        $this->_inlineTranslation = $inlineTranslation;
        $this->_transportBuilder = $transportBuilder;
        //$this->_productLoader = $_productLoader;
        $this->productRepository = $productRepository;
        $this->storeManager = $storeManager;
        $this->_order = $order;
        $this->_orderNotifier = $orderNotifier;
    }

    /**
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        /* @var $order \Magento\Sales\Model\Order */
        $order = $observer->getEvent()->getOrder();

        $templateOptions = array('area' => \Magento\Framework\App\Area::AREA_FRONTEND,'store' => 1);
        $mediaPath = $this->storeManager->getStore(1)->getBaseURL(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product';

        $table = "";
        $table .= "<table>";
        $table .= "<thead>";
        $table .= "<tr>";
        $table .= "<th>";
        $table .= "Product Image";
        $table .= "</th>";
        $table .= "<th>";
        $table .= "Product Name";
        $table .= "</th>";
        $table .= "<th>";
        $table .= "Qty.";
        $table .= "</th>";
        $table .= "<th>";
        $table .= "Price";
        $table .= "</th>";
        $table .= "</tr>";
        $table .= "</thead>";
        //start foreach for items
        foreach($order->getAllItems() as $_items){

            $_product = $this->productRepository->getById($_items->getProductId());
            $imageThumbNail = $mediaPath . $_product->getThumbnail();
            $pSKU=$_product->getSku();
            $productName = $_product->getName();
            $QtyOrdered = $_items->getQtyOrdered();
            $pPrice = $_product->getPrice();
            $CAField = $_product->getCustomAttributeField();

            $table .= "<tr>";
            $table .= "<td style='width: 120px;text-align: center;'>";
            $table .= "<img src='$imageThumbNail' title='$productName' style='width: 70px;height: 70px;' />";
            $table .= "</td>";
            $table .= "<td style='width: 200px;'>";
            $table .= "<table>";
            $table .= "<tr>";
            $table .= "<td>";
            $table .= "<span style='color: Blue;'>SKU: </span>";
            $table .= "</td>";
            $table .= "<td>";
            $table .= " <span>$pSKU</span>";
            $table .= "</td>";
            $table .= "</tr>";
            $table .= "<tr>";
            $table .= "<td>";
            $table .= "<span style='color: Blue;'>Cust. Attr. Field: </span>";
            $table .= "</td>";
            $table .= "<td>";
            $table .= "<span style='font-size: 14px;'>$CAField</span>";
            $table .= "</td>";
            $table .= "</tr>";
            $table .= "</table>";
            $table .= "</td>";
            $table .= "<td style='width: 50px;text-align: center;'>";
            $table .= "<span>$QtyOrdered</span>";
            $table .= "</td>";
            $table .= "<td style='text-align: center;'>";
            $table .= "<span>$pPrice</span>";
            $table .= "</td>";
            $table .= "</tr>";

        }

        //end foreach
        $table .= "</table>";

        $mass = $table;

        $templateVars = array(
            'store' => 1,
            'orderNumber' => $order->getIncrementId(),
            'customer_name' => $order->getCustomerName(),
            'message'  => $mass
        );

        $from = array(
            'email' => 'info@gmail.com',
            'name' => 'Customer Care'
        );

        $to = "abc@gmail.com";
        try {
            $this->_inlineTranslation->suspend();
            $to = array($to);
            $transport = $this->_transportBuilder->setTemplateIdentifier('custom_email_template')
                ->setTemplateOptions($templateOptions)
                ->setTemplateVars($templateVars)
                ->setFrom($from)
                ->addTo($to)
                ->getTransport();
            $transport->sendMessage();
            $this->_inlineTranslation->resume(); 
        }
        catch (\Exception $e)
        {
            echo $e->getMessage();
        }
    }

}

It's printing table format, like below image.

enter image description here

Please suggest us to send the email of order email copy with extra attributes?

Best Answer

Solved my self, for the Reference of Thread.

create email_templates.xml file from etc folder and paste below code.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">
    <template id="available_store_template" label="Available Store" file="available_store.html" type="html" module="ABCSolutions_AvailableStore" area="frontend"/>
</config>

Create available_store.html file from view/frontend/email folder and paste below code.

<!--@subject Available Stores for the Order of : {{var orderNumber}} @-->
<!--@vars
{"store url=\"\"":"Store Url",
"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image"}
@-->
<!--@styles
body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif; }
@-->
{{template config_path="design/email/header_template"}}
<div style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
    <table cellspacing="0" cellpadding="0" border="0" width="100%">
        <tr>
            <td align="center" valign="top" style="padding:20px 0 20px 0">
                <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                    <tr>
                        <td valign="top">
                            <h1 style="font-size:22px;font-weight:normal;line-height:22px;margin:0 0 11px 0;">{{trans "Hello Supervisor"}},</h1>
                        </td>
                    </tr>
                    <tr>
                        <td valign="top">
                            <h1 style="font-size:22px;font-weight:normal;line-height:22px;margin:0 0 11px 0;">{{trans "Please find below order information."}}</h1>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            {{layout handle="email_product_list" items=$items area="frontend"}}
                        </td>
                    </tr>
                    <tr>
                        <td valign="top">
                            <h1 style="font-size:22px;font-weight:normal;line-height:22px;margin:0 0 11px 0;">{{trans "If you have any queries, Please contact Admin: +91 9949906633"}}</h1>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div>
 {{template config_path="design/email/footer_template"}}

Create events.xml file from etc folder and paste below code.

<?xml version="1.0"?> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_place_after">
        <observer name="send_available_store_order_items" instance="ABCSolutions\AvailableStore\Observer\AfterPlaceOrderObserver" />
    </event>
</config>

Create AfterPlaceOrderObserver.php file from Observer folder and paste below code.

public function execute(\Magento\Framework\Event\Observer $observer)
    {
        /* @var $order \Magento\Sales\Model\Order */
        $order = $observer->getEvent()->getOrder();

        $templateOptions = array('area' => \Magento\Framework\App\Area::AREA_FRONTEND,'store' => 1); 

        $templateVars = array(
            'store' => 1,
            'orderNumber' => $order->getIncrementId(),
            'customer_name' => $order->getCustomerName(),
            'items'=> $order->getAllItems(),
        );

        $from = array(
            'email' => 'info@gmail.in',
            'name' => 'Customer Care'
        );

        $to = "abc@gmail.com";
        try {
            $this->_inlineTranslation->suspend();
            $to = array($to);
            $transport = $this->_transportBuilder->setTemplateIdentifier('available_store_template')
                ->setTemplateOptions($templateOptions)
                ->setTemplateVars($templateVars)
                ->setFrom($from)
                ->addTo($to)
                ->getTransport();
            $transport->sendMessage();
            $this->_inlineTranslation->resume();
        }
        catch (\Exception $e)
        {
            echo $e->getMessage();
        }
    }

create layout file email_product_list.xml from view/frontend/layout and paste below code.

<?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="Email Product List" design_abstraction="custom">
    <body>
        <block class="Magento\Framework\View\Element\Template" name="additional.product.info" template="ABCSolutions_AvailableStore::email/product.phtml"/>
    </body>
</page>

And create product.phtml file from view/frontend/templates/email and paste below code.

<?php $_items = $block->getItems() ?>
<table class="email-items">
    <thead>
    <tr>
        <th class="item-info">
            <?= /* @escapeNotVerified */  __('Product Image'); ?>
        </th>
        <th class="item-info">
            <?= /* @escapeNotVerified */  __('Product Name'); ?>
        </th>
        <th class="item-qty">
            <?= /* @escapeNotVerified */  __('Qty'); ?>
        </th>
        <th class="item-qty">
            <?= /* @escapeNotVerified */  __('Each Price'); ?>
        </th>
        <th class="item-price">
            <?= /* @escapeNotVerified */  __('Total Price'); ?>
        </th>
    </tr>
    </thead>
    <tbody>
    <?php
        $om = \Magento\Framework\App\ObjectManager::getInstance();
        $storeManager = $om->create('\Magento\Store\Model\StoreManagerInterface');
        $thumbNail =  $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product';
        $productRepository = $storeManager = $om->create('\Magento\Catalog\Api\ProductRepositoryInterface');
        $totalAmount = 0;
    ?>
    <?php foreach ($_items as $_item): ?>
        <?php $_product = $productRepository->getById($_item->getProductId()); ?>
        <tr>
            <td>
                <?php $product_image_url =  $thumbNail . $_product->getThumbnail();?>
                <img id='image' src="<?php echo $product_image_url; ?>" style='border-width:0px;height:80px;width:80px;'>
            </td>
            <td>
                <a href="<?php echo $block->getBaseUrl() . $_item->getProduct()->getUrlKey(); ?>">
                    <p class="product-name"><?php echo $block->escapeHtml($_item->getName()) ?></p>
                </a>
                <p class="sku">
                    <b><?php /* @escapeNotVerified */ echo  __('SKU') . ' : '  ?></b>
                    <a href="<?php echo $block->getBaseUrl() . $_item->getProduct()->getUrlKey(); ?>">
                        <?php echo $block->escapeHtml($_item->getSku()); ?>
                    </a>
                </p>
                <p class="sku">
                    <b><?php /* @escapeNotVerified */ echo  __('Available Store') . ' : '  ?></b>
                    <?php echo $block->escapeHtml($_product->getAvailableStore()); ?>
                </p>
            </td>
            <td class="item-qty">
                <span><?php echo $_item->getQtyOrdered() ?></span>
            </td>
            <td class="item-price">
                <span><?php echo $_item->getOriginalPrice() ?></span>
            </td>
            <td class="item-price">
                <span><?php echo $_item->getQtyOrdered() * $_item->getOriginalPrice() ?></span>
            </td>
            <?php
            $tAmount = $_item->getQtyOrdered() * $_item->getOriginalPrice();
            $totalAmount += $tAmount;
            ?>
        </tr>
    <?php endforeach; ?>
        <tr>
            <td colspan="4" style="text-align: right;font-size: 16px;font-weight: bold;">
                <span>Total: </span>
            </td>
            <td style="text-align: right;font-size: 16px;font-weight: bold;">
               <span><?php echo $totalAmount ?></span>
            </td>
        </tr>
    </tbody>
</table>