Plugin for Subscribe() method of email subscription Magento 2.

Subscribe by Email id in Magento 2 Use Subscribe($email) method to newsletter subscription in native code.

Native Class:
Magento\Newsletter\Model\Subscriber (Magento_Newsletter)

Subscriber Class contains a list of native methods related to the subscription functionality of Magento 2.

Common functions used in Subscription Class:

  • subscribe()
  • unsubscribe()
  • confirm()
  • updateSubscription()
  • sendConfirmationRequestEmail()
  • sendConfirmationSuccessEmail()
  • beforeSave()

If you want to add some logic after subscription completed you need to create afterSubscribe() method.

Create di.xml file at Global area scope,
Path:
app/code/Jesadiya/Newsletter/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Newsletter\Model\Subscriber">
        <plugin name="custom_name_plugin" type="Jesadiya\Newsletter\Plugin\Model\Subscriber"
                sortOrder="30"/>
    </type>
</config>

Create a plugin PHP file to add your custom logic after customer subscribe,
Path:
app\Code\Jesadiya\Newsletter\Plugin\Model\Subscriber.php

<?php
namespace Jesadiya\Newsletter\Plugin\Model;

use Exception;
use Psr\Log\LoggerInterface;
use Magento\Customer\Model\Customer;
use Magento\Newsletter\Model\Subscriber;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Customer\Model\ResourceModel\Customer as CustomerResource;
use Magento\Newsletter\Model\ResourceModel\Subscriber as SubscriberResource;

class Subscribe
{
    /**
     * Plugin for after subscribe
     *
     * @param Subscriber $subject
     * @param int        $result
     * @param string     $email
     *
     */
    public function afterSubscribe(
        Subscriber $subject,
        int $result,
        string $email
    ) {

        //$email email id to be subscribe
        if ($subject->getStatus() === Subscriber::STATUS_SUBSCRIBED) {
            // custom code
        } else {
            // custom code
        }

        return $result;
    }
}

In the Plugin file, $subject contains the Subscribe Class methods.

You can add your additional logic after the subscribe method called completed using the plugin way by the given approach.