如何修改Gmail的Needs Reply脚本以适配关联多邮箱?
修改Gmail自动标记脚本以支持多邮箱/域名判断
需求说明
原本的脚本只能识别当前登录的Gmail账户发送的未回复邮件,现在需要适配同步到Gmail的其他邮箱,支持两种判断规则:
- 指定单个邮箱地址(如
email1@domain.com、email2@domain.com) - 指定整个域名(如
@domain.com,匹配该域名下所有邮箱)
修改后的完整脚本
function labelNeedsReply() { // --------------------- 配置区域 --------------------- // 添加需要监控的单个邮箱 const monitoredEmails = [ Session.getActiveUser().getEmail(), 'email1@domain.com', 'email2@domain.com' ]; // 添加需要监控的域名(格式带@,比如@domain.com) const monitoredDomains = [ '@yourdomain.com' ]; // --------------------------------------------------- // 创建/获取"Needs Reply"标签 let needsReplyLabel = GmailApp.getUserLabelByName('Needs Reply'); if (!needsReplyLabel) { needsReplyLabel = GmailApp.createLabel('Needs Reply'); } // 搜索收件箱或已标记的线程 const threads = GmailApp.search('in:inbox OR label:needs-reply'); for (let i = 0; i < threads.length; i++) { const thread = threads[i]; const lastMessage = thread.getMessages()[thread.getMessageCount() - 1]; const fromText = lastMessage.getFrom(); // 从发件人文本中提取纯邮箱地址(处理"姓名 <邮箱>"的格式) const emailMatch = fromText.match(/<([^>]+)>/); const senderEmail = emailMatch ? emailMatch[1] : fromText; // 判断是否属于需要监控的邮箱或域名 let shouldLabel = false; // 检查单个邮箱匹配 if (monitoredEmails.includes(senderEmail)) { shouldLabel = true; } // 检查域名匹配 else { for (const domain of monitoredDomains) { if (senderEmail.endsWith(domain)) { shouldLabel = true; break; } } } // 添加或移除标签 if (shouldLabel) { needsReplyLabel.addToThread(thread); } else { needsReplyLabel.removeFromThread(thread); } } }
关键改动说明
新增配置区域:
monitoredEmails数组:把当前账户邮箱和需要新增的目标邮箱都放这里,直接修改即可monitoredDomains数组:添加需要监控的域名,格式要带@,比如@company.com
提取纯邮箱地址:
Gmail的getFrom()方法返回的内容格式通常是"张三 <zhangsan@domain.com>",用正则表达式/<([^>]+)>/可以提取出尖括号里的纯邮箱地址,避免因为姓名部分导致判断错误。多维度匹配逻辑:
先判断发件邮箱是否在monitoredEmails列表里,再判断是否属于monitoredDomains里的域名,任一条件满足就标记为需要跟进。
使用提示
- 直接在Google Apps Script编辑器里替换原脚本,修改
monitoredEmails和monitoredDomains的内容即可 - 可以设置脚本定时触发(比如每天执行一次),实现自动标记
内容的提问来源于stack exchange,提问作者Waldopepper
相关产品推荐
相关产品推荐

