如何在Python 3.10中通过邮箱获取Google账号的姓名?
Got it, let's break this down. Gmail automatically maps email addresses to contact names because it pulls from your connected contacts list—but there’s no direct "get name by email" endpoint in the Gmail API itself. Instead, you’ll want to use the Google People API, which is designed to access contact and profile data linked to your Google account. Here’s a step-by-step implementation tailored for Python 3.10:
Step 1: Set Up Google Cloud Credentials
First, you need to enable the People API and get OAuth credentials:
- Head to the Google Cloud Console, create a new project, and search for "People API" to enable it.
- Go to Credentials > Create Credentials > OAuth client ID, select "Desktop app" as the application type, and download the resulting
credentials.jsonfile to your project folder.
Step 2: Install Required Packages
Run this command in your terminal (fully compatible with Python 3.10):
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
Step 3: Python Implementation Code
This script will authenticate your account, search for the given email address in your contacts, and return the associated name:
from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import pickle import os.path # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/contacts.readonly'] def get_contact_name_by_email(target_email): creds = None # The file token.pickle stores your access/refresh tokens, auto-created on first auth if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # Refresh or re-authenticate if credentials are invalid/expired 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 credentials for future runs with open('token.pickle', 'wb') as token: pickle.dump(creds, token) # Initialize People API service service = build('people', 'v1', credentials=creds) # Search contacts matching the target email results = service.people().searchContacts( query=target_email, readMask='names,emailAddresses').execute() contacts = results.get('results', []) if not contacts: return f"No name found for email: {target_email}" else: # Extract the primary display name from the first matching contact contact = contacts[0].get('person') names = contact.get('names', []) return names[0].get('displayName') if names else f"No name associated with email: {target_email}" # Example usage if __name__ == '__main__': email_to_check = "example@domain.com" print(get_contact_name_by_email(email_to_check))
Key Notes
- Known contacts only: This will only return names for emails your Google account has interacted with (saved contacts, past recipients, etc.). It can’t pull names for completely unknown emails—Gmail doesn’t expose that public data.
- First-run auth: The first time you run the script, a browser window will pop up asking you to log in with your Google account and grant permission to access your contacts.
- Token persistence: The
token.picklefile saves your credentials so you don’t have to re-authorize every time. Delete it if you need to switch accounts or update scopes.
内容的提问来源于stack exchange,提问作者user19926715

