Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Assign label To Message in Google App Script

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()
  }
}
like image 420
Rahul Sharma Avatar asked Jul 05 '14 09:07

Rahul Sharma


1 Answers

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);
}
like image 185
Amit Agarwal Avatar answered Oct 03 '22 02:10

Amit Agarwal