0

I am trying to create a custom module which send an alert mail to each customer who subscribed to the product. The idea is to send a custom email when the product's date is updated with a cron that check the date once a day.

I have created custom email template that works correctly.

Here is my crontab:

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
<group id="default">
    <job instance="Namespace\To\Cron" method="execute" name="axelites_alertmail">
        <schedule>*/5 * * * *</schedule>
    </job>
</group>
</config>

The controller that send the mail:

<?php
class Alert extends \Magento\Framework\App\Action\Action{
    protected $_products = null;
    protected $_emails = null;
    protected $_sender_email = "";
    protected $_sender_name = ""

    /**
     * @var \Magento\Framework\App\Request\Http
     */
    protected $_request;
    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    protected $inlineTranslation;

    protected $_objectManager;

    protected $_customerFactory;

    protected $_productloader;

    protected $_logger;

    protected $_store;

    protected $_customer;

    protected $connection;

    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        ScopeConfigInterface $scopeConfig,
        \Magento\Framework\App\Request\Http $request,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Catalog\Model\ProductFactory $productloader,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Store\Api\Data\StoreInterface $store
) {
        parent::__construct($context);

        $this->_request = $request;
        $this->_transportBuilder = $transportBuilder;
        $this->_storeManager = $storeManager;
        $this->inlineTranslation = $inlineTranslation;
        $this->resultPageFactory = $resultPageFactory;
        $this->scopeConfig = $scopeConfig;
        $this->_productloader = $productloader;
        $this->_logger = $logger;
        $this->_store = $store;

        $this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        $resource = $this->_objectManager->get('Magento\Framework\App\ResourceConnection');
        $this->connection = $resource->getConnection();
        $this->coreRegistry = $this->_objectManager->get('Magento\Framework\Registry');
        $this->storeManager = $this->_objectManager->get('\Magento\Store\Model\StoreManagerInterface');
        $this->_customer =  $this->_objectManager->get('Magento\Customer\Model\Customer');
        $this->_customerFactory = $this->_objectManager->create('\Magento\Customer\Model\CustomerFactory');

    }


    public function execute()
    {

        $sql = $this->connection->select()->from(['ma' => 'alertmail'], ['id', 'email', 'product_id', 'sent'])->where('ma.sent = 0');
        $emails = $this->connection->fetchAll($sql);

        $template_vars = [];

        foreach($emails as $item) {

            foreach($item as $index => $value){

                if($index == "product_id"){
                    $product = $this->getLoadProduct($value);

                    //@TODO set email template variables with following data

                    $template_vars["product_name"] = $product->getUrl();
                    $template_vars["product_url"] = $product->getName();
                }

                if($index == "email"){
                    $tmp_email = $value;
                }

                if($index == "id"){
                    $tmp_id = $value;
                }


                //@TODO get customer locale code by email
                $transport = $this->_transportBuilder->setTemplateIdentifier($this->getTemplate(''))
                    ->setTemplateOptions([
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID
                    ])
                    ->setTemplateVars($template_vars)
                    ->setFrom('general')
                    // you can config general email address in Store -> Configuration -> General -> Store Email Addresses
                    ->addTo($tmp_email)
                    ->getTransport();
                $transport->send();

                $update = "UPDATE alertmail SET sent = '1' where id = " . $tmp_id;
                $this->connection->query($update);

            }

        }

        return $this;
    }

    private function getLoadProduct($product_id)
    {
        return $this->_productloader->create()->load($product_id);
    }

    private function getTemplate($store)
    {

        switch ($store) {
            case 'en_US':
                return 'alertmail EN';
                break;
            case 'fr_FR':
                return 'alertmail FR';
                break;
            case 'it_IT':
                return 'alertmail IT';
                break;
            case 'es_ES':
                return 'alertmail ES';
                break;
            case 'nl_NL':
                return 'alertmail NL';
                break;
            case 'de_DE':
                return 'alertmail DE';
                break;
            default: return 'alertmail EN';
                break;

        }

    }

    private function getCustomerLocale($id)
    {

        $sql = $this->connection->select()->from(['cae' => 'mo_customer_address_entity'], ['country_id'])->where("cae.parent_id = $id");
        $country_id = $this->connection->fetchAll($sql);

        return  $country_id['country_id'];
    }

    private function getCustomerId($email)
    {

        $this->_customer->setWebsiteId(null);
        $this->_customer->loadByEmail($email);// load customet by email address

        return $this->_customer->getId();

    }   
}

I am a big newbie with magento 2 and I am trying hard to follow the docs but I always get walls in the face because its never work as said in the docs.

Can you give me any ideas to how I can solve this problem?

I know my code have a lot of unfinished statements but thanks for your advices.

0

Check my extension. It's very close to what you are trying to achieve.

https://github.com/DominicWatts/BackInStock

Hopefully should fill in the blanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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