在新Gmail API中批量获取邮件

26 投票
2 回答
6447 浏览
提问于 2025-04-18 12:03

我正在使用谷歌新发布的Gmail API的Python版本。

下面这个调用只返回了一堆消息的ID:

service.users().messages().list(userId = 'me').execute()

但是这样我就只有一堆消息的ID了,需要一个一个地去处理。

有没有办法一次性获取这些ID对应的完整消息内容呢?(就像在谷歌日历API中那样)?

如果现在还不支持的话,谷歌会考虑在API中添加这个功能吗?

更新

这是对我有效的解决方案:
batch = BatchHttpRequest() for msg_id in message_ids: batch.add(service.users().messages().get(userId = 'me', id = msg_id['id']), callback = mycallbackfunc) batch.execute()

2 个回答

14

这是对我有效的解决办法:

batch = BatchHttpRequest()
for msg_id in message_ids:
    batch.add(service.users().messages().get(userId='me', id=msg_id['id']), callback=mycallbackfunc)
batch.execute()
20

这里有一个在Java中批量请求的例子,我通过线程的ID获取所有的线程。这个例子可以很容易地根据你的需求进行调整。

BatchRequest b = service.batch();
//callback function. (Can also define different callbacks for each request, as required)
JsonBatchCallback<Thread> bc = new JsonBatchCallback<Thread>() {

    @Override
    public void onSuccess(Thread t, HttpHeaders responseHeaders)
            throws IOException {
        System.out.println(t.getMessages().get(0).getPayload().getBody().getData());
    }

    @Override
    public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders)
            throws IOException {

    }
};

// queuing requests on the batch requests
for (Thread thread : threads) {
    service.users().threads().get("me", threads.getId()).queue(b, bc);
}


b.execute();

撰写回答