Skip to content

Instantly share code, notes, and snippets.

@pallocchi
Last active June 13, 2024 23:08
Show Gist options
  • Save pallocchi/9c3facffcf8806670d3dcaa254118917 to your computer and use it in GitHub Desktop.
Save pallocchi/9c3facffcf8806670d3dcaa254118917 to your computer and use it in GitHub Desktop.
Automatically Save Email Attachments to Google Drive Using Google Apps Script
function saveNewAttachmentsToDrive() {
var folderId = "PUT_YOUR_FOLDER_ID_HERE"; // Replace with the ID of the destination folder in Google Drive
var searchQuery = "to:your-email@example.com has:attachment"; // Replace with the search query to find emails with attachments
var lastExecutionTime = getLastExecutionDate();
var threads = GmailApp.search(searchQuery + " after:" + lastExecutionTime);
var driveFolder = DriveApp.getFolderById(folderId);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var message = messages[j];
var attachments = message.getAttachments();
for (var k = 0; k < attachments.length; k++) {
var attachment = attachments[k];
var attachmentBlob = attachment.copyBlob();
var fileName = attachment.getName();
driveFolder.createFile(attachmentBlob).setName(fileName);
}
}
}
updateLastExecutionDate();
}
function getLastExecutionDate() {
var properties = PropertiesService.getUserProperties();
return properties.getProperty("lastExecutionDate") || "2023-09-01";
}
function resetLastExecutionDate() {
PropertiesService.getUserProperties().deleteProperty("lastExecutionDate");
}
function updateLastExecutionDate() {
var now = new Date();
var dateString = now.toISOString().split("T")[0];
var properties = PropertiesService.getUserProperties();
properties.setProperty("lastExecutionDate", dateString);
}
@pallocchi
Copy link
Author

You could try changing this:

var dateString = now.toISOString().split("T")[0];

to this:

var dateString = now.toISOString();

So it also considers time, but I'm not sure if GmailApp.search would work with the full ISO string.

@MontageIT
Copy link

MontageIT commented Jun 13, 2024

Thank you for the reply, as you noted, yes it seem to not want to run once the full date and time are there. Perhaps it is a formatting issue. I found this here
https://stackoverflow.com/questions/12261785/searching-emails-in-gmail-based-on-time

var month = new Date().getMonth();
var date = new Date().getDate();
var year = new Date().getFullYear();
var time1 = new Date(year, month, date, 0, 0, 0).getTime();
var time2 = time1 - 86400000;
var query = "newer:" + time2/1000 + " older:" + time1/1000 + " in:inbox";
var conversations = GmailApp.search(query);

Can this be applied to fix the format?

I apologize in advanced as I'm not very skilled in programming.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment