Create a native filter in Gmail using Google Apps Script

坚强是说给别人听的谎言 提交于 2019-12-03 08:40:12

The functionality seems to exist, but requires enabling the full Gmail API.

For your Apps script, follow the directions at https://developers.google.com/apps-script/guides/services/advanced to enable Advanced Google Services. When I first tried using the Gmail.Users.Settings.Filters.list('me') call I got an authorization error which gave me a link to enable the Gmail API in the Developer Console which just amounted to flipping a switch.

Once you have this enabled, you can write a script to make filters, like

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

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

  // Search through the existing labels for ${labelName}
  var label = null
  labels.labels.forEach(function (l) {
    if (l.name === labelName) {
      label = l
    }
  })

  // If the label doesn't exist, return
  if (label === null) return

  // 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 apply the label id of ${labelName}
  filter.action = Gmail.newFilterAction()
  filter.action.addLabelIds = [label.id]

  // Add the filter to the user's ('me') settings
  Gmail.Users.Settings.Filters.create(filter, 'me')

}


function main () {
  createToFilter('youruser+foo@gmail.com', 'Aliases/foo')
}

I wasn't able to figure out how to create a filter that retroactively labels messages automatically since Google doesn't seem to expose that in their API.

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