I am researching a google apps script to delete an e-mail based on time. I have set up a daily agenda but they fill my inbox after some time.
I was thinking of deleting those e-mails automatically every next day, since I get updates every day after 5 AM perhaps setting a script to delete them the next day before 5AM should work but I haven't found a solution for this.
function deleteAllEmailsNotWhiteListed() {
const acct = getGlobal('abrevEmail');
var idA = [];
GmailApp.getTrashThreads().forEach(t => { Gmail.Users.Threads.remove("me", t.getId()) });
for (let k = 0; k < 2; k++) {
switch (k) {
case 0:
var threads = GmailApp.getInboxThreads();
break;
case 1:
var threads = GmailApp.getSpamThreads();
break;
}
if (threads) {
for (let i = 0; i < threads.length; i++) {
const messages = threads[i].getMessages();
if (messages) {
for (let j = 0; j < messages.length; j++) {
let msg = messages[j];
let id = msg.getId();
let sub = msg.getSubject().replace(/[^\s\w"!,?']/g, '');
let from = msg.getFrom();
let to = msg.getTo();
let body = msg.getBody();
let m = { id: id, from: from, to: to, subject: sub, account: acct }
if (!isWhiteListed(m)) {
idA.push(id);
}
}
}
}
}
}
if (idA.length > 0) {
var request = { "ids": idA };
Gmail.Users.Messages.batchDelete(request, "me");
}
}
function isWhiteListed(msg) {
const ss = SpreadsheetApp.openById(getGlobal('ssid'));
const sh = ss.getSheetByName(getGlobal('wlid'));
const wlog = ss.getSheetByName(getGlobal('wlog'));
const sr = 2;
const rg = sh.getRange(sr, 1, sh.getLastRow() - sr + 1, 1);
const wl = rg.getDisplayValues().flat().map(e => e.toLowerCase());
if (wl.length == 0) throw ('Error: WhiteList has no content');
let obj = decomposeEmailsWithTitle({ raw: msg.from, email: '', title: '' });
let status = wl.indexOf(obj.email.toLowerCase()) > -1;
wlog.appendRow([Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "E MMM dd, yyyy HH:mm:ss"), obj.email, msg.to, msg.subject, status, msg.account]);
return status;
}
function deleteAllEmailsNotWhiteListed() {
const dt = new Date();
const ydtv = new Date(dt.getFullYear(),dt.getMonth(), dt.getDate()-1).valueOf();
const acct = getGlobal('abrevEmail');
var idA = [];
GmailApp.getTrashThreads().forEach(t => { Gmail.Users.Threads.remove("me", t.getId()) });
for (let k = 0; k < 2; k++) {
switch (k) {
case 0:
var threads = GmailApp.getInboxThreads();
break;
case 1:
var threads = GmailApp.getSpamThreads();
break;
}
if (threads) {
for (let i = 0; i < threads.length; i++) {
const messages = threads[i].getMessages();
if (messages) {
for (let j = 0; j < messages.length; j++) {
let msg = messages[j];
let id = msg.getId();
let d = msg.getDate();
let dtv = new Date(d.getFullYear(),d.getMonth(),d.getDate()).valueOf()
if (dtv <= ydtv) {//modifed
idA.push(id);
}
}
}
}
}
}
if (idA.length > 0) {
var request = { "ids": idA };
Gmail.Users.Messages.batchDelete(request, "me");
}
}