How to Get Customer Data by Customer email in Magento 2?

In today's tutorial, we will teach you how to get customer data by the email id of customers in Magento 2. Getting customer data this way helps in sorting out the customer groups and cater them accordingly. Here is the code snippet that you can use to get customer data by customer email in Magento 2:

<?php
namespace MageDelight\Customer\Block;
class Customer extends \Magento\Framework\View\Element\Template
{
 public function __construct(
 \Magento\Framework\View\Element\Template\Context $context,
 \Magento\Customer\API\CustomerRepositoryInterface $customerRepository,
 array $data = []
 ) {
 $this->customerRepository = $customerRepository;
 parent::__construct($context, $data);
 }
 /*
 * $email string
 * $websiteId int
 */
 public function getCustomerByEmail($email,$websiteId = null)
 {
 return $this->customerRepository->get($email,$websiteId);
 }

Now, call getCustomerByEmail() function in template file:

$customerEmail = '@example.com';
$websiteId = 1; // pass website id
$customer = $block->getCustomerByEmail($customerEmail,$websiteId);
echo $customer->getFirstname();
echo $customer->getEmail();
echo $customer->getLastname();

Pro Tip:

You can also get customer data of all the customers with the below-mentioned method:

echo “<pre>”;print_r($customer->__toArray());

We hope we covered everything related to getting customer data by customer email in Magento 2. If we missed out on anything, feel free to reach us out!

Also read: How to Change or Update Email Addresses in Magento 2?