Magento – Magento 2 send order & invoice email manually

magento2sales-order

I tried to disable magento 2 send email order and invoice automatically (after place an order and invoice an order) by disable send email in configration Store > Configuration > Sales > Sales Emails. But when i tried to send manually by clicking send email button or do it programmatically it won't send the email, unless i enable send order email in configuration again.

enter image description here

programmatically

$order = $objectManager->create('\Magento\Sales\Model\Order')
                           ->load(225);
      $objectManager->create('Magento\Sales\Model\OrderNotifier')->notify($order);

Best Answer

This is intended behavior. If you disable the order e-mails under Configuration -> Sales Emails then no new order e-mails will get send. Not only from simply placing an order, but it's also disabled when you try to manually send the e-mail.

In case of an order this behavior comes from the send method in Magento\Sales\Model\Order\Email\Sender\OrderSender. (For invoices this is Magento\Sales\Model\Order\Email\Sender\InvoiceSender)

You could modify this behavior with your own plugin if you so desire.

-Edit-

How you do this is entirely dependant on your specific needs. But one example could be to make a custom model that extends the OrderSender and skips the check for the configuration setting:

app/code/Vendor/Myplugin/Model/Order/CustomOrderSender.php

<?php

namespace Vendor\Myplugin\Model\Order;

use Magento\Sales\Model\Order;

class CustomOrderSender extends \Magento\Sales\Model\Order\Email\Sender\OrderSender
{

    protected function checkAndSend(Order $order)
    {
        $this->identityContainer->setStore($order->getStore());        
        $this->prepareTemplate($order);

        /** @var SenderBuilder $sender */
        $sender = $this->getSender();

        try {
            $sender->send();
            $sender->sendCopyTo();
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());
        }

        return true;
    }
}

Then in your controller / custom method / wherever, you would include this model instead of the default option.

<?php

public function __construct(
    \Vendor\Myplugin\Model\Order\CustomOrderSender $customOrderSender,
    \Magento\Sales\Api\OrderRepositoryInterface $orderRepositoryInterface,
) {
    $this->customOrderSender = $customOrderSender;
    $this->orderRepositoryInterface = $orderRepositoryInterface;
}

public function send() {
    $order = $this->orderRepositoryInterface->get(<order_id>);
    $this->customOrderSender->send($order);
}
Related Topic