E-commerce is made up of several rich elements, but Email is best effective medium among all to get in touch with customers. Magento 2 comes pre-loaded with a wide range of email templates for each and every activity happened within the store environment. Magento E-commerce store is designed to send all order activity emails to their customers until products get delivered to customers but shipment plays the important role because customers are always willing to know their order shipment status until they get their products hands on.
Being a Magento developer, we always need to play with code & passed through certain requirements. Recently we need to generate shipment mail from Magento 2 environment programmatically for multiple orders. So, we decided to create a script that will help to trigger shipping email just by using order ID. Within a short period of time, we have created this script that we would like to share with you.
To use this script, you need to create a new PHP file using following code and name it as Shipment_mail.php.
Now, copy the script file to root directory of your server and simply hit the URL.
use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $obj = $bootstrap->getObjectManager(); $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $convertOrder = $objectManager->create('Magento\Sales\Model\Convert\Order'); $shipment = $convertOrder->toShipment($order); foreach ($order->getAllItems() AS $orderItem) { if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) { continue; } $qtyShipped = $orderItem->getQtyToShip(); $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped); $shipment->addItem($shipmentItem); } $shipment->register(); $shipment->getOrder()->setIsInProcess(true); try { $shipment->save(); $shipment->getOrder()->save(); $objectManager->create('Magento\Shipping\Model\ShipmentNotifier') ->notify($shipment); echo "mail success"; $shipment->save(); }
This script will automatically send email to customers tied to the account, but you can even use this code to generate shipping more than one time as per your need using the loop.
Hit below stars if this code has helped you or comment down below if you are looking for help regarding this code.
Happy Mailing!