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

如何修改Gmail自动回复脚本,匹配特定位置的'test'关键词

Fixing Your Auto-Reply Keyword Matching

Got it, let's tweak your script to only trigger the test reply when "test" appears between "google.com>" and "YOUR" in the email body. The issue with your current code is that includes('test') checks the entire body—we need a more precise check using a regular expression.

Modified Code

Here's the updated autoReplier function with the targeted matching:

function autoReplier() {
  var labelObj = GmailApp.getUserLabelByName('autoreply');
  var gmailThreads;
  var messages;
  var sender;
  // Regex to match "test" between "google.com>" and "YOUR" (supports line breaks)
  const testRegex = /google\.com>.*test.*YOUR/gs;

  for (var gg = 0; gg < labelObj.getUnreadCount(); gg++) {
    gmailThreads = labelObj.getThreads()[gg];
    messages = gmailThreads.getMessages();
    
    for (var ii = 0; ii < messages.length; ii++) {
      if (messages[ii].isUnread()) {
        const msg = messages[ii].getPlainBody();
        sender = messages[ii].getFrom();
        
        if (testRegex.test(msg)) {
          MailApp.sendEmail(sender, "Auto Reply", "This is my test");
        } else {
          MailApp.sendEmail(sender, "Auto Reply", "Sorry, your keyword was not recognized");
        }
        
        messages[ii].markRead();
        messages[ii].moveToTrash();
      }
    }
  }
}

Key Changes Explained

  • Regular Expression: google\.com>.*test.*YOUR
    • google\.com>: Matches the exact string "google.com>" (we escape the . with a backslash because it has special meaning in regex)
    • .*: Matches any sequence of characters (including spaces) between the start and end markers
    • test: The keyword we're targeting
    • YOUR: The end marker for our target range
    • gs modifiers:
      • g: Global search (not strictly necessary here, but harmless)
      • s: Allows . to match line breaks—critical because email bodies often have line breaks between these markers

Optional Adjustment

If you need the match to be case-insensitive (e.g., match "Test" or "TEST"), add the i modifier to the regex:

const testRegex = /google\.com>.*test.*YOUR/gsi;

This will ensure your auto-reply only triggers when "test" is exactly in the section you want, ignoring other occurrences elsewhere in the email.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:29:59