Skip to content

Instantly share code, notes, and snippets.

@PradeepTammali
Last active March 8, 2023 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PradeepTammali/3a31cd48579edfc51d3590fe9cf479df to your computer and use it in GitHub Desktop.
Save PradeepTammali/3a31cd48579edfc51d3590fe9cf479df to your computer and use it in GitHub Desktop.
RegEx Gmail Filter
function filterTestMail() {
// Make this function trigger every 5 min so that it will have to only get last 1 hour emails.
const LABEL_NAME = 'Guest';
const emailPattern = /^pradeep\.tammali\+fakedata[0-9]*@oneflow\.com$/;
try {
no_label = true;
labels = GmailApp.getUserLabels();
for (var i = 0; i < labels.length; i++) {
if (labels[i].getName() == LABEL_NAME) {
no_label = false;
}
}
// Create lable if doesn't exist
if (no_label == true) {
GmailApp.createLabel(LABEL_NAME);
}
const FILTER_LABEL = GmailApp.getUserLabelByName(LABEL_NAME);
// Get the yesterday date
// var yesterdayDate = (new Date().getDate() - 1).toString();
// let today = new Date();
// let after = new Date(today);
// after.setDate(after.getDate() - 1);
// var afterDate = after.toLocaleDateString();
// let yesterdayFormatted = yesterday.getFullYear() + '/' + (yesterday.getMonth() + 1).toString().padStart(2, '0') + '/' + yesterday.getDate().toString().padStart(2, '0');
// In MM/DD/YYYY format
// Get all the emails since yesterday
// var mails = GmailApp.search("in:anywhere after:" + afterDate);
// Get mails newer than 1 hour
var mails = GmailApp.search("in:anywhere newer_than:1h");
// Get mails newer than 1 day
// var mails = GmailApp.search("in:anywhere newer_than:1d");
if (mails.length > 0) {
for (var t = mails.length - 1; t >= 0; t--) {
var thread = mails[t];
var message = thread.getMessages()[0];
var toAddress = message.getTo();
if (emailPattern.test(toAddress)) {
thread.addLabel(FILTER_LABEL);
GmailApp.moveThreadToArchive(thread);
}
}
}
} catch (e) {
Logger.log(e.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment