magento2 – Magento 2 :How to override MagentoSalesModelOrderEmailSender.php model?

If you want to override the model MagentoSalesModelOrderEmailSenderOrderSender just to extend the method prepareTemplate in order to add or modify email order template variables or change the template id, then its not the recommended approach.

Better observe the event email_order_set_template_vars_before and in your observer method add or modify the order email template variables as per your requirement.

Sample code added below


<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="email_order_set_template_vars_before">
        <observer name="email_order_set_template_vars_observer" instance="VendorModuleObserverOrderEmailSetTemplateVars" />

Observer class – app/code/Vendor/Module/Observer/OrderEmailSetTemplateVars.php


namespace VendorModuleObserver;

use MagentoFrameworkEventObserverInterface;
use PsrLogLoggerInterface;
use MagentoFrameworkAppObjectManager;

class OrderEmailSetTemplateVars implements ObserverInterface
     * @var LoggerInterface
    private $logger;

    public function __construct(
        LoggerInterface $logger = null    
    ) {
        $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);

    public function execute(MagentoFrameworkEventObserver $observer)
        $this->logger->debug('Observer '__CLASS__.' called.');
        $transportObject = $observer->getEvent()->getTransportObject();
        $order = $transportObject->getOrder(); // or $transportObject->getData('order');
        // you can use get this var in your order email template
        $transportObject->setData('test_var','Test Value'); // or $transportObject->getTestVar('Test Value');

        // you can also get the sender object and change the template id if you want to, But better set the email template from stores > configuration > sales emails > template as defined in       
        $orderEmailSender = $observer->getEvent()->getSender();    
        $orderEmailSender->templateContainer->setTemplateId($templateId); // assume $templateId holds an existing email template id

        // get order's shipping method and set the email template based on that
        $shippingMethod = $order->getShippingMethod(); // or $order->getShippingDescription()            
       if ($shippingMethod == 'freeshipping') {
          $orderEmailSender->templateContainer->setTemplateId($templateId); // assume $templateId holds an existing email template id