如何通过Google Apps Script将Gmail附件直接添加到Google Drive(非复制)?
将Gmail附件关联到Google Drive(而非复制)的实现方案
你当前的脚本通过复制Blob创建Drive文件副本,要实现和手动点击「添加到云端硬盘」一致的关联效果,需分两种场景处理:
核心逻辑说明
- Google Workspace文件(Docs/Sheets/Slides等):手动添加时是创建快捷方式,不生成副本,脚本可直接获取原文件ID创建快捷方式。
- 普通文件(PDF/图片/压缩包等):手动添加本质是创建副本,但Google统一存储配额下,相同内容仅存一份,不会重复占用空间,和手动操作行为完全一致。
实现步骤与脚本
第一步:启用高级Drive服务
在脚本编辑器中,点击「服务」→「添加服务」→ 选择「Drive API」(版本选v3),保存启用。
完整脚本
const SEARCH_QUERY = 'from:some_required_email@gmail.com'; const TARGET_FOLDER_ID = '1abcde1abcde1abcde1abcde'; function addGmailAttachmentsToDrive() { const threads = GmailApp.search(SEARCH_QUERY); const targetFolder = DriveApp.getFolderById(TARGET_FOLDER_ID); for (const thread of threads) { const messages = thread.getMessages(); for (const message of messages) { const attachments = message.getAttachments(); for (const attachment of attachments) { const attachmentName = attachment.getName(); try { // 获取附件对应的Drive文件ID(仅适用于Google Workspace文件或从Drive上传的附件) const driveFileId = attachment.getId(); if (driveFileId) { // 创建快捷方式到目标文件夹 Drive.Files.create({ title: attachmentName, mimeType: 'application/vnd.google-apps.shortcut', parents: [{ id: TARGET_FOLDER_ID }], shortcutDetails: { targetId: driveFileId } }); Logger.log(`已创建快捷方式: ${attachmentName} (Drive文件ID: ${driveFileId})`); } else { // 普通文件创建副本(统一存储无额外空间占用) const attachmentBlob = attachment.copyBlob(); const file = targetFolder.createFile(attachmentBlob); file.setName(attachmentName); Logger.log(`已保存文件: ${attachmentName}`); } } catch (e) { Logger.log(`处理${attachmentName}失败: ${e.toString()}`); } } } } }
补充说明
- 快捷方式仅对原本就是Drive文件的附件生效,这类附件的
getId()会返回对应的Drive文件ID。 - 普通文件的「副本」在Google统一存储机制下,不会重复占用存储空间,和手动操作的效果一致。
- 若需避免重复处理同一附件,可新增逻辑:将已处理的附件标识(如
attachment.getId()或attachment.getName()+邮件时间)存入Script Properties,每次处理前校验。
内容的提问来源于stack exchange,提问作者Nrupesh
相关产品推荐
相关产品推荐

