1

Currently I have extended Magento_ProductAlert module so that user can subscribe to out of stock product by entering his email address. So far everything works - email gets saved in database and email about back in stock product gets also sent to user.

But now I want to send one more email - lets call it "confirmation email" - the email which is sent to user when he has successfully subscribed to product to get notification when this product will be back in stock. I've already tried some variations which I've found on internet but with no luck.

Can someone maybe help me what I have to extend to send 2 emails instead of 1?

First email - "You have succsessfully subscribed for product X" (this is what I want to add)

Second email - "Hello, We wanted to inform you that product X is back in stock" (this is what I already have)

Thank you!

1 Answer 1

1

Try following way:

Here SR_MagentoCommunity is new module. You can use your own. If you use SR_MagentoCommunity then need to create registration.php and module.xml

app/code/SR/MagentoCommunity/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\ProductAlert\Controller\Add\Stock">
        <plugin name="st_product_stock_subscriber"
                type="SR\MagentoCommunity\Plugin\ProductAlert\Controller\Add\Stock" sortOrder="1"/>
    </type>
</config>

app/code/SR/MagentoCommunity/Plugin/ProductAlert/Controller/Add/Stock.php

<?php
namespace SR\MagentoCommunity\Plugin\ProductAlert\Controller\Add;

use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Psr\Log\LoggerInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Store\Model\App\Emulation as AppEmulation;
use Magento\Framework\App\State as AppState;
use Magento\Framework\App\Area;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Helper\View;
use Magento\ProductAlert\Helper\Data;
use Magento\ProductAlert\Block\Email\Stock as EmailStock;
use Magento\Store\Model\ScopeInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;

class Stock
{
    /**
     * @var ManagerInterface
     */
    private $messageManager;

    /**
     * @var TransportBuilder
     */
    private $transportBuilder;

    /**
     * @var StateInterface
     */
    private $inlineTranslation;

    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

    /**
     * @var AppEmulation
     */
    private $appEmulation;

    /**
     * @var AppState
     */
    private $appState;

    /**
     * @var CustomerSession
     */
    private $customerSession;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var View
     */
    private $customerHelper;

    /**
     * @var Data
     */
    private $productAlertData;

    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;

    /**
     * Stock constructor.
     * 
     * @param ManagerInterface $messageManager
     * @param TransportBuilder $transportBuilder
     * @param StateInterface $inlineTranslation
     * @param ScopeConfigInterface $scopeConfig
     * @param LoggerInterface $logger
     * @param ProductRepositoryInterface $productRepository
     * @param AppEmulation $appEmulation
     * @param AppState $appState
     * @param CustomerSession $customerSession
     * @param StoreManagerInterface $storeManager
     * @param View $customerHelper
     * @param Data $productAlertData
     * @param CustomerRepositoryInterface $customerRepository
     */
    public function __construct(
        ManagerInterface $messageManager,
        TransportBuilder $transportBuilder,
        StateInterface $inlineTranslation,
        ScopeConfigInterface $scopeConfig,
        LoggerInterface $logger,
        ProductRepositoryInterface $productRepository,
        AppEmulation $appEmulation,
        AppState $appState,
        CustomerSession $customerSession,
        StoreManagerInterface $storeManager,
        View $customerHelper,
        Data $productAlertData,
        CustomerRepositoryInterface $customerRepository
    ) {
        $this->messageManager = $messageManager;
        $this->transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->scopeConfig = $scopeConfig;
        $this->logger = $logger;
        $this->productRepository = $productRepository;
        $this->appEmulation = $appEmulation;
        $this->appState = $appState;
        $this->customerSession = $customerSession;
        $this->storeManager = $storeManager;
        $this->customerHelper = $customerHelper;
        $this->productAlertData = $productAlertData;
        $this->customerRepository = $customerRepository;
    }

    public function afterExecute(
        \Magento\ProductAlert\Controller\Add\Stock $subject,
        $resultRedirect
    ) {

        $message = $this->messageManager->getMessages(false);
        $messages = $message->getItems();
        foreach ($messages as $message) {
            if (strpos($message->getText(), 'Alert subscription has been saved') !== false) {
                $productId = (int)$subject->getRequest()->getParam('product_id');
                $this->sendMail($productId);
            }
        }

        return $resultRedirect;
    }

    private function sendMail($productId)
    {
        try {
            /* @var $product \Magento\Catalog\Model\Product */
            $product = $this->productRepository->getById($productId);
            $store = $this->storeManager->getStore();
            $customer = $this->customerRepository->getById($this->customerSession->getCustomer()->getId());
            $customerName = $this->customerHelper->getCustomerName($customer);
            $block = $this->productAlertData->createBlock(EmailStock::class);;
            $block->setStore($store)->reset();

            $product->setCustomerGroupId($this->customerSession->getCustomer()->getGroupId());
            $block->addProduct($product);
            $alertGrid = $this->appState->emulateAreaCode(
                Area::AREA_FRONTEND,
                [$block, 'toHtml']
            );

            $this->inlineTranslation->suspend();
            $transport = $this->transportBuilder->setTemplateIdentifier(
                $this->scopeConfig->getValue(
                    'catalog/productalert/email_stock_subscriber_template',
                    ScopeInterface::SCOPE_STORE,
                    $store->getId()
                )
            )->setTemplateOptions(
                [
                    'area' => Area::AREA_FRONTEND,
                    'store' => $store->getId(),
                ]
            )->setTemplateVars(
                [
                    'customerName' => $customerName,
                    'alertGrid' => $alertGrid,
                ]
            )->setFrom(
                $this->scopeConfig->getValue(
                    'catalog/productalert/email_identity',
                    ScopeInterface::SCOPE_STORE,
                    $store->getId()
                )
            )->addTo(
                $this->customerSession->getCustomer()->getEmail(),
                $customerName
            )->getTransport();

            $transport->sendMessage();

            $this->inlineTranslation->resume();
        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
        }
    }
}

app/code/SR/MagentoCommunity/etc/config.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <catalog>
            <productalert>
                <email_stock_subscriber_template>catalog_productalert_email_stock_subscriber_template</email_stock_subscriber_template>
            </productalert>
        </catalog>
    </default>
</config>

app/code/SR/MagentoCommunity/etc/email_templates.xml

<?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="catalog_productalert_email_stock_subscriber_template" label="Stock Subscriber" file="stock_subscriber.html" type="html" module="SR_MagentoCommunity" area="frontend"/>
</config>

app/code/SR/MagentoCommunity/view/frontend/email/stock_subscriber.html

<!--@subject {{trans "Products subscribe in stock alert"}} @-->
<!--@vars {
"var alertGrid|raw":"Alert Data Grid",
"var customerName":"Customer Name",
"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 class="greeting">{{trans "%name," name=$customerName}}</p>
{{var alertGrid|raw}}

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.