如何使用G-Suite Admin SDK Directory API获取所有人的Gmail?

时间:2019-03-13 09:39:55

标签: python-3.x google-api google-admin-sdk

我有一个G-Suite管理员帐户,我使用此代码获取我公司的gmail地址:

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()

官方page说:

  

maxResults:要返回的最大结果数。默认值是100。最大值是500。可接受的值是1到500(含)。

我只能获得500个Gmail地址。实际上,我公司有3000余人。

如何获取每个人的邮箱?如何修改我的代码?

2 个答案:

答案 0 :(得分:0)

您正在使用Users:list来检索已删除用户或域中所有用户的分页列表。设置为maxResults的数字代表maximum number of results per page。由于您已经获得了Gmail地址,因此我很确定您的回复如下所示:

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

您已经在检索所有用户,但是没有看到它,因为您没有指定nextPageToken,这是用于访问此结果下一页的令牌。您可以从此page的底部找到此信息。

答案 1 :(得分:0)

我使用nextPageToken解决此问题,我的代码:

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()