Google应用程序脚本pageToken,用于将附件保存到Google Drive



基本上,我想做的是将收到的电子邮件中的所有附件都放在谷歌硬盘中的一个文件夹中(有很多,大部分是.PDF(。但它说,我不能用搜索功能超过500个附件,我必须使用一种名为pageToken的东西,我不知道如何将其应用于我的代码。所以我需要一些建议或指导,或者一些例子来做到这一点。

function saveGmailtoGoogleDrive() {
const folderId = '1apaQJjDSK-bNfd3ZgiFqK23cE7SCPqoB'; //Google Drive Folder
const searchQuery = 'label:unread has:attachment'; //Filter
const threads = GmailApp.search(searchQuery, 0, 500);

threads.forEach(thread => {
const messages = thread.getMessages();
messages.forEach(message => {
const attachments = message.getAttachments({
includeInlineImages: false,
includeAttachments: true

});
attachments.forEach(attachment => {
// Insert the attachment to google drive folder
Drive.Files.insert(
{
title: attachment.getName(),
mimeType: attachment.getContentType(),
parents: [{ id: folderId }]
},
attachment.copyBlob()
);
});
});
});
};

function saveGmailtoGoogleDrive() {
const folderId = '1apaQJjDSK-bNfd3ZgiFqK23cE7SCPqoB'; //Google Drive Folder
const searchQuery = 'label:unread has:attachment'; //Filter
const threads = GmailApp.search(searchQuery, 0, 500);

threads.forEach(thread => {
const messages = thread.getMessages();
messages.forEach(message => {
const attachments = message.getAttachments({
includeInlineImages: false,
includeAttachments: true

});
attachments.forEach(attachment => {
// Insert the attachment to google drive folder
Drive.Files.insert(
{
title: attachment.getName(),
mimeType: attachment.getContentType(),
parents: [{ id: folderId }]
},
attachment.copyBlob()
);
});
});
});
};

search(query, start, max)的方法的参数是query, start, maxmax的当前最大值为500。当该值超过时,会出现类似Argument max cannot exceed 500.的错误。并且,start是搜索的开始位置。所以我认为这可以用来实现你的目标。当这反映在脚本中时,它将变为如下。

修改的脚本:

来源:

const threads = GmailApp.search(searchQuery, 0, 500);

收件人:

let [start, end] = [0, 500];
let threads = [];
do {
const t = GmailApp.search(searchQuery, start, end);
start += end;
threads = [...threads, ...t];
} while (threads.length == start);
  • 通过此修改,您可以在threads中检索500多封电子邮件

参考:

  • 搜索(query,start,max(

最新更新