以下是如何使用 Python 中的 Gmail API 读取来自特定电子邮件地址的电子邮件的示例:
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
def read_emails_from_specific_email(email_address, service):
result = service.users().messages().list(userId='me', q=f'from:{email_address}').execute()
messages = result.get('messages', [])
for message in messages:
msg = service.users().messages().get(userId='me', id=message['id']).execute()
print(f'Subject: {msg["subject"]}')
print(f'From: {msg["from"]}')
print(f'Body: {msg["body"]}')
# Use a service account to access the Gmail API
creds = Credentials.from_service_account_file('path/to/service_account.json', scopes=['https://www.googleapis.com/auth/gmail.readonly'])
service = build('gmail', 'v1', credentials=creds)
# Read emails from a specific email address
read_emails_from_specific_email('example@gmail.com', service)
在此示例中,read_emails_from_specific_email 函数采用两个参数:email_address 和 service。服务参数是 Gmail API 客户端的一个实例,用于与 API 交互。该函数使用 API 检索从指定的 email_address 发送的邮件列表,然后遍历邮件以打印其主题、发件人和正文。
在调用该函数之前,代码使用服务帐户获取授权令牌,该令牌用于访问 Gmail API。服务帐户凭据存储在一个 JSON 文件中,该文件被传递给 Credentials.from_service_account_file 方法。 scopes 参数指定应用程序需要访问的 Gmail API 范围。
最后,调用 read_emails_from_specific_email 函数,将要搜索的电子邮件地址和服务实例作为参数传递。