2017-10-07 63 views
0

我试图分析我的25K +类似的帖子在这里电子邮件:http://beneathdata.com/how-to/email-behavior-analysis/Gmail的API - 快速访问曾经发送每封电子邮件的日期/接收

虽然使用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

回答

1

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

你可以把多达100个请求到一个批处理。

请注意,“一批n个请求一起批量计数,因为n个请求不是一个请求。”所以你可能需要做一些步骤来保持低于请求速率限制。

这里有一个粗略的Python的例子,将获取由IDS 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) 
+0

非常感谢您的帮助列表给出的消息!批量听起来像我在找什么。但是,这仍然会得到整个消息,然后我遍历所有消息来提取数据。你知道一种只返回某些数据/更有效的方法吗?另外,我想我仍然需要在批处理调用之前使用list/list_next来获取消息ID?欢呼 – SLater01

+0

你想要什么“某些数据”? (是的,你使用list()来获取消息ID的列表,然后get()来获取细节)。 – payne

+1

我通过设置format ='minimal'来获得它的工作。然后忽略消息体等,避免浪费数据传输。 – SLater01