如何修改Gmail转Google Drive脚本,替换附件名为指定名称加日期?
修改Gmail附件转存Google Drive脚本:自定义文件名+ddmmyy日期格式
要实现将附件文件名替换为「指定名称+ddmmyy格式日期+原扩展名」的需求,你需要对原脚本做以下3处修改:
1. 新增自定义名称变量与日期生成函数
先定义你想要的固定前缀名称,再写一个生成ddmmyy格式日期的工具函数,确保日期格式符合要求(比如1月23日2022年就是012322)。
2. 提取原附件的扩展名
从原附件文件名中拆分出扩展名,保证转存后的文件保留原格式(比如.xlsx、.csv)。
3. 替换Drive文件的标题赋值逻辑
把原本直接使用原附件名称的逻辑,改成用「自定义名称+日期+扩展名」组合成新文件名。
修改后的完整脚本
const searchItem = "in:inbox subject:(My Project) has:attachment"; const threads = GmailApp.search(searchItem, 0, 100); // 自定义固定前缀名称,可替换为你需要的内容 const customFileNamePrefix = "project"; // 生成ddmmyy格式日期的函数 function getFormattedDate() { const now = new Date(); const day = String(now.getDate()).padStart(2, '0'); const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需+1 const year = String(now.getFullYear()).slice(-2); // 取年份后两位 return day + month + year; } 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) => { const originalName = attachment.getName(); // 提取原文件扩展名,兼容无扩展名的附件 const nameParts = originalName.split('.'); const fileExtension = nameParts.length > 1 ? nameParts.pop() : ''; // 组合新文件名 let newFileName = `${customFileNamePrefix}${getFormattedDate()}`; if (fileExtension) { newFileName += `.${fileExtension}`; } // 转存到Drive时使用新文件名 Drive.Files.insert({ title: newFileName, mimeType: attachment.getContentType(), parents: [{ id: folderId }] }, attachment.copyBlob()); }); } return [id]; }); });
关键修改说明
customFileNamePrefix:直接替换成你实际需要的固定名称(比如示例中的"project")。getFormattedDate():自动生成ddmmyy格式的日期,padStart(2, '0')确保日/月都是两位数(比如1日自动补为01)。- 扩展名处理:通过拆分原文件名获取扩展名,同时兼容无扩展名的附件(避免出现多余的点号)。
内容的提问来源于stack exchange,提问作者Rex Skys
相关产品推荐
相关产品推荐

