I'm trying to write a Google Apps script which automatically adds my Gmail attachments to Google Drive. What I have been able to accomplish is to create a copy of the Gmail attachments in the Google Drive using copyBlob() function/method from GmailApp attachments and createFile() function/method from DriveApp.
Used the following script below to accomplish what I mentioned above, and it works fine.
const search = 'from:[email protected]';
const threads = GmailApp.search(search);
const folderId = '1abcde1abcde1abcde1abcde';
// Loop through the threads and extract attachments
for (const thread of threads) {
const messages = thread.getMessages();
for (const message of messages) {
const attachments = message.getAttachments();
for (const attachment of attachments) {
var attachmentBlob = attachment.copyBlob();
var attachmentName = attachment.getName();
var attachmentFolder = DriveApp.getFolderById(folderId);
try {
var file = attachmentFolder.createFile(attachmentBlob);
file.setName(attachmentName);
Logger.log("Saved: " + attachmentName);
} catch (e) {
Logger.log("Error saving " + attachmentName + ": " + e);
}
}
}
}
However, what I'm trying to accomplish is not to create a copy but to Add the attachment directly to Drive. If you look at the attached images/screenshots, the first one shows the attachment copied to Google Drive from Gmail using the Google Apps script; and the second one shows the attachment manually added to Google Drive from Gmail by clicking on the attachment.
Is there any way I could use the script to replicate the manual functionality - i.e., add the Gmail attachment to Google Drive instead of copying it and creating a file in Google Drive? I have a lot of attachments and am looking to conserve Google/Gmail drive space by avoiding duplicate copies of the attachment in Drive and Gmail, and also trying to avoid manually adding the attachments to Google Drive multiple times each day.
Thank you in advance!

