Magento 2

Magento 2 import email address to Newsletter from csv

Magento 2 import email address to Newsletter from csv.

I have a requirement to import email is from CSV and import the email ids to Newsletter Subscriber list from csv.

Write a PHP script which will import Newsletter subscriber from CSV.

In this script, first i have read the email ids  from Csv , Then  first  check an email is exits  as customer

Using Magento\Customer\Api\AccountManagementInterface ‘s   function isEmailAvailable($emailId,$websiteId) and depends  on customer types Guest ( mean guest Not register) and register, i have added  the email  to  subscriber list.

For add an email to the subscriber list, we need to call factory class Magento\Newsletter\Model\SubscriberFactory  and need to Customer.Guest customer  use

$_subscriberFactory->create()->subscribe($Email);

 

and register customer ,use

$_subscriberFactory->create()->subscribeCustomerById($CustomerId);

Step1: First create importnewsletter.php at magento2 dir for import email to Newsletter subscriber list from CSV.

add below code  for

 

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

ini_set("soap.wsdl_cache_enabled", "0");
ini_set('default_socket_timeout', 600);

//require 'C:\xampp\htdocs\sample216\app\bootstrap.php';
require __DIR__ . '/app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

$obj = $bootstrap->getObjectManager();

$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');



$websiteId =  $obj->get('Magento\Store\Model\StoreManagerInterface')
    ->getStore()
    ->getWebsiteId();

$customerAccountManagement =$obj
    ->create('Magento\Customer\Api\AccountManagementInterface');

$_subscriberFactory = $obj->create('Magento\Newsletter\Model\SubscriberFactory');

if (($handle = fopen("subscribers.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
       /* customer */
        if($customerAccountManagement->isEmailAvailable($data[0], $websiteId)){
            echo $data[0]."Guest <br/>";
            $_subscriberFactory = $_subscriberFactory->create()->subscribe($data[0]);
        }else{
            echo $data[0]."Register <br/>";
            $customerFactory = $obj->get('Magento\Customer\Model\CustomerFactory');
            $customer=$customerFactory->create();
            $customer->setWebsiteId($websiteId);
            $customer->loadByEmail($data[0]);// load customer by email address
            if($customer->getId()){
                $_subscriberFactory->create()->subscribeCustomerById($customer->getId());
            }

        }
    }
    fclose($handle);
}

Step2: Create Csv file for import address.

CSV  like subscribers

Using this script,  you can Programmatically import email address to Newsletter from csv.