How To

Magento 2: How to Send Email when Product Price Change

Hello Magento Friends,

In today’s blog we will learn about how to send email when there is a change in product prices for your Magento 2 store.

Keeping admins informed about product price changes can improve price management and foster transparency within your team. Here’s a comprehensive guide on how to set up this feature.

Before that, learn How to Change Product Price with Plugin in Magento 2.

Steps to Send Email when Product Price Change in Magento 2:

Step 1: First, we need to create an “events.xml“ file inside our extension at the following path

app\code\Vendor\Extension\etc\adminhtml\events.xml

Then add the below-mentioned code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">     
    <event name="catalog_product_save_before">
        <observer name="custom_shipping_observet" instance="Vendor\Extension\Observer\Saveshippingdata" />
    </event>
</config>

Step 2: After that, we need to create a “Saveshippingdata.php” file inside our extension at the following path

app\code\Vendor\Extension\Observer\Saveshippingdata.php

And add the code as given below

<?php

namespace Vendor\Extension\Observer;

use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;
use Magento\ProductAlert\Model\StockFactory;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\ResourceConnection;
use Magento\Customer\Model\CustomerFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Directory\Model\Currency;

class Saveshippingdata implements ObserverInterface
{
    protected $request;
    protected $stockFactory;
    protected $resourceConnection;
    protected $customFactory;
    protected $_transportBuilder;
    protected $storeManager;
    protected $inlineTranslation;
    protected $currency;
 
    public function __construct(
        \Magento\Framework\App\RequestInterface $request,
         StockFactory $stockFactory = null,
         ResourceConnection $resourceConnection,
         CustomerFactory $customFactory,
         StoreManagerInterface $storeManager,
         TransportBuilder $_transportBuilder,
         StateInterface $inlineTranslation,
         Currency $currency
    )
    {
        $this->stockFactory = $stockFactory ?? ObjectManager::getInstance()->get(StockFactory::class);
        $this->resourceConnection = $resourceConnection;
        $this->request = $request;
        $this->customFactory=$customFactory;
     $this->storeManager=$storeManager;
     $this->_transportBuilder=$_transportBuilder;
     $this->inlineTranslation=$inlineTranslation;
     $this->currency=$currency;
    }
    
    public function execute(Observer $observer)
    {
     $product = $observer->getEvent()->getDataObject();
     $post = $this->request->getPost();
        $post = $post['product'];
     $originalPrice = $product->getOrigData('price');
        $currentPrice = $product->getData('price');
        if($originalPrice != '' && $originalPrice != NULL)
        {
         $formatted_original_price = number_format($originalPrice, 2);
         if($formatted_original_price != $currentPrice)
             {
               if (array_key_exists("thumbnail",$post))
                        {
                                $product_image = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'catalog/product'.$post['thumbnail'];
                        }
              $templateOptions = array('area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $this->storeManager->getStore()->getId());
              $templateVars = array(
                                                'store' => $this->storeManager->getStore(),
                                                'message'    => 'Price change alert! We wanted you to know that prices have changed for these products:',
                                                'productname'=>$post['name'],
                                                'productimage'=>$product_image,
                                                'producturl'=>$this->storeManager->getStore()->getBaseUrl().$post['url_key'].".html",
                                                'productprice'=>$this->currency->format($post['price'], ['symbol' => $currencySymbol, 'precision'=> $precision], false, false)
                                            );
                            $from = array('email' => "sender@example.com", 'name' => 'Sender Name');
                            $this->inlineTranslation->suspend();
                            $to = receiver@gmail.com;
                            $transport = $this->_transportBuilder->setTemplateIdentifier('price_change_email')
                                            ->setTemplateOptions($templateOptions)
                                            ->setTemplateVars($templateVars)
                                            ->setFrom($from)
                                            ->addTo($to)
                                            ->getTransport();
                            $transport->sendMessage();
                            $this->inlineTranslation->resume();
             }
        }
    }
}

Step 3: After that, we need to create an “email_templates.xml” file inside our extension at the following path

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

And add the code as follows

<?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="price_change_email" label="Stock ALert" file="price_change.html" type="html" module="Vender_Extension" area="frontend"/>
</config>

Step 4: After that, we need to create a “price_change.html” file inside our extension at the following path

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

Now add the below-mentioned code

<!--@subject Products price changed alert @-->
<!--@vars
{"store url=\"\"":"Store Url",
"skin url=\"email/logo/stores/1/Company_Logos_9_.png\" _area='frontend'":"Email Logo Image"}
@-->
<!--@styles
body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif; }
@-->
{{template config_path="design/email/header_template"}}
        <table cellspacing="0" cellpadding="0" border="0" 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">
                                <h1 style="font-size:22px;font-weight:normal;line-height:22px;margin:0 0 11px 0;">{{trans "Hello"}}</h1>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <table cellspacing="0" cellpadding="0" border="0" width="650">
                                    <tbody>
                                        <tr>
                                            <td colspan="2" valign="top" style="font-size:12px;padding:7px 9px 9px 9px;border:1px solid #EAEAEA;">
                                                {{var message}}
                                            </td>
                                        </tr>
                                        <tr>
                                        <td valign="top" style="font-size:12px;padding:7px 9px 9px 9px;border:1px solid #EAEAEA;">
                                         <a href="{{var producturl}}">
                                                <img src="{{var productimage}}" width="200px"
                                                height="200px" alt="{{var productname}}">
                                           <div class="product-name">{{trans "Product Name: "}}<b>{{var productname}}</b></div></a>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2" valign="top" style="font-size:12px;padding:7px 9px 9px 9px;border:1px solid #EAEAEA;">
                                               {{trans "Price: "}}{{var productprice}}
                                            </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </td>
                           
                        </tr>
                        <tr>
                            <td bgcolor="#EAEAEA" align="center" style="background:#EAEAEA;text-align:center;">
                                <center>
                                    <p style="font-size:12px;margin:0;">
                                        <strong>{{trans "Thank you"}}</strong>
                                    </p>
                                </center>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    {{template config_path="design/email/footer_template"}}

Conclusion:

With these steps, you have set up a system in Magento 2 that sends email notifications to admins when a product price changes. This proactive approach helps maintain competitive pricing strategies and ensures that the admin is always informed of any significant changes.

If you have any questions or run into issues, feel free to leave a comment below or contact us for further assistance.

Happy Coding!

Click to rate this post!
[Total: 0 Average: 0]
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

Handling Forms and Data in Shopify Remix: useSubmit vs. useFetcher

In Shopify Remix, managing form submissions and data fetching is crucial for building interactive and…

12 hours ago

SEO and Digital Marketing for Magento Stores

When positioning oneself in the constantly developing field of internet sales, it is critical to…

16 hours ago

Emerging Shopify Trends That Student Entrepreneurs Should Know About

One major challenge student entrepreneurs encounter is difficulty balancing academics and business. Most find themselves…

16 hours ago

How to Setup Vite in Shopify Remix App?

In this article, we will learn how to set up Vite in the Shopify remix…

2 days ago

Magento 2: How to Add View Button in Admin Grid to Open a View Page in Slide Window

Hello Magento Friends, In Magento 2, customizations to the admin panel can significantly enhance the…

3 days ago

Magento 2: How to Observe the Multi-shipping Order Creation Event

Hello Magento Friends, Magento 2 provides a robust event-driven architecture that allows developers to observe…

6 days ago