You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确格式化Gmail旧邮件日期并重命名附件?

问题

编写脚本从Gmail提取CSV文件并移动到指定Drive文件夹,希望将文件重命名为邮件接收日期(格式MMddyyyy),但实际运行后文件被重命名为脚本执行日期而非邮件接收日期。打印date变量能看到正确的邮件日期,但格式为[星期][日][月][年][时间]格式。

当前使用的代码:

//const fileType = ['csv'];
//const processedLabel = "Processed TBD Data";
//var res = GmailApp.search(query);
const dir = DriveApp.getFolderById("<folderID>");
const query = 'has:attachment from:it label:EOD-TBD';
var rmLabel = GmailApp.getUserLabelByName('EOD-TBD');
var newLabel = GmailApp.getUserLabelByName('Processed TBD Data');

function countThreads() { 

  //Find threads within "EOD-TBD" that have an attachment
  var TBD_Threads = GmailApp.search(query);

  for (var m = 0; m < TBD_Threads.length; m++) { //Counts threads
  var threads = TBD_Threads[m].getMessages()
  
  for (var j = 0; j < threads.length; j++) {
    var date = threads[j].getDate()
    var nDate = Utilities.formatDate(new Date(date), "GMT+1", "MM/dd/yyyy")
    Logger.log("Processing Message from: " + nDate)
    var att=threads[j].getAttachments()
    for (var k = 0; k < att.length; k++){
      var attachmentBlob = att[k].copyBlob().setName(nDate);
      //var file = DriveApp.createFile(attachmentBlob);
      var file = dir.createFile(attachmentBlob);

    }
  }
  TBD_Threads[m].removeLabel(rmLabel);
  TBD_Threads[m].addLabel(newLabel);
}
}
解决方案

问题根源

  1. 多余的Date对象包装:threads[j].getDate()已经返回标准Date对象,再用new Date(date)包装会触发异常解析,最终使用脚本执行的当前日期。
  2. 日期格式错误:你需要的是MMddyyyy格式,但代码中用了MM/dd/yyyy,且Drive文件名不允许包含斜杠,会导致命名异常。
  3. 未筛选CSV附件:当前代码会处理所有类型附件,不符合仅提取CSV的需求。

修改后的代码

const dir = DriveApp.getFolderById("<folderID>");
const query = 'has:attachment from:it label:EOD-TBD';
const rmLabel = GmailApp.getUserLabelByName('EOD-TBD');
const newLabel = GmailApp.getUserLabelByName('Processed TBD Data');
const targetFileType = 'csv'; // 指定只处理CSV附件

function countThreads() { 
  const TBD_Threads = GmailApp.search(query);

  for (let m = 0; m < TBD_Threads.length; m++) {
    const messages = TBD_Threads[m].getMessages();
    
    for (let j = 0; j < messages.length; j++) {
      const receiveDate = messages[j].getDate();
      // 直接使用邮件接收的Date对象,格式化为MMddyyyy,时区保持GMT+1
      const formattedDate = Utilities.formatDate(receiveDate, "GMT+1", "MMddyyyy");
      Logger.log("Processing Message from: " + formattedDate);
      
      const attachments = messages[j].getAttachments();
      for (let k = 0; k < attachments.length; k++) {
        const attachment = attachments[k];
        // 只处理CSV类型的附件
        if (attachment.getContentType() === 'text/csv' || attachment.getName().toLowerCase().endsWith('.csv')) {
          // 保留原文件的.csv后缀,避免文件类型识别问题
          const blob = attachment.copyBlob().setName(`${formattedDate}.csv`);
          dir.createFile(blob);
        }
      }
    }
    // 移动邮件标签
    TBD_Threads[m].removeLabel(rmLabel).addLabel(newLabel);
  }
}

关键修改点

  • 移除new Date(date)的多余包装,直接使用邮件返回的Date对象进行格式化。
  • 将日期格式改为MMddyyyy,并添加.csv后缀,保证文件类型正确识别。
  • 新增CSV附件筛选逻辑,避免处理非目标类型文件。
  • 简化标签操作的链式调用,让代码更简洁。

内容的提问来源于stack exchange,提问作者Amelia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:55:16