Magento2 | PWA | GraphQL

Magento 2 Send Coupon code to Newsletter Subscriber after successfully Subscribe


Customers are blood of any website. If you are running Ecommerce website in Magento2 then you must have to check your newsletter susbscription process which gives you customer emails. With which you can do many email promotional activities like sending coupon code, discounts, promotional activities of your site and send any news to your customers.

In this post you will learn how to send coupon code to Newsletter Subscriber after successfully Subscribe.

Find Complete Module on github at Magelearn_Newsletter

Create folder in app/code/Magelearn/Newsletter

Add registration.php file in it:
<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magelearn_Newsletter', __DIR__);
Add composer.json file in it:
	
{
    "name": "magelearn/module-newsletter",
    "description": "Generate Random Coupon code with SKU condition for newsletter subscriber users.",
    "type": "magento2-module",
    "license": "OSL-3.0",
    "authors": [
        {
            "email": "info@mage2gen.com",
            "name": "Mage2Gen"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "psr-4": {
            "Magelearn\\Newsletter\\": ""
        },
        "files": [
            "registration.php"
        ]
    }
}
Add etc/module.xml file:
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="Magelearn_Newsletter">
		<sequence>
			<module name="Magento_Newsletter"/>
		</sequence>
	</module>
</config>
Add etc/frontend/di.xml file and override Magento\Newsletter\Model\Subscriber
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
	<preference for="Magento\Newsletter\Model\Subscriber" type="Magelearn\Newsletter\Rewrite\Magento\Newsletter\Model\Subscriber"/>
</config>
Create your override file at app/code/Magelearn/Newsletter/Rewrite/Magento/Newsletter/Model/Subscriber.php and write your logic to generate coupon code and send it to newsletter subscriber in the email by passing coupon code value as template variable.
<?php
declare(strict_types=1);

namespace Magelearn\Newsletter\Rewrite\Magento\Newsletter\Model;

use \Magento\Framework\App\ObjectManager;

class Subscriber extends \Magento\Newsletter\Model\Subscriber
{
	/**
     * @var \Magento\Customer\Model\GroupFactory
     */
    protected $_customerGroup;

    /**
     * @var \Magento\Store\Model\Website
     */
    protected $_website;

    /**
     * @var \Magento\SalesRule\Model\Rule
     */
    protected $_salesRule;
	
	/**
     * Sends out confirmation success email
     *
     * @return $this
     */
    public function sendConfirmationSuccessEmail()
    {
        if ($this->getImportMode()) {
            return $this;
        }

        if (!$this->_scopeConfig->getValue(
            self::XML_PATH_SUCCESS_EMAIL_TEMPLATE,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        ) || !$this->_scopeConfig->getValue(
            self::XML_PATH_SUCCESS_EMAIL_IDENTITY,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        )
        ) {
            return $this;
        }

        $this->inlineTranslation->suspend();

        $this->_transportBuilder->setTemplateIdentifier(
            $this->_scopeConfig->getValue(
                self::XML_PATH_SUCCESS_EMAIL_TEMPLATE,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE
            )
        )->setTemplateOptions(
            [
                'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                'store' => $this->_storeManager->getStore()->getId(),
            ]
        )->setTemplateVars(
            ['subscriber' => $this, 'coupon_code' => $this->generateCouponCode()]
        )->setFrom(
            $this->_scopeConfig->getValue(
                self::XML_PATH_SUCCESS_EMAIL_IDENTITY,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE
            )
        )->addTo(
            $this->getEmail(),
            $this->getName()
        );
        $transport = $this->_transportBuilder->getTransport();
        $transport->sendMessage();

        $this->inlineTranslation->resume();

        return $this;
    }
	/**
     * Retrieve the coupon code
     *
     * @return string
     */
    protected function generateCouponCode()
    {
        try {
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $sku = array('XXXXXXXXXX','XXXXXXXXXX');// skus you want to exclude for this rule.
			$couponData[] = $objectManager->create('Magento\SalesRule\Model\Rule');
            $couponData['name'] = '$10 Gift Voucher Newsletter Subscription ('.$this->getEmail().')';
            $couponData['description'] = '10% Off';
            $couponData['is_active'] = '1';
            $couponData['simple_action'] = 'by_percent';
            $couponData['discount_amount'] = '10';
            $from_date = date('Y-m-d');
            $couponData['from_date'] = $from_date;
            $from_date_time = strtotime($from_date);
            $to_date_time = strtotime("+14 day", $from_date_time);
            $end_time = '23:59:59';
            $to_date = date('Y-m-d', $to_date_time)." ".$end_time;
            $couponData['to_date'] = $to_date;
            $couponData['uses_per_coupon'] = '1';
            $couponData['uses_per_customer'] = '1';
            $couponData['coupon_type'] = '2';
            $couponData['customer_group_ids'] = $this->getCustomerGroupIds();
            $couponData['website_ids'] = $this->getWebsiteIds();
            /** @var \Magento\SalesRule\Model\Rule $rule */
            $rule = $this->_getSalesRule();
            $couponCode = $rule->getCouponCodeGenerator()->setLength(4)->setAlphabet(
                'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
            )->generateCode().'SUBNEW';
            $couponData['coupon_code'] = $couponCode;
            $rule->loadPost($couponData);
			$actions = $objectManager->create('Magento\SalesRule\Model\Rule\Condition\Product\Found')
            						 ->setType('Magento\SalesRule\Model\Rule\Condition\Product')
            						 ->setData('attribute','sku')
                                     ->setData('operator','!()')
                    				 ->setValue($sku);
            $rule->getActions()->addCondition($actions);
            $rule->save();
            return $couponCode;
        } catch (\Exception $e) {
            return null;
        }
    }
	/**
     * Retrieve the customer group ids
     *
     * @return array
     */
    protected function getCustomerGroupIds()
    {
        $groupsIds = [];
        $collection = $this->_getCustomerGroup()->getCollection();
        foreach ($collection as $group) {
                $groupsIds[] = $group->getId();
        }
        return $groupsIds;
    }

    /**
     * Retrieve the website ids
     *
     * @return array
     */
    protected function getWebsiteIds()
    {
        $websiteIds = [];
        $collection = $this->_getWebsite()->getCollection();
        foreach ($collection as $website) {
            $websiteIds[] = $website->getId();
        }
        return $websiteIds;
    }

    /**
     * @return \Magento\Customer\Model\Group
     */
    protected function _getCustomerGroup()
    {
        if ($this->_customerGroup === null) {
            $this->_customerGroup = ObjectManager::getInstance()->get(\Magento\Customer\Model\Group::class);
        }
        return $this->_customerGroup;
    }

    /**
     * @return \Magento\Store\Model\Website
     */
    protected function _getWebsite()
    {
        if ($this->_website === null) {
            $this->_website = ObjectManager::getInstance()->get(\Magento\Store\Model\Website::class);
        }
        return $this->_website;
    }

    /**
     * @return \Magento\SalesRule\Model\Rule
     */
    protected function _getSalesRule()
    {
        if ($this->_salesRule === null) {
            $this->_salesRule = ObjectManager::getInstance()->get(\Magento\SalesRule\Model\Rule::class);
        }
        return $this->_salesRule;
    }
}
Define your custom email template file at app/code/Magelearn/Newsletter/etc/email_templates.xml and add your custom module email template file for newsletter subscription.
<?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="newsletter_subscription_success_email_template" label="Subscription Success" file="subscr_success.html" type="html" module="Magelearn_Newsletter" area="frontend"/>
</config>
Add your custom Email template file after successfully subscribe at app/code/Magelearn/Newsletter/view/frontend/email/subscr_success.html
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<!--@subject {{trans "Newsletter subscription success"}} @-->
<!--@vars {
"template config_path=\"design\/email\/footer_template\"":"Email Footer Template",
"template config_path=\"design\/email\/header_template\"":"Email Header Template"
} @-->


{{template config_path="design/email/header_template"}}

<p>{{trans "You have been successfully subscribed to our newsletter."}}</p>

<p>{{trans "Congratulation! You got $10 gift voucher to purchase items in our store."}}</p>

<p><strong><a href='{{store url = ""}}'>Shop Now</a></strong> {{trans "and get $10% off your next order from our store, with code: <b>%coupon_code</b>" coupon_code=$coupon_code|html}} {{trans "(expires in 2 weeks)."}}</p>

{{template config_path="design/email/footer_template"}}

Now check in admin, new coupon code will be generated with unique code and SKU excluding condition at Marketing >> Promotions >> Cart Price Rules.

0 Comments On "Magento 2 Send Coupon code to Newsletter Subscriber after successfully Subscribe"

Back To Top