Last active
March 12, 2020 13:43
-
-
Save sussan0416/4e25110921e4f4c6884e459eafd81542 to your computer and use it in GitHub Desktop.
A Google Apps Script for trashing aged mails.
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
// Set this function as Trigger | |
function myFunction() { | |
const queries = [ | |
"from: to-be-trashed@hoge.fuga.com", | |
"from: high-frequently-ads@hoge.fuga.com" | |
]; | |
trashMails(queries); | |
} | |
function getDateBefore7Days() { | |
var date = new Date(); | |
date.setDate(date.getDate() - 7); | |
return date; | |
} | |
function trashMails(queries) { | |
const fromDate = getDateBefore7Days(); | |
const year = fromDate.getFullYear(); | |
const month = fromDate.getMonth(); | |
const date = fromDate.getDate(); | |
const fromDateString = year + "/" + (month + 1) + "/" + date; | |
var isFirstDelete = true; | |
queries.forEach((query) => { | |
const searchQuery = query + " is:all NOT is:trash before:" + fromDateString; | |
const threads = GmailApp.search(searchQuery); | |
Logger.log(searchQuery); | |
if (threads.length == 0) { | |
Logger.log("No results."); | |
return | |
} else { | |
Logger.log(threads.length + " results."); | |
} | |
var titles = ""; | |
if (isFirstDelete) { | |
titles = "*DELETE MAILS BEFORE " + fromDateString + "*\n"; | |
isFirstDelete = false; | |
} | |
titles += "*" + query + "*\n"; | |
threads.forEach((thread) => { | |
titles += "- " + thread.getFirstMessageSubject() + "\n" | |
}) | |
// POST to Slack | |
const postUrl = "https://hooks.slack.com/services/***hogehogehogehoge***"; | |
const jsonData = { | |
"username": "Mail Trasher", | |
"icon_emoji": ":wastebasket:", | |
"text": titles | |
}; | |
const payload = JSON.stringify(jsonData); | |
var options = { | |
"method" : "post", | |
"contentType" : "application/json", | |
"payload" : payload | |
}; | |
var response = UrlFetchApp.fetch(postUrl, options); | |
// move to Trash if responseCode is 200 | |
if (response.getResponseCode() == 200) { | |
threads.forEach((thread) => { | |
thread.moveToTrash(); | |
}); | |
} else { | |
Logger.log("Slack unexpected response code: " + response.getResponseCode()); | |
Logger.log(response.getAllHeaders()); | |
Logger.log(response.getContentText()); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment