Magento store owners widely use Emails to communicate with users. Emails serve many purposes such as marketing, confirmation about store activities of customers, query solution. Also, customers can contact admin via Email for questions regarding products or services.
As we know that Emails have a noticeable impact in Magento stores, it’s template designing must be given attention. The subject of the Email is the first thing that recipient notices. It should be proper and relative to the email content.
For example, a customer has questions for a particular product and requests for a solution to the admin via the contact form on the product page. On click of the “submit” button, an Email gets sent to the admin with the query related to the product. In this scenario, If if the Email subject is set to the “Query For” + “name of the product”, admin finds it easy to approach the problem. Now, each product has the different name and to set such a dynamic subject, you need to custom code.
Hence a relative email subject is impactful. But it is not feasible to manually change the subject every time for each product or service. So here’s the solution to set dynamic email subject in Magento 2 via the template. We use the system variable to dynamically change the subject of the email and the below code shows its implementation.
Code to Set Dynamic Email Subject in Magento 2 via Template:
Vendor\Extensionname\view\frontend\email\youremailfile.html
@subject {{vardynamic_subject|raw }}@
in youremailfile html file.
Vendor\Extensionname\Controller\Index\Index.php
<?php public function execute() { try { $from = "[email protected]"; $this->inlineTranslation->suspend(); $to = "[email protected]"; $subject = "Dynamic Subject"; $templateOptions = ['area'=>\Magento\Framework\App\Area::AREA_FRONTEND,'store'=>\Magento\Store\Model\Store::DEFAULT_STORE_ID]; $templateVars = [dynamic_subject=>$subject]; $transport = $this->transportBuilder->setTemplateIdentifier('youremailfile')->setTemplateOptions($templateOptions)->setTemplateVars($templateVars)->setFrom($from)->addTo($to)->getTransport(); $transport->sendMessage(); $this->inlineTranslation->resume(); $this->messageManager->addSuccessMessage(__('Your Email Sent successfully')); $this->_redirect(' */*/'); }catch (\Exception $e) { $this->inlineTranslation->resume(); $this->messageManager->addErrorMessage(__('We can\'t process your request' . $e->getMessage())); $this->_redirect('*/*/'); } }
Creating a dynamic subject line to help admin recognize the query or match the end users’ interests can boost Email open rates and interactions. Easily set the dynamic Email subjects accordingly with the above method!