Site icon MageComp Blog

How to Add Newsletter Subscriber Programmatically in Magento 2?

How to Add Newsletter Subscriber Programmatically in Magento 2

Hello Magento Friends,

In today’s blog, we will learn about How to Add Newsletter Subscriber Programmatically in Magento 2?

A newsletter helps to build relationships with customers. It is an important aspect of the email marketing strategy of an eCommerce business. Learn How to Grow Newsletter Subscribers.

Magento 2 store owners can easily create newsletters and manage subscribers using the admin panel. Moreover, Newsletter Popup helps to catch users’ attention and increase the newsletter subscribers list.

You have an email of customers, and you want to add them to the newsletter subscriber list. You can achieve it programmatically in Magento 2. Let’s learn How to Add Newsletter Subscriber Programmatically in Magento 2.

Steps to Add Newsletter Subscriber Programmatically in Magento 2:

Step 1: Create a Data.php file inside the Helper folder

app\code\Vendor\Extension\Helper

Then add the code as follows

<?php
namespace Vendor\Extension\Helper;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{
   protected $subscriberFactory;

   public function __construct(
         \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
         )
   {
       $this->_subscriberFactory = $subscriberFactory;
   }
     
   public function setNewslettersubscriber()
   {
      $customeremail = 'test.magecomp@gmail.com';
      $subscriber = $this->_subscriberFactory->create()->loadByEmail($customeremail);
      $subscriber->setStatus(\Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED);
      $subscriber->save();
   }
}

You can initialize the object, Magento\Newsletter\Model\SubscriberFactory, to add a subscriber in block, controller etc. You can also add the subscriber by any email ID.

Conclusion:

This way, you can add newsletter subscribers programmatically in Magento 2. Admin can send Newsletters Manually to Customer Group in Magento 2. If you have difficulty adding the newsletter subscriber, contact me through comments for the solution.

Share the tutorial with your friends on social media and stay in the know for the latest updates.

Happy Coding!

Exit mobile version