My goal is to make sure that all incoming Gmail messages from [email protected] are immediately permanently deleted.
I have created a filter that gives new messages from this address the label "deleteforever". Next, I have made a Google script that completely deletes all messages with the label "deleteforever". To be certain that no other messages are deleted, I check an extra time whether the messages really are from [email protected]. In this way, when a thread contains messages from [email protected] and messages from another address, only the messages from [email protected] should be deleted.
I plan to run it every minute. I have 3 questions:
- Does this algorithm always completely delete all new messages from [email protected]?
- Does this algorithm never delete a message from another sender?
- Will this not cost too much runtime, assuming that [email protected] does not send many emails? (I saw that there is a limit of 1 hour per day.)
function extractEmailAddress(header) {
return header.match(/[^@<\s] @[^@\s>] /)[0];
}
function deleteForever() {
var threads, msgs, label1, label2, sender,message,messageId;
label1="[email protected]";
label2="[email protected]";
threads= GmailApp.getUserLabelByName("deleteforever").getThreads();
msgs = GmailApp.getMessagesForThreads(threads);
for (var i = 0 ; i < msgs.length; i ) {
for (var j = 0; j < msgs[i].length; j ) {
message=msgs[i][j];
sender = extractEmailAddress(message.getFrom());
if (sender==label1 || sender==label2){
messageId=message.getId();
Gmail.Users.Messages.remove("me", messageId);
}
}
}
}
UPDATE
Inspired by the comment of @TheMaster, the following strategy solves the potential runtime problem:
-modify the filter in Gmail so that messages from [email protected] skip the inbox.
-hide the "deleteforever" folder
Now the script can be run every 5 minutes or with even lower frequency.
CodePudding user response:
Since you are open to muting the notifications as suggested by TheMaster and running the script/function on a less frequent basis, I suggest you improve it further by using Gmail API
, specifically batchDelete
to improve the performance.
Script:
function deleteForever() {
label_name = 'deleteforever';
sender1 = '[email protected]';
sender2 = '[email protected]';
// get labelId of label_name
var labelId = Gmail.Users.Labels.list("me").labels.filter(label => label.name == label_name)[0].id;
// filter messages where it has labelId and from either sender1 or sender2
var messages = Gmail.Users.Messages.list("me", {
"labelIds": labelId,
"q": `{from: ${sender1} from: ${sender2}}`
}).messages;
// if messages is not empty
if(messages){
// get ids of the messages
var ids = messages.map(message => message.id);
// bulk delete the messages
Gmail.Users.Messages.batchDelete({"ids": ids}, "me");
}
}
This will delete the accumulated message IDs by bulk where it meets the conditions:
- Sender is either
sender1
orsender2
- Has label
label_name
.
Note:
- You will not need
extractEmailAddress
anymore.