I’m working with Google Apps Script to process my Gmail messages. I need to find emails with specific labels that aren’t starred yet, then grab their attachments and save them to Google Drive.
The script I wrote does what I want, but it keeps hitting timeout limits after handling around 25 image files (I’m using a free Gmail account). Here’s the main part of my code:
// Iterate through each thread's messages
for (var x = 0; x < emailThreads.length; x++) {
for (var y = 0; y < emailThreads[x].length; y++) {
var activeEmail = emailThreads[x][y];
if (!activeEmail.isStarred()) {
var attachmentList = activeEmail.getAttachments();
var emailTitle = activeEmail.getSubject();
if (attachmentList.length == 0) {
var textFile = targetFolder.createFile(emailTitle, 'No attachments found', MimeType.PLAIN_TEXT);
} else {
for (var z = 0; z < attachmentList.length; z++) {
var savedFile = targetFolder.createFile(attachmentList[z].copyBlob().getAs('image/jpeg').setName(emailTitle));
}
}
activeEmail.star();
}
}
}
Any suggestions for making this more efficient would be really helpful!
Running into execution limits myself when dealing with email processing. The nested loop structure you have there is eating up execution time fast. What worked for me was breaking the work into chunks and using PropertiesService to track progress between runs. Set up a time-based trigger to resume where you left off instead of trying to process everything in one go. Also noticed you’re calling getAttachments() on every email even if it might not have any - this API call is expensive. Consider using getAttachments().length check earlier in your logic flow. One more thing that helped reduce my timeouts was avoiding the copyBlob().getAs() chain when possible and just working with the original blob format. The file conversion is resource intensive and might not always be necessary depending on your use case.
timeout issues r brutal with apps script! try processing emails in smaller batches and use utilities.sleep() between heavy operations. also consider using lock service to prevent multiple executions overlapping - that helped me avoid similar headaches
Your code has some performance bottlenecks that are causing the timeouts. The main issue is creating files one by one inside nested loops without any optimization. I faced similar problems when processing large email batches and found that caching Drive folder references and reducing API calls made a huge difference. Instead of calling targetFolder.createFile() repeatedly, collect all the blobs first and then batch create them. Also, you’re converting everything to JPEG regardless of original format which adds unnecessary processing time. Consider checking the actual MIME type first and only convert when needed. Another thing that worked for me was implementing a simple counter to track processed items and exit before hitting the 6-minute execution limit, then resuming with a time-based trigger.