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.
Joel Pham
Joel Pham is the CEO of Magenest, with extensive experience in eCommerce, business operations, and digital transformation. He has led projects for major brands across Magento, Shopify, Odoo, and enterprise technology solutions.