Gmail API - 快速访问曾经发送/接收的每封电子邮件的日期

Gmail API - Quickly access the dates of every email ever sent / received

我正在尝试分析我的 25k+ 封电子邮件,类似于此处的 post:http://beneathdata.com/how-to/email-behavior-analysis/

虽然提到的脚本使用 IMAP,但我正在尝试使用 Gmail API 来实现它以提高安全性。我正在使用 Python(和 Pandas 进行数据分析),但这个问题更普遍地适用于 Gmail API.

的使用

从文档中,我可以使用以下方式阅读电子邮件:

msgs = service.users().messages().list(userId='me', maxResults=500).execute()

然后使用循环访问数据:

for msg in msgs['messages']:
    m_id = msg['id'] # get id of individual message
    message = service.users().messages().get(userId='me', id=m_id).execute()
    payload = message['payload'] 
    header = payload['headers']

    for item in header:
        if item['name'] == 'Date':
           date = item['value']
           ** DATA STORAGE FUNCTIONS ETC **

但这显然很慢。除了循环遍历每条消息外,我还必须多次调用 list() API 来循环遍历所有电子邮件。

是否有更高性能的方法来做到这一点?例如要求 API 仅 return 数据而不是所有不需要的消息信息。

谢谢。

参考:https://developers.google.com/resources/api-libraries/documentation/gmail/v1/python/latest/gmail_v1.users.messages.html

您可以将 messages.get() 操作分批处理,请参阅:https://developers.google.com/gmail/api/guides/batch

您最多可以将 100 个请求放入一个批次中。

请注意 "a set of n requests batched together counts toward your usage limit as n requests, not as one request." 因此您可能需要调整一些节奏以保持在请求率限制之下。

这是一个粗略的 Python 示例,它将获取 ID 列表给出的消息 id_list

msgs = []
def fetch(rid, response, exception):
    if exception is not None:
        print exception
    else:
        msgs.append(response)

# Make a batch request
batch = gmail.new_batch_http_request()
for message_id in id_list:
    t = gmail.users().messages().get(userId='me', id=message_id, format=fmt)
    batch.add(t, callback=fetch)

batch.execute(http=http)