Development and Configuration of Order Email Coupons in Magento 2

Development and Configuration of Order Email Coupons in Magento 2



E-commerce businesses always needs dynamic rules of marketing to attract and lure their customers. The more the customers visits the sites, the more opportunity for the merchants to sell their products and ultimately, in returns a handsome revenue.

Magento-2 a leading E-commerce platform provides a full flexible and customizable architecture to implement any sort of automation that ultimately leads in generating customer traffic and business.

The automated coupons in order email is one of the marketing tactics of many e commerce businesses and in this blog we will cover the implementation of “order email coupons” within Magento-2 system.

The module “order email coupons” will email new coupon in every order email, to lure customer to re-visit site and shop more.

We will try to cover each and every necessary step of module development and configurations.

For reference, we have attached screen-shots for letting it know, how module need to be configured.


Order Email Coupons - Magento 2 Blog folio3

Order Email Coupons - Magento 2 Blog folio3

Order Email Coupons - Magento 2 Blog folio3

Order Email Coupons - Magento 2 Blog folio3

Order Email Coupons - Magento 2 Blog folio3

Order Email Coupons - Magento 2 Blog folio3




Create new module, at following path:



Create required module files and folder:





<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Folio3_OrderEmailCoupon" setup_version="1.0.1">



We will provide new order email templates for logged-in and guest customers. Add templates code in file:


    <template id="sales_email_order_with_coupon" label="New Order With Coupon" file="ordRRQMCM02er_new_with_coupon.html" type="html" module="Folio3_OrderEmailCoupon" area="frontend"/>
    <template id="sales_email_order_guest_with_coupon" label="New Order Guest With Coupon" file="order_new_guest_with_coupon.html" type="html" module="Folio3_OrderEmailCoupon" area="frontend"/>



In order to show the added emailed templates under admin→stores→configuration…

We need to code the following module file:


        <tab id="folio3" translate="label" sortOrder="200">
        <section id="coupon" translate="label" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Gift Coupon</label>
            <group id="general" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0">
                <label>Coupon Configuration</label>                
                <field id="id" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Generate Rule ID</label>
                    <comment>The cart price rule ID must be valid and active.</comment>



Create email templates (html) files:

For Guest Customer(s):


For Logged-in Customer(s):


Please insert, the required gift coupon code in each email templates

     {{if gift-coupon}}
                <table class="message-info">
                            <h3 style="text-align:center;">{{trans "Gift Coupon"}}</h3>
                            <p style="text-align:center;">{{var gift-coupon}}</p>



Create need shopping cart rule under admin→marketing→promotions→cart price rules, with following necessary configurations, also highlighted in screen-shots:

Active: Yes

Coupon: Specific Coupon

(Checked) Use Auto Generation

User per Customer: 1


This rule will be utilized for creating dynamic coupon. The logic will be covered shortly.

Once rule is configured, please save it, copy the rule ID from URL and paste under text field at admin→stores→configuration→folio3→gift coupon→generate rule ID…


Step-7 (final step):

We have almost completed the required module files & folders with configurations.

In this step, we will add event “email_order_set_template_vars_before” at following path, that will be responsible for inserting coupon information at the time of sending order email.


<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="email_order_set_template_vars_before">
        <observer name="folio3_send_coupon_in_email" instance="Folio3\OrderEmailCoupon\Observer\OrderEmailCoupon" />


Create observer file:

The observer will check for “Rule ID” and if found, generates dynamic coupon and bind it in order emails.


namespace Folio3\OrderEmailCoupon\Observer;

use Magento\Framework\Event\ObserverInterface;

class OrderEmailCoupon implements ObserverInterface

    protected $logger;
    protected $ruleFactory;
    protected $massgenerator;
    protected $scopeConfig;

    public function __construct(
        \Psr\Log\LoggerInterface $logger,
        \Magento\SalesRule\Model\RuleFactory $ruleFactory,
        \Magento\SalesRule\Model\Coupon\Massgenerator $massgenerator,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        $this->logger = $logger;
        $this->ruleFactory = $ruleFactory;
        $this->massgenerator = $massgenerator;
        $this->scopeConfig = $scopeConfig;

     * @param \Magento\Framework\Event\Observer $observer
     * @return void
    public function execute(\Magento\Framework\Event\Observer $observer)
        $transport = $observer->getTransport();
        $couponApplied = $transport->getOrder()->getCouponCode();    
        $generatedCoupon = $this->generateOrderEmailCoupon();

        if($generatedCoupon) {
            $transport['gift-coupon'] = $generatedCoupon;

    public function generateOrderEmailCoupon() {

        $ruleModel = $this->ruleFactory->create();
        $ruleId = $this->scopeConfig->getValue('coupon/general/id' ,\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        //if ruleId defined under, stores->configuration->Folio3->Gift Coupon->Generate Rule ID
        if($ruleId) { 

            try {
                if(!$ruleModel->load($ruleId)->getIsActive()) {
                    return false;

                $generateData = array(
                                'rule_id' => $ruleId,
                                'qty' => 1,
                                'length' => '12',
                                'format' => 'alphanum',
                                'prefix' => '',
                                'suffix' => '',
                                'dash'=> 0

                /** @var $generator \Magento\SalesRule\Model\Coupon\Massgenerator */
                $generator = $this->massgenerator;
                if (!$generator->validateData($generateData)) {
                    throw new \Magento\Framework\Exception\LocalizedException(
                        __('Coupon generation validation fails.')
                else {
                    $generated = $generator->getGeneratedCount();
                    $codes = $generator->getGeneratedCodes();
                    if(isset($codes[0])) {
                        return $codes[0];    
            catch (\Magento\Framework\Exception\LocalizedException $e) {
            catch (\Exception $e) {

        return false;

Please feel free to comment or reach out if you have any questions. If you need any help with customizing your Magento 2 web store, please get in touch with us.


USA408 365 4638


1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Contact us

Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.

Tel: +1 408 365 4638
Support: +1 (408) 512 1812