0

我正在尝试分析我的 25k 多封电子邮件,类似于此处的帖子: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 只返回数据而不是所有不需要的消息信息。

谢谢。

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

4

1 回答 1

4

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

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

请注意,“一组 n 个请求一起批处理计入您的使用限制,作为 n 个请求,而不是一个请求。” 因此,您可能需要进行一些调整以保持低于请求速率限制。

这是一个粗略的 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)
于 2017-10-07T00:20:34.773 回答