Search code examples
google-apps-scriptgmailgmail-api

Google Apps Script - Changing label of individual email in Gmail


I want to change the label of an individual email programatically in gmail in a Google Script. I can't use the standard GmailApp service because it applies actions to the whole thread instead of an individual email. I've found a few examples of this being done with the Advanced Gmail API (Search/replace labels in specific messages (not the whole thread) with Google Apps Script). But I've not had success with this. I keep getting the following error:

Invalid number of arguments provided. Expected 3-4 only (line 5, file "test")

Here is a code snippet that I've tried in Google Script's Editor:

function changeLabel() {
  var addLabel = '3to-smartsheetstest';
  var removeLabel = '3to-smartsheets';
  var msgId = '142b7c52e4cc4619';
  var msgLabel = Gmail.Users.Messages.modify({
    'userId': 'me',
    'id': messageId,
    'resource':{
      'addLabelIds': [addlabel],
      'removeLabelIds': [removelabel]
    }
  })
}

Google's resource documentation says to structure the parameters like this for javascript:

'userId': userId,
'id': messageId,
'addLabelIds': labelsToAdd,
'removeLabelIds': labelsToRemove

But it seems that it actually needs to be structured this way (clarified in a bug report here: https://github.com/google/google-api-nodejs-client/issues/312):

'userId': 'some email address',
'id': 'some message id',
'resource':{
    'addLabelIds': ['some label id'],
    'removeLabelIds': []
}

Either way I get the same error.


Solution

  • How about this modification?

    Modification points:

    • Please modify the spelling of variables for Gmail.Users.Messages.modify().
      • Modify messageId to msgId.
      • Modify addlabel to addLabel.
      • Modify removelabel to removeLabel.
    • You can use Gmail.Users.Messages.modify() like Gmail.Users.Messages.modify(resource, userId, id). You can see this by the autocomplete of the script editor.

    Modified script:

    From:
    var msgLabel = Gmail.Users.Messages.modify({
      'userId': 'me',
      'id': messageId,
      'resource':{
        'addLabelIds': [addlabel],
        'removeLabelIds': [removelabel]
      }
    })
    
    To:
    var msgLabel = Gmail.Users.Messages.modify({
      'addLabelIds': [addLabel],
      'removeLabelIds': [removeLabel]
    }, 'me', msgId);
    

    Note:

    • This modified script supposes that Gmail API is enabled at Advanced Google Services and API console.

    Reference:

    If I misunderstand your question, I'm sorry.