如何修改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.*YOURgoogle\.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 markerstest: The keyword we're targetingYOUR: The end marker for our target rangegsmodifiers: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
相关产品推荐
相关产品推荐

