Create a native filter in Gmail using Google Apps Script
<p>I want to make a filter that is native to gmail for certain set of parameters.</p>

<p>Basically I use the google alias function a lot (the + sign after your email). I want to automate the process of creating a filter that reads the "To" line then looks for a "+". If the a "+" is found it will make a label of what is after the "+". Then it will create a dedicated/native filter that will: skip the inbox and apply the label of what is after the "+".</p>

<p>I have looked through the gmail scripts and have not found a way to make a native filter. I understand that this functionality might have just been implemented. </p>

<pre><code>function getTo() { 
  // Log the To line of up to the first 50 emails in your Inbox 
  var email = Session.getActiveUser().getEmail(); 
  Logger.log(email); 
  var threads = GmailApp.getInboxThreads(0, 50); 
  for (var i = 0; i &lt; threads.length; i++) { 
    var messages = threads[i].getMessages(); 
    for (var j = 0; j &lt; messages.length; j++) {
      Logger.log(messages[j].getTo()||email); 
     } 
   }
}
</code></pre>

<p>Any help would be great. </p>

<p>Solution:</p>

<pre><code>// Creates a filter to put all email from ${toAddress} into
// Gmail label ${labelName}
function createToFilter(toAddress, labelName) {

// Lists all the filters for the user running the script, 'me'
var labels = Gmail.Users.Settings.Filters.list('me')

// Search through the existing filters for ${toAddress}
var label = true
labels.filter.forEach(function(l) {
    if (l.criteria.to === toAddress) {
        label = null
    }
})

// If the filter does exist, return
if (label === null) return
else { 
// Create the new label 
GmailApp.createLabel(labelName)

// Lists all the labels for the user running the script, 'me'
var labelids = Gmail.Users.Labels.list('me')

// Search through the existing labels for ${labelName}
// this operation is still needed to get the label ID 
var labelid = false
labelids.labels.forEach(function(a) {
    if (a.name === labelName) {
        labelid = a
    }
})
Logger.log(labelid);
Logger.log(labelid.id);
// Create a new filter object (really just POD)
var filter = Gmail.newFilter()

// Make the filter activate when the to address is ${toAddress}
filter.criteria = Gmail.newFilterCriteria()
filter.criteria.to = toAddress

// Make the filter remove the label id of ${"INBOX"}
filter.action = Gmail.newFilterAction()
filter.action.removeLabelIds = ["INBOX"];
// Make the filter apply the label id of ${labelName} 
filter.action.addLabelIds = [labelid.id];

// Add the filter to the user's ('me') settings
Gmail.Users.Settings.Filters.create(filter, 'me')
}
</code></pre>

<p>}</p>

<p>Thanks, Ender</p>