已添加Gmail OAuth测试用户仍需重复授权,如何正确授权测试应用?
解决Gmail OAuth测试应用重复授权问题
你的问题核心是没有持久化授权凭据,每次运行代码都会重新触发OAuth授权流程——添加测试用户只是让你能在应用处于测试状态时正常调用API,而非跳过授权步骤。
解决方案:持久化授权凭据
修改代码,将首次授权后的凭据保存到本地文件,后续运行直接加载该文件,无需重复授权:
import base64 import os.path from email.mime.text import MIMEText from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from requests import HTTPError from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request SCOPES = ["https://www.googleapis.com/auth/gmail.send"] def get_credentials(): creds = None # 检查本地是否有已保存的凭据文件 if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # 无有效凭据时触发授权或刷新流程 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) # 将凭据写入本地文件,供后续运行使用 with open('token.json', 'w') as token: token.write(creds.to_json()) return creds # 获取授权凭据 creds = get_credentials() service = build('gmail', 'v1', credentials=creds) message = MIMEText('This is the body of the email') message['to'] = 'recipient@gmail.com' message['subject'] = 'Email Subject' create_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} try: message = (service.users().messages().send(userId="me", body=create_message).execute()) print(f'sent message to {message} Message Id: {message["id"]}') except HTTPError as error: print(f'An error occurred: {error}') message = None
额外注意事项
- 首次运行代码时仍需完成一次OAuth授权流程,之后
token.json会自动生成,后续运行无需再授权。 - 确认你的邮箱已正确添加到「OAuth同意屏幕 > 测试用户」列表,且发送邮件的账号与该邮箱一致。
- 若
token.json丢失或过期,删除该文件后重新运行代码,即可再次触发授权流程生成新凭据。
内容的提问来源于stack exchange,提问作者stevew
相关产品推荐
相关产品推荐

