Last active
June 1, 2021 13:00
-
-
Save matsuyoro/c53d82017b2763633e5b to your computer and use it in GitHub Desktop.
GAS(google app script)で指定ラベルのGmailをslackに通知
This file contains 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
// slackのwebhook URL | |
var postUrl = "https://hooks.slack.com/services/xxxxxxxxxxx"; | |
// 通知したいslackのチャネル(部屋) | |
var postChannel = "#n_app_review"; | |
// 抽出元のGmailのラベル | |
var checkLabel = "TO_ME"; | |
function myFunction() { | |
// 未読の指定ラベル を検索 | |
var threads = GmailApp.search('is:unread label:' + checkLabel); | |
var count = threads.length; | |
Logger.log("対象件数:" + threads.length); | |
for(var i = 0; i < count; i++) { | |
var lastDate = threads[i].getLastMessageDate(); | |
var datetime = lastDate.getFullYear() + "/" + (lastDate.getMonth() + 1) + "/" + lastDate.getDate() | |
+ " " + lastDate.getHours() + ":" + lastDate.getMinutes() + ":" + lastDate.getSeconds(); | |
var messages = threads[i].getMessages(); | |
//同じ件名で、ネストされたメッセージを個別に | |
if(messages.length > 0){ | |
for(var j = 0; j < messages.length; j++){ | |
// 簡易的に、brタグを改行に | |
var brTagStripped = messages[j].getBody().replace(/(<br>|<br \/>)/gi, '\n'); | |
// 簡易的に、HTMLメールのタグを解除 | |
var stripped = brTagStripped.replace(/(<([^>]+)>)/ig,""); | |
var postMessage = " 件名: ``` " + threads[i].getFirstMessageSubject() + " ``` " + " \n本文 ``` " + stripped + " ``` "; | |
Logger.log(datetime + postMessage); | |
//slackに通知 | |
sendHttpPost(postMessage); | |
// 対象のメールを1通を既読に。 | |
messages[j].markRead(); | |
} | |
} | |
// 対象のメールを既読にする | |
// NOTE: ネストされているものはすべて既読になります。 | |
// threads[i].markRead(); | |
} | |
} | |
function sendHttpPost(message, username) | |
{ | |
var jsonData = | |
{ | |
"channel" : postChannel, | |
"username" : username, | |
"text" : message | |
}; | |
var payload = JSON.stringify(jsonData); | |
var options = | |
{ | |
"method" : "post", | |
"contentType" : "application/json", | |
"payload" : payload | |
}; | |
UrlFetchApp.fetch(postUrl, options); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
関連したメールが1つにまとまった場合に、個別に本文等が取得できない点を改善しました。
下記のようなケース
