I'm using the following code to place an order programmatically in Magento 2:
// Configure the quote $quote = $this->cart->getQuote(); $quote->setInventoryProcessed(false); $quote->setPaymentMethod('custom_gateway'); $quote->save(); // Set the payment method $payment = $quote->getPayment(); $payment->importData(['method' => 'custom_gateway']); // Update the quote $quote->collectTotals()->save(); // Place the order $this->cartManagement->placeOrder($quote->getId());
This code is creating the order as expected, but is also sending an email to the shopper.
I would like to send the confirmation email at a later stage in the process, only when the payment has been confirmed.
How can I place an order without notifying the customer? As a solution I would like to avoid turning email notifications off in the global configuration.
Thanks a lot for your answers.
Turn off automatic sending an email after order placement, and then use this code when you decide to do it at some point:
$orderid = '100000003'; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $order = $objectManager->create('Magento\Sales\Model\Order')->loadByIncrementId($orderid); $objectManager->create('Magento\Sales\Model\OrderNotifier')->notify($order);
Also, do not use ObjectManager, rather inject dependencies via constructor. I've pasted code with ObjectManager just to make it clear what should be used.
Thank you very much for this answer.
Is there a way to avoid turning off emails globally? I am working on a custom payment gateway and my worry is that if a user turns off emails globally, other payment gateways that need it might be impacted. Isn't it possible to manage this programmatically for each order placed?
public function __construct(
$this->cartRepositoryInterface = $cartRepositoryInterface;
$this->cartManagementInterface = $cartManagementInterface;
public function execute()
$cart = $this->cartRepositoryInterface->get($cart->getId());
$order_id = $this->cartManagementInterface->placeOrder($cart->getId());
we are using above method and all order place without send email, hope it will work for you.