Skip to content

Instantly share code, notes, and snippets.

@k-ogasawara
Last active July 14, 2021 07:45
Show Gist options
  • Save k-ogasawara/abcf4373ccead9c185771854c33ee5b1 to your computer and use it in GitHub Desktop.
Save k-ogasawara/abcf4373ccead9c185771854c33ee5b1 to your computer and use it in GitHub Desktop.
Gmail: post to slack automatically

Gmail: post to slack automatically

Automatically post emails that match the specified label to Slack.

Ref: https://gist.github.com/jamesramsay/9298cf3f4ac584a3dc05

Get started

  • Create a new Google Apps Script at https://script.google.com
  • Overwrite the placeholder with the javascript below
  • Update the following constants:
    • LABELS_TO_POST: The name of the Gmail Label that is to be posted
    • WEBHOOK_URL: Slack incoming webhook url
  • Save the script, then run:
    • Initialize
    • Install

If you ever want to remove the script, run Uninstall to remove any left over triggers.

// Your webhook url
var WEBHOOK_URL = '';
// The name of the Gmail Label that is to be posted to Slack
var LABELS_TO_POST = [
'ToSlack'
];
var TRIGGER_NAME = 'main';
/*
IMPLEMENTATION
*/
function Intialize() {
return;
}
function Install() {
ScriptApp.newTrigger(TRIGGER_NAME)
.timeBased().everyMinutes(5).create();
}
function Uninstall() {
var triggers = ScriptApp.getProjectTriggers();
for (var i=0; i<triggers.length; i++) {
ScriptApp.deleteTrigger(triggers[i]);
}
}
function generateText(message) {
var text = '';
text += message.getSubject() + '\n';
text += message.getFrom() + '\n\n';
text += message.getPlainBody().slice(0,512) + '\n\n';
text += message.getDate() + '\n';
return text;
}
function postToSlack(message) {
var text = generateText(message);
if (!text) return;
var payload = JSON.stringify({ text: text });
var options = {
method: 'POST',
contentType: 'application/json',
payload: payload
};
UrlFetchApp.fetch(WEBHOOK_URL, options);
}
function main() {
var search = 'is:unread newer_than:1d (label:' + LABELS_TO_POST.join(' OR label:') + ')';
Logger.log('SEARCH: ' + search);
var threads = GmailApp.search(search, 0, 100);
Logger.log('Processing ' + threads.length + ' threads...');
var messages = GmailApp.getMessagesForThreads(threads);
for (var i = messages.length - 1; i >= 0; i--) {
for (var j = 0; j < messages[i].length; j++) {
var message = messages[i][j];
if (message.isUnread()) {
postToSlack(message);
message.markRead();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment