I've reviewed the issue you've encountered, and here are some key points to help resolve it clearly and effectively:
Why are you seeing errors?
The execution errors you're experiencing (40% failure rate) typically occur for these reasons in Gmail scripts within Google Apps Script:
Missing or expired authorization (incorrect permissions).
Exceeding execution quota limits.
Incorrect parameters or search criteria in GmailApp
.
Your logic is mostly correct, but some critical corrections are needed:
var threads = GmailApp.search('is:inbox after:' + timeFrom);
The after:
parameter in GmailApp searches expects a date formatted as YYYY/MM/DD
, not a timestamp in seconds.
You should instead use:
var dateFrom = new Date(date.getTime() - (1000 * 60 * interval));
var formattedDate = Utilities.formatDate(dateFrom, "GMT", "yyyy/MM/dd");
var threads = GmailApp.search('is:inbox is:unread after:' + formattedDate);
2. Marking as read and important
This step is optional, but fine if you wish to keep it.
Here is the corrected script incorporating these changes:
function autoReply() {
var interval = 5; // Script execution interval in minutes
var date = new Date();
var day = date.getDay();
var hour = date.getHours();
if ([6, 0].indexOf(day) > -1 || (day == 1 && hour < 8) || (day == 5 && hour >= 17)) {
var dateFrom = new Date(date.getTime() - (1000 * 60 * interval));
var formattedDate = Utilities.formatDate(dateFrom, "GMT", "yyyy/MM/dd");
var threads = GmailApp.search('is:inbox is:unread after:' + formattedDate);
for (var i = 0; i < threads.length; i++) {
threads[i].reply("Our offices are closed for the weekend. If this is an urgent request (i.e., fallen tree on structure or impending traffic), please forward your message to [email protected] and our team will get back to you as soon as possible. If the request is not urgent, we will respond when our business reopens. Thank you!");
threads[i].markRead();
threads[i].markImportant();
}
}
}