0

I have an administrator account of G-Suite,I use this code to get gmail address of my company:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']
def main():
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('Calendar_Administrator.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('admin', 'directory_v1', credentials=creds)
    results = service.users().list(customer='my_customer', maxResults=500,orderBy='email').execute()
    users = results.get('users', [])
    if not users:
        print('No users in the domain.')
    else:
        print('Users:')
        for user in users:
            print(u'{0} {1}'.format(user['primaryEmail'],
                user['name']['fullName']))


if __name__ == '__main__':
    main()

As the official page said:

maxResults:Maximum number of results to return. Default is 100. Maximum is 500. Acceptable values are 1 to 500, inclusive.

I can only get 500 gmail address.Actually, there are more than 3000 people in my company.

How can I get everyone's mailbox?How to modify my code?

2 Answers2

1

I use nextPageToken to solve this problem,my code:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = 'https://www.googleapis.com/auth/admin.directory.user'
def main():

    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('Calendar_Administrator.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('admin', 'directory_v1', credentials=creds)
    results = service.users().list(customer='my_customer',maxResults=500,orderBy='email').execute()
    users = results.get('users', [])
    nextPageToken = results.get('nextPageToken', {})
    print(nextPageToken)
    if not users:
        print('No users in the domain.')
    else:
        print('Users:')
        for user in users:
            print(u'{0} {1}'.format(user['primaryEmail'],
                user['name']['fullName']))


    loopFlag = True
    while loopFlag:
        if nextPageToken:
            print(nextPageToken)
            results = service.users().list(customer='my_customer', pageToken = nextPageToken, maxResults=500, orderBy='email').execute()
            users = results.get('users', [])
            if not users:
                print('No users in the domain.')
            else:
                print('Users:')
                for user in users:
                    print(u'{0} {1}'.format(user['primaryEmail'],
                                            user['name']['fullName']))

            nextPageToken = results.get('nextPageToken', {})
            if not nextPageToken:
                loopFlag = False
                break


if __name__ == '__main__':
    main()
0

You are using Users:list which retrieves a paginated list of either deleted users or all users in a domain. The number set as maxResults stands for the maximum number of results per page. Since you're already getting Gmail addresses, I'm pretty sure your response looks like this:

{
  "kind": "admin#directory#users",
  "etag": etag,
  "users": [
    users Resource
  ],
  "nextPageToken": string
}

You're already retrieving all your users, but you're not seeing it because you did not specify a nextPageToken which is a token used to access next page of this result. You can find this information from the bottom of this page.

Jacque
  • 757
  • 4
  • 9