Try with below
/**
* Subscriber factory
*
* @var SubscriberFactory
*/
protected $_subscriberFactory;
public function __construct(
...
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
...
){
...
$this->_subscriberFactory = $subscriberFactory;
...
}
public function myUserDefinedFunction() {
$subscriber = $this->_subscriberFactory->create()->loadByEmail($email);
if ($subscriber->getId(){
echo __("This email address is already subscribed");
}
}
[Update]
Change state of the subscription, right at the time the customer is saved from the admin end.
1. app/code/Stackexchange/HideShip/etc/adminhtml/events.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_save_after_data_object">
<observer name="change_subscriber_state"
instance="Stackexchange\ModuleName\Observer\CustomereditPost"/>
</event>
</config>
2. app/code/Stackexchange/HideShip/Observer/CustomereditPost.php
<?php
namespace Stackexchange\ModuleName\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Newsletter\Model\SubscriberFactory;
use Magento\Newsletter\Model\Subscriber;
class CustomereditPost implements ObserverInterface
{
protected $_subscriberFactory;
public function __construct(
SubscriberFactory $subscriberFactory
)
{
$this->_subscriberFactory = $subscriberFactory;
}
public function execute(EventObserver $observer)
{
$email = "[email protected]";
$subscriber = $this->_subscriberFactory->create()->loadByEmail($email);
if ($subscriber->getId()) {
echo __("This email address is already subscribed");
} else {
//$this->_subscriberFactory->create()->subscribe($email);
$this->_subscriberFactory->create()
->setStatus(Subscriber::STATUS_SUBSCRIBED)
->setEmail($email)
->save();
}
}
}