Move all threads older than X with gmail api

1k Views Asked by At

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

There are 1 best solutions below

0
On BEST ANSWER

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.