来自 Google Workspace 的用户邮箱使用情况报告

问题描述 投票:0回答:1

我正在尝试获取基本的电子邮件使用情况报告。我们需要获取用户名及其电子邮箱的大小。下面提供的代码抛出异常

https://admin.googleapis.com/admin/directory/v1/users?alt=json 返回“错误请求”。详细信息:“[{'message': '错误请求', 'domain': ' global', 'reason': 'badRequest'}]">**" 就行了

users = service.users().list().execute()

完整代码如下:

from __future__ import print_function
import os.path
import csv
import io
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# If modifying these scopes, delete the file token.json.
#SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly']
SCOPES = ['https://admin.googleapis.com/admin/directory/v1/users']

creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

service = build('admin', 'directory_v1', credentials=creds)
print('Getting users in the domain')
users = service.users().list().execute()

    # Create a dictionary to store the user data.
user_data = {}

    # Iterate over the list of users and get their first name, last name, and mailbox size.
for user in users["users"]:
        user_data[user["primaryEmail"]] = {
        "firstName": user["name"]["givenName"],
        "lastName": user["name"]["familyName"],
        "mailboxSize": user["storage"]["quotaUsage"],
    }

# Open the CSV file for writing.
with open("user_data.csv", "w", newline="") as f:
    writer = csv.writer(f)

    # Write the header row.
    writer.writerow(["email", "firstName", "lastName", "mailboxSize"])

    # Iterate over the user data and write each user's data to a new row in the CSV file.
    for email, data in user_data.items():
        writer.writerow([email, data["firstName"], data["lastName"], data["mailboxSize"]])

# Close the CSV file.
f.close()

凭证正确。测试多次。正如您从示例中看到的,我尝试使用不同的范围。 我在这里做错了什么?

python google-api google-admin-sdk google-api-python-client google-directory-api
1个回答
0
投票

你错过了你的

customer='my_customer'

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']

USER_TOKEN = "token_create_user.json"

CREDENTIALS = 'C:\Development\FreeLance\GoogleSamples\Credentials\Workspace-Installed-TestEverything.json'

def main():
    """Shows basic usage of the Admin SDK Directory API.
    Prints the emails and names of the first 10 users in the domain.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(USER_TOKEN):
        creds = Credentials.from_authorized_user_file(USER_TOKEN, SCOPES)
    # 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(
                CREDENTIALS, SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(USER_TOKEN, 'w') as token:
            token.write(creds.to_json())

    service = build('admin', 'directory_v1', credentials=creds)

   

    # Call the Admin SDK Directory API
    print('Getting the first 10 users in the domain')
    results = service.users().list(customer='my_customer', maxResults=10,
                                   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()
© www.soinside.com 2019 - 2024. All rights reserved.