Skip to content

Prevent invoice email notification after invoice creation in Magento 2

I have used below event to stop Invoice email notification that is triggered after the invoice creation.

Vendor/Module/etc/events.xml

<?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_invoice_save_after">
      <observer name="stop_invoice_email_sending" instance="VendorModuleObserverStopInvoiceEmail" />
   </event>
</config>

Vendor/Module/Observer/StopInvoiceEmail.php

 <?php
 namespace MindtreeBilldeskObserver;

 use MagentoFrameworkEventObserver;
 use MagentoFrameworkEventObserverInterface;
 use PsrLogLoggerInterface;

 class StopInvoiceEmail implements ObserverInterface
 {
   protected $logger;

   public function __construct(LoggerInterface $logger)
    {
       $this->logger = $logger;
    }
 public function execute(Observer $observer)
 {
    try{
        $invoice = $observer->getEvent()->getInvoice();
        // Check the payment method used for the order
        $order = $invoice->getOrder();
        $payment = $order->getPayment();
        if ($payment->getMethod() === 'razorpay') {
            $this->logger->info('Razorpay method inside--');
            // Prevent sending invoice email
            $invoice->setEmailSent(true);
        }
    }catch(Exception $e){
        $this->logger->info('An error occurred: ' . $e->getMessage());
     }
   }
}

The above code is still sending the invoice email notification to the customer. Can anyone suggest how we can achieve this? Thanks in advance!!