1

Below code is working fine for me...

Step 1 : Before override Order confirmation email templates are genereted in below path root_folder/vendor/magento/module-sales/view/frontend/templates/email/items/order/defualt.phtml

    <?php
    /**
     * Copyright © Magento, Inc. All rights reserved.
     * See COPYING.txt for license details.
     */

    // @codingStandardsIgnoreFile

    /** @var $block \Magento\Sales\Block\Order\Email\Items\DefaultItems */

    /** @var $_item \Magento\Sales\Model\Order\Item */
    $_item = $block->getItem();
    $_order = $_item->getOrder();
    ?>
    <tr>
        <td class="item-info<?php if ($block->getItemOptions()): ?> has-extra<?php endif; ?>">
            <p class="product-name"><?= $block->escapeHtml($_item->getName()) ?></p>
            <p class="sku"><?= /* @escapeNotVerified */  __('SKU') ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p>
            <?php if ($block->getItemOptions()): ?>
                <dl class="item-options">
                <?php foreach ($block->getItemOptions() as $option): ?>
                    <dt><strong><em><?= /* @escapeNotVerified */  $option['label'] ?></em></strong></dt>
                    <dd>
                        <?= /* @escapeNotVerified */  nl2br($option['value']) ?>
                    </dd>
                <?php endforeach; ?>
                </dl>
            <?php endif; ?>
            <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?>
            <?php if ($addInfoBlock) :?>
                <?= $addInfoBlock->setItem($_item)->toHtml() ?>
            <?php endif; ?>
            <?= $block->escapeHtml($_item->getDescription()) ?>
        </td>
        <td class="item-qty"><?= /* @escapeNotVerified */  $_item->getQtyOrdered() * 1 ?></td>
        <td class="item-price">
            <?= /* @escapeNotVerified */  $block->getItemPrice($_item) ?>
        </td>
    </tr>
    <?php if ($_item->getGiftMessageId() && $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_item->getGiftMessageId())):

Step 2 : After override, Override slaes modules under your theme folder like app/design/frontend/[vendor]/[template]/Magento_Sales/templates/email/items/order/defualt.phtml

    /** @var $block \Magento\Sales\Block\Order\Email\Items\DefaultItems */

    /** @var $_item \Magento\Sales\Model\Order\Item */
    $_item = $block->getItem();
    $_order = $_item->getOrder();
    /* add this line */
    $_store = $_order->getStore();
    ?>
    <tr>
        <td class="item-info<?php if ($block->getItemOptions()): ?> has-extra<?php endif; ?>">
       /* Start code for displaying product image */
          <?php
            // $_imageHelper = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Catalog\Helper\Image');
            // $_baseImageUrl = $_store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'catalog/product';

            $imageUrl = $this->helper('Magento\Catalog\Helper\Image')
            ->init($_item->getProduct(), 'product_base_image')
            ->constrainOnly(TRUE)
            ->keepAspectRatio(TRUE)
            ->keepTransparency(TRUE)
            ->keepFrame(FALSE)
            ->resize(150, 150)->getUrl();
            ?>
            <img src="<?php echo $imageUrl; ?>" alt="some" />
         /* end here  */

            <p class="product-name"><?= $block->escapeHtml($_item->getName()) ?></p>
            <p class="sku"><?= /* @escapeNotVerified */  __('SKU') ?>: <?= $block->escapeHtml($block->getSku($_item)) ?></p>
            <?php if ($block->getItemOptions()): ?>
                <dl class="item-options">
                <?php foreach ($block->getItemOptions() as $option): ?>
                    <dt><strong><em><?= /* @escapeNotVerified */  $option['label'] ?></em></strong></dt>
                    <dd>
                        <?= /* @escapeNotVerified */  nl2br($option['value']) ?>
                    </dd>
                <?php endforeach; ?>
                </dl>
            <?php endif; ?>
            <?php $addInfoBlock = $block->getProductAdditionalInformationBlock(); ?>
            <?php if ($addInfoBlock) :?>
                <?= $addInfoBlock->setItem($_item)->toHtml() ?>
            <?php endif; ?>
            <?= $block->escapeHtml($_item->getDescription()) ?>
        </td>
        <td class="item-qty"><?= /* @escapeNotVerified */  $_item->getQtyOrdered() * 1 ?></td>
        <td class="item-price">
            <?= /* @escapeNotVerified */  $block->getItemPrice($_item) ?>
        </td>
    </tr>
    <?php if ($_item->getGiftMessageId() && $_giftMessage = $this->helper('Magento\GiftMessage\Helper\Message')->getGiftMessage($_item->getGiftMessageId())):
5
  • is this file in atachment responsible to send email Commented Nov 29, 2018 at 10:31
  • Exactly,While placing order mail will generate with product name and other order description details
    – Ajithkumar
    Commented Nov 29, 2018 at 11:11
  • so override this template and add img tag somewhre in template and as src get progut url from my shaird code Commented Nov 29, 2018 at 11:12
  • should i shair code? Commented Nov 29, 2018 at 11:16
  • Sure,its pleasure to have a code from yours
    – Ajithkumar
    Commented Nov 29, 2018 at 11:36

2 Answers 2

0

1 .By Object Manager

