How to import contacts from gmail using php?

Member

by rollin , in category: Third Party Scripts , a month ago

How to import contacts from gmail using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , a month ago

@rollin 

To import contacts from Gmail using PHP, you can use Google's People API. Here is a step-by-step guide on how to do this:

  1. Create a Google API project:
  • Go to the Google Developers Console at https://console.developers.google.com/.
  • Create a new project and enable the People API for that project.
  • Create credentials for the API project by going to the "Credentials" section and selecting "Create credentials" -> "OAuth client ID". Choose "Web application" as the application type and add "http://localhost" as an authorized redirect URI.
  1. Install the Google API PHP client library:
  • You can install the library using Composer by running the following command in your project directory:
1
composer require google/apiclient:^2.0


  1. Write PHP code to import contacts from Gmail:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php

require_once 'vendor/autoload.php';

$client = new Google_Client();
$client->setAuthConfig('path/to/credentials.json');
$client->addScope('https://www.googleapis.com/auth/contacts.readonly');

if (isset($_GET['code'])) {
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token);
}

if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}

$service = new Google_Service_PeopleService($client);

$connections = $service->people_connections->listPeopleConnections('people/me', [
    'personFields' => 'names,emailAddresses',
]);

foreach ($connections->getConnections() as $person) {
    $names = $person->getNames();
    $emailAddresses = $person->getEmailAddresses();
    $name = $names[0]->getDisplayName();
    $email = $emailAddresses[0]->getValue();
    
    echo "Name: $name, Email: $email <br>";
}


  1. Run the PHP script:
  • Start a PHP development server by running the following command in your project directory:
1
php -S localhost:8000


  • Open a web browser and go to http://localhost:8000 to run the PHP script. Follow the authorization flow to grant access to your Gmail contacts.
  1. Handle the imported contacts:
  • Once the script is successfully executed, you should see a list of names and email addresses of your Gmail contacts printed on the webpage.


That's it! You have successfully imported contacts from Gmail using PHP.