Last active
September 26, 2024 18:17
-
-
Save markflorkowski/505d2a93376e2d3ad9df8c77dc4f1ac3 to your computer and use it in GitHub Desktop.
Gmail - Label emails based on sender domain
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
function main() { | |
const labelMap = new Map(); | |
Gmail.Users.Labels.list("me").labels.forEach((label) => { | |
if (label.type == "user") labelMap[label.name] = label.id; | |
}); | |
if (messageList = Gmail.Users.Messages.list("me", { | |
q: "in:Inbox has:nouserlabels", | |
}).messages) { | |
messageList.forEach((msg) => { | |
const newLabel = | |
"Sender/" + | |
GmailApp.getMessageById(msg.id) | |
.getFrom() | |
.match(/\s*"?([^"]*)"?\s+<(.+)>/)[2] | |
.replace(/.*@/, "") | |
.replace(/\..*$/, ""); | |
if (newLabel in labelMap) { | |
// label email | |
Gmail.Users.Messages.modify({ | |
addLabelIds: [labelMap[newLabel]] | |
}, | |
"me", | |
msg.id | |
); | |
} else { | |
// create label, add to map | |
labelMap[newLabel] = Gmail.Users.Labels.create({ | |
name: newLabel | |
}, | |
"me" | |
).id; | |
// label email | |
Gmail.Users.Messages.modify({ | |
addLabelIds: [labelMap[newLabel]] | |
}, | |
"me", | |
msg.id | |
); | |
} | |
}); | |
} else { | |
console.log("no unlabelled mail") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment