Magento – How send order confirmation mail after only Payment success

magento2magento2.2order-email

I'm using Magento 2.2. Order confirmation mail was sent when checkout button trigged. So, I disabled Order mail from the Backend. I only need to send order confirmation mail/invoice from my website itself automatically when payment is done. But I'm only getting mails from PayU about credit and debit payment details.

Best Answer

I am just extending @anime answer and writing order email code

In your module create events.xml in etc folder

<?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="checkout_onepage_controller_success_action">
       <observer name="process_gateway_redirect" instance="Vendor\Module\Observer\EmailSenderAfterPayment" />
   </event>
</config>

in your Observer

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Store\Model\StoreManagerInterface;

class EmailSenderAfterPayment implements ObserverInterface
{
    /**
     * @param Observer $observer
     * @return void
     */
    private $storeManager;
    protected $_checkoutSession;
    protected $sender;  
    protected $order;   

    public function __construct(
    StoreManagerInterface $storeManager,
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Sales\Model\Order\Email\Sender\OrderSender $sender,
    \Magento\Sales\Model\Order $order

    ) {
        $this->storeManager = $storeManager;
        $this->_checkoutSession = $checkoutSession;
        $this->sender = $sender;
        $this->order = $order;

    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
       $orderIds = $observer->getOrderIds();
       $order = $this->order->load($orderIds[0]);
       $this->sender->send($order, true); //pass second param if you want to send the email asynchronous - otherwise it will be send by running corresponding cron job
       return;
    }
}
Related Topic