Magento 2: Fast way to debug on emails

Magento 2 sends emails in many occasions. For example, it will send an order success email whenever an order is placed in the site. If we want to customize or fix something in this email then we make some changes in the email template or in the backend logic of it and then place an order to see the changes are working properly in the email sent. This can be a cumbersome process and definitely time consuming job.

Solution: Magento Dev console

We can rely on the console interfaces which Magento 2 CLI provides in order to debug this case. The command for this would be:

bin/magento dev:console

With this command, you will have access to the nice $di variable which is an instance of \Magento\Framework\App\ObjectManager. With this variable $di, we can access any class in Magento and do some dirty works quickly.

Snippet to trigger order success email

Below is the code snippet that I prepared to send an order success email from the dev console interface

use Magento\Sales\Model\Order\Email\Sender\OrderSender;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Framework\App\State;
use Magento\Framework\App\Area;

$state = $di->get(State::class);
$order = $di->get(OrderInterface::class);
$sender = $di->get(OrderSender::class);

$state->setAreaCode(Area::AREA_ADMINHTML);
$order->load(25);

$sender->send($order);

Here 25 is the order id for which we need to send an email. You need to copy paste this code in the interface only once. After that, when you want to send the email for debugging, just execute $sender->send($order); in the console interface and you will see the email in your inbox.

I hope this will help you to debug emails faster next time 🙂

Rajeev K Tomy

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top