Move all threads older than X with gmail api

大憨熊 提交于 2019-12-13 02:03:23

问题


I have a folder, Archive where I'd like to store all of my emails from before a given date.

In the Gmail web UI, you can accomplish this by doing a search like "in:inbox before:2012/01/01", select all, then "move" from the dropdown.

I'd like to do this with the gmail api. How can I accomplish this? Will I need to do the query then iterate through each thread to move it? Or is there a better way?

Bonus points for a code snippet / example or link to the relevant section of api docs.


回答1:


You are right on the money. You need to get every threadId and move them one at a time (can be achieved by a batch request, but they will count as individual requests to your quota anyway). Might be another solution with another API I don't know of.

But with the Gmail API you would do the following.

Get all threadIds from your inbox which got received before a given date.

GET https://www.googleapis.com/gmail/v1/users/me/threads?fields=nextPageToken%2Cthreads%2Fid&q=n%3Ainbox+before%3A2012%2F01%2F01&key={YOUR_API_KEY}

Which will give you the following data:

{
 "threads": [
  {
   "id": "12345"
  },
  {
   "id": "123456"
  },
  {
    .
    .
    .
  }
 ],
 "nextPageToken": "112233"
}

Use the nextPageToken in the next request to get more threadIds.

GET https://www.googleapis.com/gmail/v1/users/me/threads?pageToken=112233&fields=nextPageToken%2Cthreads%2Fid&q=n%3Ainbox+before%3A2012%2F01%2F01&key={YOUR_API_KEY}

Repeat previous step until there is no nextPageToken in the response.

You now have all the threads that were active before your given date (2012/01/01).

Modify them one by one. Remove the INBOX-label and add the Archive-label

POST https://www.googleapis.com/gmail/v1/users/me/threads/12345/modify?key={YOUR_API_KEY}

{
 "addLabelIds": [
  "Archive"
 ],
 "removeLabelIds": [
  "INBOX"
 ]
}

Again, this can be done in a batch request, but will still count as many separate ones.

Depending on how many threads you have, you might end up doing more requests per second than Google allows. If you get an error, wait for a moment in your code, and continue.



来源:https://stackoverflow.com/questions/31012222/move-all-threads-older-than-x-with-gmail-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!