Skip to content

Instantly share code, notes, and snippets.

@rod-dot-codes
Created April 21, 2022 20:40
Show Gist options
  • Save rod-dot-codes/96e91318fcb7b2d189c4fdec6a7b64ff to your computer and use it in GitHub Desktop.
Save rod-dot-codes/96e91318fcb7b2d189c4fdec6a7b64ff to your computer and use it in GitHub Desktop.
This creates Labels on a schedule (when configured) for each new catch-all domain. For example, if you have flights@joebloggs.com - it'll create a new label called "📬 flights"
// Configure this trigger to run often
// (*how* often depends on the desired response time *and* how willing you are to risk hitting Google Apps Script’s rate limits;
// 10 minutes is good enough for me generally)
var LABEL_DICT = {}
var EMAIL_WORKSPACE_DOMAIN = "" // do not include the @ sign, so for XYZ@joebloggs.com, put joebloggs.com
function getUserLabels() {
GmailApp.getUserLabels().map((value) => {
LABEL_DICT[value.getName().toString()] = value;
return { "label": value, "name": value.getName() };
});
}
function getLabelByName(name) {
return LABEL_DICT.hasOwnProperty(name) ? LABEL_DICT[name] : undefined;
};
function createLabelIfNotExists(name) {
var newLabel = null;
var label = getLabelByName(name);
if (!label) {
newLabel = GmailApp.createLabel(name.toString());
LABEL_DICT[name.toString()] = newLabel;
label = newLabel;
}
return label;
};
function getLabelByEmailType(emailAddress) {
if (!emailAddress) {
return;
}
let emailLower = emailAddress.toString().toLowerCase();
if (emailLower.toString().endsWith(EMAIL_WORKSPACE_DOMAIN)) {
let futureLabel = emailLower.toString().split("@");
return createLabelIfNotExists("📬 " + futureLabel[0]);
};
};
function triggerScriptForEmail() {
getUserLabels();
let indicatorLabelString = "🆕";
var LABEL_TO_REMOVE = LABEL_DICT[indicatorLabelString];
var GET_THREADS_AT_TIME = 5;
var threads = new Array();
while (Array.isArray(threads)) {
Logger.log(`Calling getUserLabelByName = ${indicatorLabelString}`);
threads = GmailApp.getUserLabelByName(indicatorLabelString).getThreads(0, GET_THREADS_AT_TIME);
Logger.log(`Thread length == ${threads.length}`);
if (threads.length == 0) {
Logger.log('All gone');
return;
}
threads.forEach((thread) => {
var messages = GmailApp.getMessagesForThread(thread);
Logger.log(`${messages}`);
var emailAddresses = messages.map((msg) => (msg.getTo ? [msg.getTo()] : [])).map((value) => value.toString().match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/gi));
[...new Set(emailAddresses)].forEach((recipient) => {
Logger.log(`Checking email address ${recipient}`);
var labelToAttach = getLabelByEmailType(recipient);
if (labelToAttach) {
Logger.log(`Attaching label ${labelToAttach.getName()}`);
labelToAttach.addToThread(thread);
}
});
Logger.log(`Removing indicator label`);
LABEL_TO_REMOVE.removeFromThread(thread);
return null;
})
}
}
function doGet(e) {
triggerScriptForEmail();
return `OK`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment