Get Customer Id by email Magento 2.

Magento 2 We can get Customer data by customer email id.

You can get the customer id, first name, last name, and other customer specific data by customer email id.

You need to call Magento\Customer\Api\CustomerRepositoryInterface Interface to fetch customer-related data.

We need to call CustomerRepositoryInterface in our class __construct() method.

Using Block class,

namespace Rbj\Customer\Block;

class CustomerData extends \Magento\Framework\View\Element\Template
    protected $customerRepository;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        array $data = []
    ) {
        $this->customerRepository = $customerRepository;

     * Retrieve Customer id from email by website level
     * @return int
     * @throws \Magento\Framework\Exception\LocalizedException
    public function getCustomer($email)
        try {
            $websiteId = 1;
            $customer = $this->customerRepository->get($email,$websiteId);
        } catch (Exception $e) {
            throw new \Magento\Framework\Exception\LocalizedException(__("The customer email isn't defined."));
        return $customer->getId();

If a customer is available, return customer id otherwise throws an error for customer email id not found.

Call from a template file,

$email = "";
echo $customerId = $block->getCustomer($email);

2 // customer_id