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:
1
2
3
4
<?php
use Magento\Framework\Component\ComponentRegistrar;
 
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magelearn_Newsletter', __DIR__);
Add composer.json file in it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
     
{
    "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:
1
2
3
4
5
6
7
8
<?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
1
2
3
4
<?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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
<?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.
1
2
3
4
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!--
/**
 * 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.

Related Post:

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

Back To Top