- Home
- Technical Guidelines
- How to add Magento 2 subscriber programmatically?
How to add Magento 2 subscriber programmatically?
September 18 2020
Lucy Pham
249 Views
0 Comment
0 Stars
You need to initialize the object, Magento\Newsletter\Model\SubscriberFactory to add a subscriber. You can also add the subscriber by any email.
Follow example below to set magento 2 subscriber programmatically
/** * @var \Magento\Newsletter\Model\SubscriberFactory */ protected $subscriberFactory; public function __construct( ... \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory, ... ) { ... $this->subscriberFactory = $subscriberFactory; ... } public function execute() { $email = 'example@gmail.com'; $this->subscriberFactory->create()->subscribe($email); // Subscribes by email // Load email and update status $subscriber = $this->subscriber->create()->loadByEmail($email); $subscriber->setStatus(\Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED); $subscriber->save(); }
- \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED: User has confirmed and subscriber to the newsletter
- \Magento\Newsletter\Model\Subscriber::STATUS_NOT_ACTIVE: User subscriber to the newsletter but waiting for confirmation to activate the subscription
- \Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED: User may or may not have confirmed his email address but is certainly not subscribed to the newsletter
- \Magento\Newsletter\Model\Subscriber::STATUS_UNCONFIRMED: User has subscribed to the newsletter but does not need to confirm the email address
This article introduces how to add a subscriber programmatically by email in Magento 2 and change subscriber status. We are here to help when you have questions on any steps, don’t hesitate to contact us.
Share This Blog:

Lucy Pham
Marketing Executive | Content Manager
Recommended For You
Categories
-
eCommerce (221)
- » Magento 2 Migration (16)
- » Insight (83)
- » Tips & Tricks (120)
- Extension (45)
-
News & Deals (22)
- » Deals (4)
- Technical Guidelines (85)
Weekly Trending
-
10 Best Mega Menu Examples in 2020October 29 2020
Recent Posts
-
Overview of 6 Best Magento 2 Payment Gateway ProvidersJanuary 25 2021
-
Social Login: Everything You Should Know About ItJanuary 23 2021
-
What is SMS Marketing & What does it work in Magento 2?January 21 2021
-
How to validate custom input fields in Magento 2January 20 2021