Skip to content

Instantly share code, notes, and snippets.

@markflorkowski
Last active September 26, 2024 18:17
Show Gist options
  • Save markflorkowski/505d2a93376e2d3ad9df8c77dc4f1ac3 to your computer and use it in GitHub Desktop.
Save markflorkowski/505d2a93376e2d3ad9df8c77dc4f1ac3 to your computer and use it in GitHub Desktop.
Gmail - Label emails based on sender domain
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