6

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;
    }
}
9

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);
  • i updated my question with code i want to subscribe under newsletter function but i am getting error – magento12345 Dec 14 '16 at 11:25
  • How to subscribe first name ans last name? – jafar pinjar Sep 7 '18 at 14:17
  • Above code works but firstname and lastname values how we can pass? – jafar pinjar Sep 10 '18 at 7:51
  • @jafarpinjar the name of the subscriber is taken from the customer entity if one exists with that e-mail. Out of the box there's no way to set name values for guest customers as far as I can see. – Milan Simek Sep 13 '18 at 1:09
  • can we not override and customize it? – jafar pinjar Sep 14 '18 at 6:08
2
$email = 'test_email@gmail.com';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$subscriber= $objectManager->create('Magento\Newsletter\Model\SubscriberFactory'); 
$subscriber->create()->subscribe($email);

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.