So today I wanted to download my entire history of municipality statements and use some AI tools to build some analytical dashboards for insights. The first thing to automate was downloading attachments from GMail. Instead of manually downloading one-by-one, or manually using a filter rule on GMail, I wanted to test ChatGPT and Gemini to see if it could provide a Google Workspace Appscript to meet my needs.
So Gemini was OKAY - I'm using Gemini Advanced 1.5 Pro with Advanced research. Interesting, it took the prompt "Help me with a google script or query in gmail that I can use for finding all emails from a specified email sender, downloading the attachments from each email, to a specified folder". Gemini then went along with doing the research, then provided the code. Unfortunately, the code didn't work, even after a few tries - maybe it was a Google drive sync issue - but Gemini was stuck on maintaining its response on the nature of the exception ("either an auth issue" or "folder does not exist").
So I resorted to ChatGPT 4-Turbo, created a project with these instructions, and used the same prompt and included the original code from Gemini "Act as an expert software engineer to build a google appscript for downloading attachments for all emails from a specific sender. The script needs to work flawlessly from within the Google Apps Script console.
I wrote the following code - but the script does not work. I'm getting an Exception: Unexpected error while getting the method or property getFolderById on object DriveApp"
Guess what? ChatGPT nailed it on first try, even added enough logging for tracing! Here's the code. Read the report from Gemini, as this is an example of how content can be generated by AI, and it's only going to get better.
function downloadAttachmentsFromSender() {
// Replace with the email address of the sender.
var senderEmail = '[enter email here]';
// Replace with the ID or intended name of the folder in Google Drive.
var folderName = '[name of folder]'; // Base name for the folder
// Variable to store the target folder
var folder;
try {
// Verify Drive API is working
DriveApp.getFolders();
} catch (e) {
Logger.log("Please authorize the script to access your Drive.");
return; // Exit if Drive access is not authorized
}
// Check if the folder exists
var folders = DriveApp.getFoldersByName(folderName);
if (folders.hasNext()) {
folder = folders.next();
Logger.log("Using existing folder: " + folder.getName());
} else {
// Create a new folder with the current date appended
var dateSuffix = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd');
var newFolderName = folderName + "_" + dateSuffix;
folder = DriveApp.createFolder(newFolderName);
Logger.log("Created new folder: " + newFolderName);
}
// Search for emails from the specified sender.
var threads;
try {
threads = GmailApp.search('from:' + senderEmail);
Logger.log("Found " + threads.length + " threads from sender: " + senderEmail);
} catch (e) {
Logger.log("Error searching for emails: " + e.message);
return; // Exit if Gmail search fails
}
// Iterate through each email thread.
threads.forEach(function (thread) {
var messages = thread.getMessages();
messages.forEach(function (message) {
var attachments = message.getAttachments();
attachments.forEach(function (attachment) {
// Extract the original file extension
var fileName = attachment.getName();
var fileExtension = fileName.substring(fileName.lastIndexOf("."));
// Create the new filename with timestamp and original extension
var newFileName = fileName.substring(0, fileName.lastIndexOf(".")) +
"_" + new Date().getTime() + fileExtension;
try {
folder.createFile(attachment).setName(newFileName);
Logger.log("Saved attachment: " + newFileName);
} catch (e) {
Logger.log("Error saving attachment: " + e.message);
}
});
});
});
Logger.log("Process complete.");
}
Anyway, I now have a repeatable way to extract attachments from emails in GMail, and now you can too.