Google Apps Script - Changing label of individual email in Gmail

我是研究僧i 提交于 2021-02-19 15:53:33

问题


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.


回答1:


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:

  • Using autocomplete

If I misunderstand your question, I'm sorry.



来源:https://stackoverflow.com/questions/52270973/google-apps-script-changing-label-of-individual-email-in-gmail

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