How to send order email to a custom email address?

By: Saurabh Parekh, Nov 3rd, 2018 # Magento 2 # Email # How to

How to send order email to a custom email address - Aureate Labs

This piece of information will throw some light on to how to send an order email to a custom email address in Magento 2.

To achieve this, you just have to follow a couple of steps mentioned below:

  • Step 1: Set an email form
  • Step 2: Create a Controller file


Step 1: Set an email form

Set the email form with the input field line as given below:

<form id="send-order-email" action="<?php $block->getUrl('demomodule/order/sendemail'); ?>">
   <label>Email Address</label>
   <input type="text" class="input-text" id="email">
</form>

Step 2: Create a Controller file

Create a controller file at the path given below and add the following code: app\code\Aureatelabs\DemoModule\Controller\Order\Email
This file is based on the class \Magento\Framework\App\Action\Action and it will take the submit action from the form created in the first step.

public function execute()
{
   $email = $this->getRequest()->getParam('email');
   $order = $this->_objectManager->create('Magento\Sales\Model\Order')->load(1); // this is entity id
   $order->setCustomerEmail($email);
   if ($order) {
       try {
           $this->_objectManager->create('\Magento\Sales\Model\OrderNotifier')
               ->notify($order);
           $this->messageManager->addSuccess(__('You sent the order email.'));
       } catch (\Magento\Framework\Exception\LocalizedException $e) {
           $this->messageManager->addError($e->getMessage());
       } catch (\Exception $e) {
           $this->messageManager->addError(__('We can\'t send the email order right now.'));
           $this->_objectManager->create('Magento\Sales\Model\OrderNotifier')->critical($e);
       }
   }
}

Feel free to leave the comments below and contact us if you need any help to customize your Magento store.

Happy coding!