I created an script that can transfer my gmail attachment to gdrive, but I have to modify my script since it downloads all the gmail attachment even its already downloaded.
May I know what I need to modify on my script?
function saveGmailToGdrive(){
const folderId = "GDRIVE"
const searchItem = "label:MONEY"
const threads = GmailApp.search(searchItem,0,100)
threads.forEach((thread) => {
const messages = thread.getMessages()
messages.forEach((message) => {
const attachments = message.getAttachments({
includeInlineImages:false,
includeAttachments:true
})
attachments.forEach((attachment) => {
Drive.Files.insert({
title:attachment.getName(),
mimeType:attachment.getContentType(),
parents:[{id:folderId}]
},
attachment.copyBlob()
)
})
})
})
}
I hope someone can help me thank you!
CodePudding user response:
In that case, how about storing the message IDs that the attachment files were downloaded? By this, after 2nd run of the script, the attachment files from only new messages can be downloaded by searching the message IDs.
Modified script:
Before you use this script, please create a new Spreadsheet and put the Spreadsheet ID to spreadsheetId
.
function saveGmailToGdrive() {
const spreadsheetId = "###"; // Please create new Spreadsheet and put Spreadsheet ID here.
// 1. Retrieve message IDs from Spreadsheet.
const sheet = SpreadsheetApp.openById(spreadsheetId).getSheets()[0];
const lastRow = sheet.getLastRow();
const values = lastRow == 0 ? [] : sheet.getRange(1, 1, lastRow).getValues().map(([a]) => a);
// 2. By checking the message IDs, the attachment files are downloaded.
const folderId = "GDRIVE"; // Please set your folder ID.
const searchItem = "label:MONEY";
const threads = GmailApp.search(searchItem, 0, 100);
const ids = threads.flatMap((thread) => {
const messages = thread.getMessages();
return messages.map((message) => {
const id = message.getId();
if (!values.includes(id)) {
const attachments = message.getAttachments({ includeInlineImages: false, includeAttachments: true });
attachments.forEach((attachment) => {
Drive.Files.insert({ title: attachment.getName(), mimeType: attachment.getContentType(), parents: [{ id: folderId }] }, attachment.copyBlob());
});
}
return [id];
});
});
// 3. Update message IDs on Spreadsheet.
if (ids.length == 0) return;
sheet.clear().getRange(sheet.getLastRow() 1, 1, ids.length, 1).setValues(ids);
}
- When this script is run for the first time, the attachment files are downloaded from all messages. In this run, the message IDs are stored in Spreadsheet. After 2nd run, by searching the message IDs, the attachment files are downloaded.