Created
May 12, 2017 07:55
-
-
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
This file contains hidden or 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
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