-
-
Save jimbrig/39140fe43b74b5073189724b1291d008 to your computer and use it in GitHub Desktop.
Automatically Save Email Attachments to Google Drive Using Google Apps Script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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