Aware that there’s been a few questions about this over the years, but Google’s documentation has changed, and methods etc. have changed.
The doc page appears to reference both Gmail.users.messages.delete and Gmail.users.Threads.delete, and I’m not sure how to tell which is the current one, beyond neither of them working when I change the script.
https://developers.google.com/gmail/api/reference/rest/v1/users.threads/delete
Aware that also, the recommendation is that trash is used. The Gscript that I’ve got to move all messages with a certain filter move to trash fine but I want that same script to dump them from trash too and I’d prefer, in this case, to bypass it entirely.
Have added the Gmail API service into the project, and also enabled the GmailAPI in my account.
So initially, I thought I’d trash it, and then remove from trash, thus:
function DeleteMail() {
var threads = GmailApp.search('subject:test');
for (var i = 0; i < threads.length; i++) {
threads[i].moveToTrash();
}
var threads2= GmailApp.search('in:trash subject:test')
for (var p = 0; p < threads2.length; p++) {
var thisid=threads2[p].getId();
Gmail.users.messages.delete('me', threads2[p].thisid);
}
}
I get the error: TypeError: Cannot read properties of undefined (reading ‘delete’)
So I altered the script so that it would bypass the trashing bit and just straight up remove it
function DeleteMail() {
var threads = GmailApp.search('subject:test');
for (var i = 0; i < threads.length; i++) {
var thisId = threads[i].getId();
Gmail.users.messages.delete('me', threads[i].thisId);
}
and get the error: TypeError: Cannot read properties of undefined (reading ‘messages’)
Can anyone point me where I’m going wrong here please?
2
Answers
If I understood your question correctly you want to delete certain messages directly without them having to go to trash.
Try:
Modifications:
In your current code, in the subject, you have to enclose the actual subject in double quote (").
Also changed the
Gmail.users.messages.delete('me', threads[i].thisId);
toGmail.Users.Messages.remove('me', thisId);
.Set up with time driven trigger.
Delete email from inbox
Adjust subject target as required