要使用 Gmail API 获取特定用户的第一条消息,您需要遵循以下步骤:
http://localhost
)。使用 Python 的话,您可以通过 pip 安装 Google API 客户端库:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
以下是一个示例代码,展示如何使用 Gmail API 获取特定用户的第一条消息:
import os
import base64
import json
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
# 如果修改这些 SCOPES,删除文件 token.json。
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def main():
"""Shows basic usage of the Gmail API.
Lists the user's first message.
"""
creds = None
# token.json 存储用户的访问和刷新令牌,首次运行时会创建。
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())
# 调用 Gmail API
service = build('gmail', 'v1', credentials=creds)
# 获取用户的邮件列表
results = service.users().messages().list(userId='me', maxResults=1, orderBy='ascending').execute()
messages = results.get('messages', [])
if not messages:
print('没有找到消息。')
else:
# 获取第一条消息的 ID
first_message_id = messages[0]['id']
# 获取消息详细信息
message = service.users().messages().get(userId='me', id=first_message_id).execute()
# 打印消息主题
for header in message['payload']['headers']:
if header['name'] == 'Subject':
print('第一条消息的主题:', header['value'])
# 打印消息内容(可选)
if 'data' in message['payload']['parts'][0]['body']:
data = message['payload']['parts'][0]['body']['data']
decoded_data = base64.urlsafe_b64decode(data).decode('utf-8')
print('消息内容:', decoded_data)
if __name__ == '__main__':
main()
token.json
文件,如果存在,则加载凭据;如果不存在,则通过 OAuth 流程获取凭据。service.users().messages().list()
方法获取用户的邮件列表,设置 maxResults=1
和 orderBy='ascending'
以获取第一条消息。service.users().messages().get()
方法获取该消息的详细信息。云+社区技术沙龙[第21期]
云+社区技术沙龙[第14期]
云+社区技术沙龙[第10期]
云+社区技术沙龙[第7期]
腾讯云GAME-TECH游戏开发者技术沙龙
云+社区技术沙龙[第9期]
领取专属 10元无门槛券
手把手带您无忧上云