2

I need to collect SubScriber email in Magento 2. So, I tried to inject \Magento\Newsletter\Model\Subscriber $subscriber , I didn't work for me.

  <?php
    namespace Vendor\Module\Cron;

    class NewsLetter
    {
        protected $_logger;
        protected $_subscriber;
        protected $_customerdata;
        public function __construct(
        \Psr\Log\LoggerInterface $logger,
           \Magento\Newsletter\Model\Subscriber $subscriber,
           \Magento\Customer\CustomerData\Customer $customerdata,
           )
        {
        $this->_logger = $logger;
         $this->_subscriber= $subscriber;
        $this->_customerdata= $customerdata;
        }
        public function execute()
        {
           $customer= $this->_customerdata->getSectionData();
          $data=$this->getCustomerEmail($customer)
          foreach($data as $email)
         {
         $customerEmail =$email;

         $checkSubscriber = $this->_subscriber->loadByEmail($customerEmail);
        if ($checkSubscriber->isSubscribed()) {
            // Customer is subscribed
         $this->_logger->addDebug($customerEmail."subscribed Email");
        } else {
           $this->_logger->addDebug($customerEmail."Unsubscribed Email");
        }
         }

        }
    }

Suggest me what I missed.

  • for($data as $email) or foreach(......) check – Bilal Usean Sep 13 '16 at 13:49
  • @BilalUsean update question – Rajkumar .E Sep 13 '16 at 13:51
  • How about your current issue? – Khoa TruongDinh Sep 15 '16 at 13:36
2

In your case, we can use \Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory.

<?php

namespace Vendor\Module\Cron;

class NewsLetter
{


 /**
 * @var \Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory
 */
protected $_subcriberCollectionFactory;

    public function __construct(
         ......
        \Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory $subcriberCollectionFactory,
         ......
    )
    {
        ......
        $this->_subcriberCollectionFactory = $subcriberCollectionFactory;
    }
}

Load only subscribed customers:

$this->_subcriberCollectionFactory->create()->useOnlyCustomers();

Adds customer info to select:

$this->_subcriberCollectionFactory->create()->showCustomerInfo();

See more: vendor/magento/module-newsletter/Model/ResourceModel/Subscriber/Collection.php

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.