Skip to content

Instantly share code, notes, and snippets.

@alexkuang0
Created December 29, 2020 14:33
Show Gist options
  • Save alexkuang0/2ee802041f1d807dd94f0b5401c473db to your computer and use it in GitHub Desktop.
Save alexkuang0/2ee802041f1d807dd94f0b5401c473db to your computer and use it in GitHub Desktop.
Apps Script for Gmail - Label mails by address
const PARENT_LABEL = 'example.com'
const LABEL_SEPARATOR = '-'
const LEVEL_SEPARATOR = '.'
const getLabelOrCreate = (labelName) => GmailApp.getUserLabelByName(labelName) || GmailApp.createLabel(labelName)
function labelMailsByAddress() {
const allTargetThreads = GmailApp.search(`label:${PARENT_LABEL} `)
allTargetThreads.forEach(thread => {
if (thread.isUnread()) {
Logger.log(`SUBJECT: ${thread.getFirstMessageSubject()}`)
const toAddress = thread.getMessages()[0].getTo()
const localPart = /(.*)@/g.exec(toAddress)[1]
localPart.split(LABEL_SEPARATOR).forEach(labelName => {
const allLabelParts = labelName.split(LEVEL_SEPARATOR)
const currentLabelParts = [PARENT_LABEL]
allLabelParts.forEach(labelPart => {
let currentLength = currentLabelParts.push(labelPart)
let fullLabelName = currentLabelParts.join('/')
let currentLabel = getLabelOrCreate(fullLabelName)
if (currentLength === allLabelParts.length + 1) {
thread.addLabel(currentLabel)
Logger.log(`ADDED LABEL: ${fullLabelName}`)
}
})
})
}
})
}
@alexkuang0
Copy link
Author

@hellodword 是的,Gmail 地址还可以可以用 + 号扩展(发给 [email protected] 的邮件会发送到 [email protected]),有时间写个给用在这种情况下的。不过不知道你说的域名邮箱的问题大概有什么,我目前只打算用这个收邮件,用 ImprovMX 转发,都有免费额度,感觉体验还行暂时没有遇到什么问题。

@hellodword
Copy link

@hellodword 是的,Gmail 地址还可以可以用 + 号扩展(发给 [email protected] 的邮件会发送到 [email protected]),有时间写个给用在这种情况下的。不过不知道你说的域名邮箱的问题大概有什么,我目前只打算用这个收邮件,用 ImprovMX 转发,都有免费额度,感觉体验还行暂时没有遇到什么问题。

比如注册时的接受度...总会遇到一些只接受主流邮箱后缀却又不得不注册的场景

@alexkuang0
Copy link
Author

@hellodword 是的,Gmail 地址还可以可以用 + 号扩展(发给 [email protected] 的邮件会发送到 [email protected]),有时间写个给用在这种情况下的。不过不知道你说的域名邮箱的问题大概有什么,我目前只打算用这个收邮件,用 ImprovMX 转发,都有免费额度,感觉体验还行暂时没有遇到什么问题。

比如注册时的接受度...总会遇到一些只接受主流邮箱后缀却又不得不注册的场景

确实,不过 Gmail 的加号也有这个问题

@alexkuang0
Copy link
Author

alexkuang0 commented Aug 28, 2023

This gist has some bugs and has been discontinued. Following updates will be in the repo here: https://github.com/alexkuang0/mail-organizer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment