要获取Gmail API消息的文本/纯文本部分,你需要遵循以下步骤:
Gmail API 是 Google 提供的一个服务,允许开发者访问用户的 Gmail 邮件数据。获取邮件的文本部分通常涉及到解析邮件的 MIME 结构,找到其中的纯文本部分。
users.messages.list
方法获取邮件列表。users.messages.get
方法获取特定邮件的详细内容。以下是一个简单的示例代码,展示如何获取并解析Gmail邮件的纯文本部分:
import base64
from email import policy
from email.parser import BytesParser
def get_message_text(service, user_id, msg_id):
message = service.users().messages().get(userId=user_id, id=msg_id).execute()
payload = message['payload']
# 查找纯文本部分
for part in payload['parts']:
if part['mimeType'] == 'text/plain':
body = base64.urlsafe_b64decode(part['body']['data'].encode('UTF-8'))
return body.decode()
# 如果没有找到纯文本部分,尝试解析整个邮件的MIME结构
if 'parts' in payload:
msg_bytes = base64.urlsafe_b64decode(payload['body']['data'].encode('UTF-8'))
else:
msg_bytes = base64.urlsafe_b64decode(message['payload']['body']['data'].encode('UTF-8'))
msg = BytesParser(policy=policy.default).parsebytes(msg_bytes)
for part in msg.walk():
if part.get_content_type() == 'text/plain':
return part.get_payload(decode=True).decode()
# 使用示例
# service = 已授权的Gmail API服务对象
# user_id = 'me'
# msg_id = '邮件的ID'
# text = get_message_text(service, user_id, msg_id)
# print(text)
通过以上步骤和示例代码,你应该能够成功获取Gmail邮件的纯文本部分。
领取专属 10元无门槛券
手把手带您无忧上云