Search code examples
gmailgmail-api

Gmail API: asynchronous label update/application


I'm using the Users.messages:modify method to apply labels to emails, however, I must refresh the page before the labels which I apply programmatically appear on the gmail user interface.

The desired action is akin to if I manually select a gmail message and then apply a label from the dropdown label applicator at the top of the gmail screen: the label is applied asynchronously. Is this possible to do programmatically?

Code

var applyLabel = function (gapiRequestURL, labelIdsArr)
{

  $.ajax({
    url: gapiRequestURL,
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify({
      addLabelIds: labelIdsArr
    }),
    success: function(msg){
      // alert(JSON.stringify(msg));
    },
    error: function(msg){
      alert("Error:" + JSON.stringify(msg));
    }
  })
}

var decideWhichLabelToApply = function(messageContentsArr){
  var testLabelOne = "Label_12"
  var testLabelTwo = "Label_13"
  var labelIdsArr = []

  for(var i=0; i < messageContentsArr.length; i++){
    var currentMessage = messageContentsArr[i]
    var messageID = currentMessage.id

    if (true){
      var labelModifyURL = "https://www.googleapis.com/gmail/v1/users/me/messages/" + messageID + "/modify?access_token=" + thisToken
      labelIdsArr.push(testLabelOne)
      applyLabel(labelModifyURL, labelIdsArr)
    }
    else {
      var labelModifyURL = "https://www.googleapis.com/gmail/v1/users/me/messages/" + messageID + "/modify?access_token=" + thisToken
      labelIdsArr.push(testLabelTwo)
      applyLabel(labelModifyURL, labelIdsArr)
    }
  }
}

Solution

  • Not that I know of. The Gmail web interface does some lazy caching and doesn't seem to notice particularly well changes to the underlying data (i.e. from Inbox, IMAP, API, etc). I believe it doesn't require a full browser (F5) refresh but certainly one needs to do some UI action like clicking on labels or hitting the in-webpage refresh icon for update to show up.