gpt4 book ai didi

python - 如何使用 gmail api 获取我的 gmail 帐户的每封邮件的正文?

转载 作者:太空宇宙 更新时间:2023-11-04 04:18:13 30 4
gpt4 key购买 nike

我正在尝试使用 google oauth 和 gmail api 服务从我的 gmail 帐户解析每个邮件正文。目前我只能获取消息 ID 和线程 ID,当我打开它们时根本没有任何意义。所以我使用的以下代码如下:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
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()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)

service = build('gmail', 'v1', credentials=creds)

# Call the Gmail API
results = service.users().labels().list(userId='me').execute()
print(service.users().messages().list(userId='me').execute())
print(service.users().messages().get(userId='me', id='16931216e3a05048').execute())
labels = results.get('labels', [])

if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
print(label['name'])

if __name__ == '__main__':
main()

对于使用此行 print(service.users().messages().get(userId='me', id='16931216e3a05048') 的消息 ID 之一,我得到的输出是这样的。执行())

输出是这样的: this is the output I have been getting using the above piece of code

最佳答案

你忘记添加格式了

messages.get

enter image description here

message = service.users().messages().get(userId=user_id, id=msg_id,
format='raw').execute()

print 'Message snippet: %s' % message['snippet']

msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))

mime_msg = email.message_from_string(msg_str)

关于python - 如何使用 gmail api 获取我的 gmail 帐户的每封邮件的正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55045670/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com