【发布时间】:2021-03-03 21:04:04
【问题描述】:
我正在编写一个脚本,它从我的 gmail 收件箱中获取 n 封电子邮件并将 n 个主题写入一个文本文件。虽然这目前工作正常。我正在寻找一种方法来获取例如 20 封 JSON 格式的电子邮件,只需要一次调用,而不是在一个循环中一个接一个地进行。
目前我有这个:
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(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
resultsMessages = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
messages = resultsMessages.get('messages', [])
f = open("output.txt", "a")
message_count = int(input("How many messages do you want to write?"))
if not messages:
print("no messages found")
else:
print("messages:")
for i, message in enumerate(messages[:message_count]):
f.write("message "+ str(i))
msg = service.users().messages().get(userId='me', id=message['id']).execute()
headers = msg["payload"]["headers"]
subject = [i['value'] for i in headers if i["name"] == "Subject"]
f.write("subject: "+subject[0])
f.write("\n")
f.close()
if __name__ == '__main__':
main()
这基本上是获取 100 封电子邮件的 ID,然后它会通过每封电子邮件获取主题并将其写入文件。它工作正常,但我想找到一种更快的方法。有没有什么方法可以让我只用一个电话就可以从服务器获取 n 封 JSON 格式的电子邮件?我想我的代码的瓶颈是调用msg = service.users().messages().get(userId='me', id=message['id']).execute()
在循环中执行。
非常感谢
【问题讨论】:
-
@DalmTo 代码在这里甚至不相关,我只是想知道是否有一种方法可以通过一次调用获取例如 20 封 JSON 格式的电子邮件,而不是在一个循环。
标签: python google-api gmail gmail-api google-api-python-client