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

Google Sheets指定日期4周后发邮件:提取同行列B内容至正文失败求助

解决Google Sheets脚本无法将B列内容带入邮件正文的问题

看起来你已经搞定了定时触发的部分,卡在了把对应行的B列内容带进邮件正文对吧?我来帮你把代码补全并修正逻辑,确保每封邮件都能准确带上对应行的B列信息:

完整修正代码

function sendReminderEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  // 获取第9行到第39行(共31行)的B列(第2列)和Q列(第17列)数据
  var dataRange = sheet.getRange(9, 2, 31, 16); // 从B列开始,跨16列到Q列
  var data = dataRange.getValues();
  
  var today = new Date();
  // 统一日期格式,只保留年月日,避免时间干扰判断
  today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
  
  data.forEach(function(row) {
    var targetDate = row[15]; // Q列是区域内第16列,数组索引为15(从0开始)
    var bColumnContent = row[0]; // B列是区域内第1列,数组索引为0
    
    // 先检查Q列是否为有效日期,避免脚本报错
    if (targetDate instanceof Date && !isNaN(targetDate.getTime())) {
      // 计算目标日期4周后的日期(28天)
      var reminderDate = new Date(targetDate);
      reminderDate.setDate(reminderDate.getDate() + 28);
      // 同样统一日期格式
      reminderDate = new Date(reminderDate.getFullYear(), reminderDate.getMonth(), reminderDate.getDate());
      
      // 如果今天正好是目标日期的4周后,发送提醒邮件
      if (reminderDate.getTime() === today.getTime()) {
        var recipient = Session.getActiveUser().getEmail(); // 默认发送给自己
        var subject = "4周到期提醒";
        var body = `你好,距离指定日期 ${targetDate.toLocaleDateString()} 已过去4周,相关信息:\n${bColumnContent}`;
        
        MailApp.sendEmail(recipient, subject, body);
      }
    }
  });
}

关键逻辑说明

  • 绑定B列与Q列数据:之前你只单独获取了Q列的数据,现在我们一次性获取对应行的B列和Q列区域,确保每一行的日期和内容一一对应,不会出现错位。
  • 日期格式统一处理:把所有日期都转换为仅保留年月日的格式,避免因为单元格日期带有时分秒、或者脚本运行时间的时分秒差异导致判断失误。
  • 有效性检查:增加了对Q列内容是否为有效日期的判断,防止空值或非日期内容导致脚本崩溃。
  • 邮件内容动态填充:在邮件正文中直接使用bColumnContent变量,把对应行的B列内容插入进去,实现你需要的动态内容效果。

额外注意事项

  • 如果你的数据行数不是31行,只需要修改getRange(9, 2, 31, 16)中的第三个参数(31)为实际的行数即可。
  • 收件人可以替换成固定邮箱地址,比如把Session.getActiveUser().getEmail()改成"your-email@example.com"。
  • 邮件的主题和正文格式可以根据你的需求自由调整,比如添加更多格式或者其他单元格的信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:33:41