Skip to content

Instantly share code, notes, and snippets.

@jmpinit
Created December 1, 2022 17:38
Show Gist options
  • Save jmpinit/09f306a6ea6363bc14c602accd954b81 to your computer and use it in GitHub Desktop.
Save jmpinit/09f306a6ea6363bc14c602accd954b81 to your computer and use it in GitHub Desktop.
App Script to add an "Events" label to GMail messages sent from Google Calendar.

Usage

  1. Create an "Events" label in GMail
  2. Go to script.google.com and create a new project.
  3. Replace the contents of Code.gs with those from this gist
  4. Create a trigger. Select processInbox as the function to run. Select "Time-driven" as the event source. Select "Hour timer" as the type of time based trigger. Select "Every hour" as the hour interval.
function threadHasLabel(thread, labelName) {
var existingLabels = thread.getLabels();
for (var i = 0; i < existingLabels.length; i++) {
if (existingLabels[i].getName() === labelName) {
return true;
}
}
return false;
}
// Adds a label to the thread a message is a part of
// if it is not already present
function addLabel(message, labelName) {
var thread = message.getThread();
// Only add the label if it is not already on the thread
if (threadHasLabel(thread, labelName)) {
return;
}
var label = GmailApp.getUserLabelByName(labelName);
if (label === undefined) {
Logger.log('The label "' + labelName + '" does not exist');
return;
}
thread.addLabel(label);
}
function processMessage(message) {
var body = message.getRawContent();
// Sender: Google Calendar <[email protected]>
if (body.indexOf("Sender: Google Calendar") > -1) {
addLabel(message, 'Events');
}
}
function processInbox() {
// Process all recent threads in the Inbox
var threads = GmailApp.search('in:inbox');
Logger.log('Processing ' + threads.length + ' emails.');
for (var i = 0; i < threads.length; i++) {
// Get all messages in a given thread
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var message = messages[j];
processMessage(message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment