Google AppMaker基于计算日期触发邮件通知功能实现问询
Google AppMaker 日期触发式邮件提醒函数实现
我帮你把这个函数规整好,还补上了基于triggerDay的日期触发逻辑,这样就能按照你要求的提前天数自动触发邮件提醒啦:
function alertnotice(to, subject, body, dueDate, notifyBeforeDay) { // 内部封装的邮件发送函数,处理异常捕获 function sendEmail(to, subject, body){ try { MailApp.sendEmail({ to: to, subject: subject, htmlBody: body }); } catch(e) { console.error(JSON.stringify(e)); } } // 核心:计算触发提醒的日期(截止日期往前推notifyBeforeDay天) const triggerDay = new Date(dueDate); triggerDay.setDate(triggerDay.getDate() - notifyBeforeDay); // 工具函数:格式化日期为YYYY-MM-DD,避免时分秒干扰判断 const formatDate = (date) => { return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; }; // 格式化今日和触发日期,只比较年月日 const todayFormatted = formatDate(new Date()); const triggerDayFormatted = formatDate(triggerDay); // 日期触发判断逻辑 if (todayFormatted === triggerDayFormatted) { sendEmail(to, subject, body); console.log(`提醒邮件已成功发送至:${to}`); } else { console.log(`今日未到达提醒触发日期,预计触发日期为:${triggerDayFormatted}`); } }
关键细节说明:
- 日期计算:通过
setDate()和getDate()方法安全计算提前提醒的日期,不用担心跨月/跨年的日期溢出问题 - 日期格式化:统一转成
YYYY-MM-DD格式,避免因为传入的dueDate包含时分秒,导致和今日日期的时分秒不匹配而跳过触发 - 异常处理:保留了原有的邮件发送异常捕获,同时添加了执行日志,方便排查问题
内容的提问来源于stack exchange,提问作者alep
相关产品推荐
相关产品推荐