$product_id = 1;//your product id here
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product       = $objectManager->get('Magento\Catalog\Model\Product')->load($product_id);
$store         = $objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore();
$imageUrl      = $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'catalog/product' . $product->getImage();

hope it will help to get image adn just put it in

<img src="<?php echo $imageUrl ?>">

2 .By Dependency inj.

<?php


namespace Vendor\Module\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{

    protected $resultPageFactory;

    /**
     * Constructor
     *
     * @param \Magento\Framework\App\Action\Context  $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
   \Magento\Catalog\Helper\Image $imageHelper,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,        
    .........
    ) {

        $this->imageHelper = $imageHelper;
        $this->productRepository = $productRepository;
       ......
    }

    /**
     * Execute view action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {

          try {
                $_product = $this->productRepository->getById(2);//Product id here
            } catch (NoSuchEntityException $e) {
                return 'product not found';
            }
            $image_url = $this->imageHelper->init($_product, 'product_base_image')->getUrl();
            echo $image_url;

    }
}

.... stands for other dependency

if any help nedeed comment.

16
  • Thanks for sharing dude,but inject object manager is not a good practise in magento that's the reason I did it like that
    – Ajithkumar
    Commented Nov 29, 2018 at 12:03
  • so its no phtml is not class how can you do it by dependency ingection Commented Nov 29, 2018 at 12:11
  • if you want dependency injection way i can improve ans. Commented Nov 29, 2018 at 12:11
  • Can you send me dependency injection to add product image while sending order confirmation email
    – Ajithkumar
    Commented Nov 29, 2018 at 12:40
  • Instead of using dependency injection we can go for helper class right,it's gonna reduce our line of code.
    – Ajithkumar
    Commented Nov 29, 2018 at 12:41
0

To add product images in order confirmation email in Magento 2 without using object manager, you can create a custom module and follow these steps:

  1. Create a custom module with a registration.php file in the app/code directory of your Magento installation.

  2. Create a di.xml file in the module's etc directory and add the following code to it:

    <type name="Magento\Sales\Model\Order\Email\Sender\OrderSender">
        <plugin name="add_product_image_to_order_email" type="Vendor\Module\Plugin\OrderSender" sortOrder="10" disabled="false"/>
    </type>
    

This code will create a plugin for the OrderSender class.

  1. Create a plugin class named OrderSender.php in the Vendor/Module/Plugin directory and add the following code to it:

    <?php
     namespace Vendor\Module\Plugin;
    
     use Magento\Sales\Model\Order\Email\Container\Template;
     use Magento\Sales\Model\Order\Email\Container\OrderIdentity;
     use Magento\Sales\Model\Order\Email\Sender\OrderSender as Sender;
     use Magento\Framework\Event\ManagerInterface as EventManager;
     use Magento\Framework\App\ObjectManager;
    
     class OrderSender
     {
     /**
      * @var EventManager
      */
     protected $eventManager;
    
     /**
      * @param EventManager $eventManager
      */
     public function __construct(
         EventManager $eventManager
     ) {
         $this->eventManager = $eventManager;
     }
    
     public function aroundSend(Sender $subject, \Closure $proceed, $order, $forceSyncMode = false)
     {
         $objectManager = ObjectManager::getInstance();
         $productImageHelper = $objectManager->get('\Magento\Catalog\Helper\Image');
         $productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
    
         $result = $proceed($order, $forceSyncMode);
    
         $templateContainer = $objectManager->create(Template::class, ['templateContainer' => Template::XML_PATH_EMAIL_TEMPLATE]);
    
         $productImageWidth = 200;
         $productImageHeight = 200;
    
         foreach ($order->getAllVisibleItems() as $item) {
             $product = $productRepository->get($item->getSku());
             $imageUrl = $productImageHelper->init($product, 'product_page_image_small')->resize($productImageWidth, $productImageHeight)->getUrl();
    
             $templateVars = $templateContainer->getTemplateVars();
             $templateVars['items'][$item->getId()]['product_image_url'] = $imageUrl;
             $templateContainer->setTemplateVars($templateVars);
         }
    
         return $result;
     }
      }
    

This code will add a product image URL to the email template vars for each item in the order.

  1. Create a custom email template in the app/code/Vendor/Module/view/frontend/email directory and add the following code to it:

     <!--@subject {{var order.increment_id}} - Your Order @-->
     <!--@vars
     {"store url=\"\"":"Store Url",
      "var formattedShippingAddress|raw":"Formatted Shipping Address",
       "var order.getShippingDescription()":"Shipping Description",
       "var payment_html|raw":"Payment Details",
       "var order.getBillingAddress().format('html')":"Billing Address",
       "var order.getEmailCustomerNote()":"Customer Notification",
       "layout handle=\"sales_email_order_items\" order=$order":"Order Items Grid",
        "var order.getShippingMethod()":"Shipping Method",
        "var order.getShippingDescription()":"Shipping Description",
         "var shipping_msg":"Shipping Message",
         "var gift_msg":"Gift Message",
         "var formattedDiscountAmount":"Discount Amount",
         "var formattedGrandTotal":"Order Total",
         "var formattedSubtotal":"Order Subtotal",
         "var formattedTaxAmount":"Tax Amount",
         "var invoice":"Invoice
    

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.