How To

How to Set Dynamic Email Subject in Magento 2

Hello Magento Friends,

In this Magento 2 tutorial, I am going to show How to Set Dynamic Email Subject in Magento 2.

eCommerce stores use email marketing campaigns for various purposes. Store owners inform customers about the latest offers, discounts, and new releases via email. Customers communicate with the store for any query or help. 47% of emails are opened based on the subject line. Email subject lines matter a lot for its open rate. Using personalized email subjects helps to get high open rates.

Magento 2 store merchants can make the email subject lines dynamic for a better success rate. Let’s learn How to Set Dynamic Email Subject in Magento 2.

Steps to Set Dynamic Email Subject in Magento 2:

Step 1: Create an email template configuration file at the below path

app\code\Vendor\Extension\etc\email_templates.xml 

Then add the below code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Email:etc/email_templates.xsd">
    <template id="your_email_template_id" label="Label of your template file" file="email_file.html" type="html" module="Vendor_Extension" area="frontend"/>
</config>

Step 2: Now create an email template file at the following path

app\code\Vendor\Extension\view\frontend\email\email_file.html

Now add the below code snippet

<!--@subject {{var subject|raw }}@-->
<!--@vars
{"var customerName":"Customer Name",
"var customerEmail":"Customer Email",
"var customerComment":"Comment"}
@-->
<body style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
<div style="background:#F6F6F6; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0; padding:0;">
<table cellspacing="0" cellpadding="0" border="0" height="100%" width="100%">
    <tr>
        <td align="center" valign="top" style="padding:20px 0 20px 0">
            <table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                <tr>
                    <td valign="top" colspan="5">
                        <h1 style="font-size:22px; font-weight:normal; line-height:22px; margin:0 0 11px 0;">Hello Admin,</h1>
                    </td>
                </tr>
                <tr>
                    <td valign="top" colspan="5">
                        <p style="border:1px solid #E0E0E0; font-size:12px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;">You Have Received New Query As Bellow.<p>
                    </td>
                </tr>
                <tr>
                    <td valign="top" colspan="5">
                        <p style="border:1px solid #E0E0E0; font-size:12px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;">Customer Name : <strong>{{var customerName}}</strong></td>
                </tr>
                <tr>
                    <td valign="top" colspan="5">
                        <p style="border:1px solid #E0E0E0; font-size:12px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;">Customer Email : <strong>{{var customerEmail}}</strong></td>
                </tr>
                <tr>
                    <td valign="top" colspan="5">
                        <p style="border:1px solid #E0E0E0; font-size:12px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9;">Customer Comment : <strong>{{var customerComment}}</strong></td>
                </tr>
                <tr>
                    <td valign="top" colspan="5">
                        <p style="border:1px solid #E0E0E0; font-size:12px; line-height:16px; margin:0; padding:13px 18px; background:#F9F9F9; text-align:center;"><strong>Thank you.</strong></td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</div>
</body>

Step 3: Now the template is ready and we will do the code for sending mail.

Go to your controller file

app\code\Vendor\Extension\Controller\Index\Index.php

Add the below-mentioned code

<?php
namespace Vendor\Extension\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $transportBuilder;
    protected $storeManager;
    protected $inlineTranslation;
    protected $state;

    public function __construct(
        Context $context,
        StoreManagerInterface $storeManager,
        TransportBuilder $transportBuilder,
        StateInterface $state)
    {
        $this->transportBuilder = $transportBuilder;
        $this->storeManager = $storeManager;
        $this->inlineTranslation = $state;
        parent::__construct($context);
    }
    public function execute()
    {        
        $templateId = 'your_email_template_id'; // template id
        $fromEmail = 'admin@gmail.com';  // sender Email id
        $toEmail = 'test.magecomp@gmail.com'; // receiver email id
        $subject = 'your_dynamic_subject'; // Dynamic subject
        try
        {
            // template variables pass here
            $templateVars = [
                'subject' => $subject,
                'customerName' => 'Test',
                'customerEmail' => 'Magecomp',
                'customerComment' => 'Test Comment'
            ];
 
            $storeId = $this->storeManager->getStore()->getId();
            $this->inlineTranslation->suspend();
 
            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $templateOptions = [
                'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                'store' => $storeId
            ];
            
            $transport = $this->transportBuilder->setTemplateIdentifier($templateId, $storeScope)
                ->setTemplateOptions($templateOptions)
                ->setTemplateVars($templateVars)
                ->setFrom($fromEmail)
                ->addTo($toEmail)
                ->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('*/*/');
        }
    }
}

Conclusion:

This way you can Set Dynamic Email Subject in Magento 2 and improve the open rate of your email marketing campaigns. If you are unable to perform the steps correctly, you can freely reach out to me with your problem through the comments.

Share the article with those who are in search of making their email marketing campaigns a total success.

Happy Coding!

Click to rate this post!
[Total: 1 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Add a Custom Field to the Cart Price Rules Form in Magento 2?

Hello Magento Friends, In this blog, we will learn How to Add a Custom Field…

10 hours ago

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

3 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

5 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

5 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

1 week ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago