How To Assign label To Message in Google App Script

google-apps-script, javascript

Solution

You can use the addLabel method to apply label to a thread, not a message. Also, since you are using the larger search operator, there's little need to recheck the attachment size later.

var threads = GmailApp.search('in:inbox has:attachment larger:15M');
var label = GmailApp.getUserLabelByName("label name goes here");

for (var t in threads) {
  threads[t].addLabel(label);
}

Problem

Hi I am making a script which will search mail on Gmail and if then assign label to the searched mails, but i am not sure how to assign label to messages, i am able to create lable but i cannot assign it. Another thing i want to know whether i am using Utilities sleep function at correctly or not. ``` function addNaggingLabels() { var label = _getNaggingLabel(); var start = parseInt(UserProperties.getProperty("start")); var sheet = SpreadsheetApp.getActiveSheet(); var ss = SpreadsheetApp.getActiveSpreadsheet() for (;;) { // Find all Gmail messages that have attachments var threads = GmailApp.search('in:inbox has:attachment larger:15M'); if (threads.length == 0) { ss.toast("Processed " + start + " messages.", "Scanning Done", -1); return; } for (var i=0; i<threads.length; i++) { var messages = threads[i].getMessages(); UserProperties.setProperty("start", ++start); for (var m=0; m<messages.length; m++) { var size = getMessageSize(messages[m].getAttachments()); if (size>15) { Logger.log("label: " + GmailApp.createLabel("FOO")); } } } } // Wait for a second to avoid hitting the system limit Utilities.sleep(1000); return Math.round(size*100/(1024*1024))/100; } function getMessageSize(att) { var size = 0; for (var i=0; i<att.length; i++) { //size += att[i].getBytes().length; size += att[i].getSize(); // Better and faster than getBytes() } } ```

Original source