W3docs

Facebook Graph API, how to get users email?

To get the email of a user through the Facebook Graph API, you will need to follow some steps.

To get the email of a user through the Facebook Graph API, you will need to:

  1. Have the user grant your app permission to access their email address. You can do this by using the email permission in your Facebook Login flow.
  2. Make a request to the Graph API to get the user's email address. You can do this by making a GET request to the /me endpoint and specifying the fields parameter with the value email.

Here is an example of how to do this in PHP:

How to get the email of a user through the Facebook Graph API in PHP?

<?php

// Requires: composer require facebook/graph-sdk:^5.0
$fb = new Facebook\Facebook([
    'app_id' => '{app-id}',
    'app_secret' => '{app-secret}',
    'default_graph_version' => 'v18.0',
]);

try {
    // Get the Facebook\GraphNodes\GraphUser object for the current user.
    // The access token should be obtained via the Facebook Login (OAuth 2.0) flow.
    $response = $fb->get('/me?fields=email', '{access-token}');
} catch (Facebook\Exceptions\FacebookResponseException $e) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();
    exit();
} catch (Facebook\Exceptions\FacebookSDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit();
}

$me = $response->getGraphUser();
echo 'Logged in as ' . $me->getName();

// Print the email (handle cases where permission is denied or email is hidden)
$email = $me->getEmail();
echo 'Email: ' . ($email ?? 'Not available');

Note that this will only work if the user has granted your app the email permission and if the user's privacy settings allow your app to access their email address.