Skip to content

Instantly share code, notes, and snippets.

@nodaguti
Created May 12, 2017 07:55
Show Gist options
  • Save nodaguti/50a16a2739759f0d40fe2ef18a269f73 to your computer and use it in GitHub Desktop.
Save nodaguti/50a16a2739759f0d40fe2ef18a269f73 to your computer and use it in GitHub Desktop.
Post new emails that have a certain label to a specified Slack channel
var slack = {
postUrl: 'https://slack.com/api/chat.postMessage',
token: 'xoxp-0000000000000000000000000000',
userName: 'Postman',
};
var labelToChannel = {
'slack-finance': '#finance',
'slack-financial-news': '#financial-news',
'slack-cryptocurrency': '#cryptocurrency',
};
var postMessage = function(channelId, text) {
UrlFetchApp.fetch(slack.postUrl, {
method: 'post',
payload: {
token: slack.token,
channel: channelId,
username: slack.userName,
text: text,
},
});
}
function findAndForward(label, channel) {
var threads = GmailApp.search('is:unread label:' + label);
threads.forEach(function (thread) {
var message = thread.getMessages()[0];
var subject = message.getSubject();
var from = message.getFrom();
var body = message.getPlainBody();
if (~from.indexOf('<')){
from = from.match(/<(.+?@.+?)>/)[1];
}
postMessage(channel, [
'*' + subject + ' (' + from + ')* ',
body.substring(0, 4000),
].join('\n'));
thread.markRead();
});
}
function myFunction() {
Object.keys(labelToChannel)
.forEach(function(label) {
findAndForward(label, labelToChannel[label]);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment