Magento 2 – How to Create Newsletter Subscriber Programmatically

magento2newsletter

How to create newsletter subscriber programmatically ? I have email id I want to save that email id in newsletter subscriber how can I do that ?

<?php

/**
 * Copyright 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace vendorname\moduelname\Model;

use Sapient\CustomApi\Api\CustomInterface;

/**
 * Defines the implementaiton class of the calculator service contract.
 */
class Custom implements CustomInterface
{

    protected $subscriberFactory;


    public function __construct(

    \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
) {
    $this->subscriberFactory= $subscriberFactory;

}
    /**
     * Return the sum of the two numbers.
     *
     * @api
     * @param int $num1 Left hand operand.
     * @param int $num2 Right hand operand.
     * @return int The sum of the two values.
     */
    public function add($num1, $num2) {
        return $num1 + $num2;
    }

    /**
     * Sum an array of numbers.
     *
     * @api
     * @param string[] $email The array of numbers to sum.
     * @return string The sum of the numbers.
     */
    public function newsletter($email) {

           //$data ="sssssssss"; 
          // print_r($data);
           //die;
        $this->subscriberFactory->create()->subscribe($email);
        return $email;
    }
}

Best Answer

To do that you can inject Magento\Newsletter\Model\SubscriberFactory in your constructor:

protected $subscriberFactory;

public function __construct(
    //
    \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
) {
    $this->subscriberFactory= $subscriberFactory;
    //
}

Then in your code you can call:

$this->subscriberFactory->create()->subscribe($email);