The default Magento 2 allows the merchants to set up order confirmation Email in Magento 2, and also for the shipment and invoice generation. These email notifications are very important for the better customer shopping experience.
Sometimes, due to the stock unavailability or any other reasons, the admin has to cancel the order from the backend. However, when an order is cancelled from the backend, the order cancellation email is not sent to the customers. Therefore, if the admin cancels the order, and the customer does not receive an email. It affects shopping experience and lower the customer retention rate.
Today, I’ve come up with the solution to send email after order cancellation in Magento 2 to better notify the customers for their cancelled orders.
Programmatic Solution to Send Email after Order Cancellation in Magento 2
1. Create events.xml at app/code/Vendor/Extension/etc/
<?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_save_after"> <observer name="sales_order_save_after" instance="Vendor\Extension\Observer\OrderSaveAfter"/> </event> </config>
2. Create OrderSaveAfter.php at app/code/Vendor/Extension/Observer/
<?php namespace Vendor\Extension\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Sales\Model\Order\Email\Sender\OrderCommentSender; class OrderSaveAfter implements ObserverInterface { protected $orderCommentSender; public function __construct( OrderCommentSender $orderCommentSender ) { $this->orderCommentSender = $orderCommentSender; } public function execute(\Magento\Framework\Event\Observer $observer) { $order = $observer->getEvent()->getOrder(); if ($order->getState() == 'canceled') { $this->orderCommentSender->send($order, true); } } }
Done!
Implementing the above solution automatically sends email notification to customers after the order is cancelled from the backend.
Do consider sharing this post with Magento Community via social media.
Thank you.