we need to send mail to customer for each & every product in One order without spliting the order id in magento 2.4
1 Answer
Please check below code and try.
- Create a class to handle sending the email:
Here is the code:-
<?php
namespace YourVendor\Module\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Sales\Model\Order;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
class Email extends AbstractHelper
{
protected $_storeManager;
protected $_transportBuilder;
protected $_inlineTranslation;
public function __construct(
Context $context,
StoreManagerInterface $storeManager,
TransportBuilder $transportBuilder,
StateInterface $inlineTranslation
) {
$this->_storeManager = $storeManager;
$this->_transportBuilder = $transportBuilder;
$this->_inlineTranslation = $inlineTranslation;
parent::__construct($context);
}
public function sendProductEmail($order)
{
// Get the order items
$orderItems = $order->getItems();
// Loop through the order items
foreach ($orderItems as $item) {
// Get the product name
$productName = $item->getName();
// Get the product email template
$templateId = 'product_email_template_id';
// Get the sender information
$sender = [
'name' => 'Sender Name',
'email' => '[email protected]',
];
// Get the recipient information
$recipient = [
'email' => $order->getCustomerEmail(),
'name' => $order->getCustomerName(),
];
// Set the template variables
$templateVars = [
'product_name' => $productName,
];
// Enable HTML emails
$this->_inlineTranslation->suspend();
// Send the email
$this->_transportBuilder->setTemplateIdentifier($templateId)
->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $this->_storeManager->getStore()->getId()])
->setTemplateVars($templateVars)
->setFrom($sender)
->addTo($recipient['email'], $recipient['name'])
->getTransport()
->sendMessage();
// Re-enable HTML emails
$this->_inlineTranslation->resume();
}
}
}
sendProductEmail
function call as your requirement plugin or observer where you want to send email.
Let me know if any query.
THANKS.