Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jimbrig/39140fe43b74b5073189724b1291d008 to your computer and use it in GitHub Desktop.
Save jimbrig/39140fe43b74b5073189724b1291d008 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment