In this article I will show how to import a list of subscribers into Magento 2 from a CSV file via the built-in console command tool. For your reference I’ve run it on Magento 2.1.2,  PHP 7.

First of all, you will need a custom module (there are hundreds of articles on line showing how to build one). Now, you need to add the following code to your app/code/MYNAMESPACE/MYMODULE/etc/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\Framework\Console\CommandList">
        <arguments>
            <argument name="commands" xsi:type="array">
                <item name="SubscriberImportCommand" xsi:type="object">MYNAMESPACE\MYMODULE\Console\Command\SubscriberImportCommand</item>
            </argument>
        </arguments>
    </type>
</config>

Now, create the file MYNAMESPACE\MYMODULE\Console\Command\SubscriberImportCommand.php and add the code below:

<?php

namespace MYNAMESPACE\MYMODULE\Console\Command;

USE Magento\Framework\App\State;
use Magento\Store\Model\StoreManager;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\ObjectManagerFactory;
use Symfony\Component\Console\Input\InputOption;
use Magento\Newsletter\Model\SubscriberFactory;
use Magento\Newsletter\Model\Subscriber;

/**
 * Class SubscriberImportCommand
 * @package MYNAMESPACE\MYMODULE\Console\Command
 */
class SubscriberImportCommand extends \Symfony\Component\Console\Command\Command
{
    /**
     * @var \Magento\Framework\ObjectManagerInterface
     */
    protected $_objectManager;

    /**
     * @var \Magento\Framework\App\Filesystem\DirectoryList
     */
    protected $_directoryList;

    /**
     * @var Magento\Newsletter\Model\SubscriberFactory
     */
    protected $_subscriberFactory;

    /**
     *
     */
    const CSV_EMAIL_POSITION = 0;

    /**
     * SubscriberImportCommand constructor.
     *
     * @param ObjectManagerFactory $objectManagerFactory
     * @param State $state
     * @param DirectoryList $_directoryList
     * @param SubscriberFactory $_subscriberFactory
     */
    public function __construct(
        ObjectManagerFactory $objectManagerFactory,
        State $state,
        DirectoryList $_directoryList,
        SubscriberFactory $_subscriberFactory
    ){
        $params = $_SERVER;

        $params[StoreManager::PARAM_RUN_CODE] = 'admin';
        $params[StoreManager::PARAM_RUN_TYPE] = 'store';
        $this->_objectManager = $objectManagerFactory->create($params);
        $state->setAreaCode('admin');
        
        
        $this->_directoryList = $_directoryList;
        $this->_subscriberFactory = $_subscriberFactory;
        parent::__construct();
    }

    /**
     *
     */
    protected function configure()
    {
        $this->setName('newsletter:subscriber:import')
            ->setDescription('Imports newsletter subscribers');

        $this->setDefinition([new InputOption(
            'csv-path',
            null,
            InputOption::VALUE_REQUIRED,
            'Path to csv file within Magento.',
            null
        )]);

        parent::configure();
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return bool
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('<info>Starting Category Cleanup</info>');

        $magentoRoot = $this->_directoryList->getPath(DirectoryList::ROOT);
        $csvPath = $magentoRoot . '/' . $input->getOption('csv-path');

        if(!file_exists($csvPath)) {
            $output->writeln("<error>CVS file not found in {$csvPath}</error>");
            return false;
        }

        $csv = array_map('str_getcsv', file($csvPath));
        $count = count($csv);

        foreach($csv as $key => $row) {
            $email = $row[self::CSV_EMAIL_POSITION];

            if(!$this->isValidEmail($email)) {
                continue 1;
            }

            $this->_subscriberFactory->create()
                ->setStatus(Subscriber::STATUS_SUBSCRIBED)
                ->setEmail($email)
                ->save();

            $output->writeln("<info>{$key} of {$count} - {$email} has been added.</info>");
        }
        return true;
    }

    /**
     * Remove all illegal characters from email and validates it.
     *
     * @param string $email
     * @return bool
     */
    protected function isValidEmail(string $email)
    {
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);

        if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
            return false;
        }

        return true;
    }
}

The code above is straightforward. You could use the method ->subscribe() instead adding setEmail(), setStatus() and save(). However, if for any reason you need to handle the status, this approach is better.

Now, to import the subscribers, place the CSV file some where in your Magento project and run the command below:

php bin/magento newsletter:subscriber:import --csv-path='pub/media/import/subscribers_sample.csv'

That’s it. All the subscribers should be imported by now.

Happy coding!

Magento 2 Import Newsletter Subscriber Programmaticallyhttps://i0.wp.com/blog.mdnsolutions.com/wp-content/uploads/2017/02/Screen-Shot-2017-02-14-at-11.02.19-AM.png?fit=497%2C249&ssl=1https://i0.wp.com/blog.mdnsolutions.com/wp-content/uploads/2017/02/Screen-Shot-2017-02-14-at-11.02.19-AM.png?resize=150%2C150&ssl=1Renato MedinaMagentoMagento 2Import,Magento 2,Newsletter,Programmatically,SubscriberIn this article I will show how to import a list of subscribers into Magento 2 from a CSV file via the built-in console command tool. For your reference I've run it on Magento 2.1.2,  PHP 7. First of all, you will need a custom module (there are hundreds of...A Magento Craftsman in Melbourne