Created
December 29, 2020 14:33
-
-
Save alexkuang0/2ee802041f1d807dd94f0b5401c473db to your computer and use it in GitHub Desktop.
Apps Script for Gmail - Label mails by address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`) | |
} | |
}) | |
}) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This gist has some bugs and has been discontinued. Following updates will be in the repo here: https://github.com/alexkuang0/mail-organizer