There’s a well known problem using gmail as a mail reader for messages downloaded using POP. That is, gmail wants to treat replies as already seen, and so they skip the inbox. You can easily find people complaining about this, as I did when it happened in our house. Apparently gmail is reading the message header, doing some pattern matching, and deciding this is not inbox material. There may be more elegant solutions, but after much effort and following much wrong advice, I vibe coded this and it seems to work. There were quite a few mistakes at first, so be careful. Some things to pay attention to.
-The script should take seconds to execute. If it is going more than 15 seconds, it is probably reading too many emails. Abort and inspect.
-You are repeatedly seeing archived emails return. This is a problem with labelling. Ask for help.
Here’s my solution:
Go to https://script.google.com/ and create a new project. Name it something practical, like “Gmail Sweep.” Paste the script below into the editor. Remember to replace youraddress@example.com in the second line with your actual address. Note: You will see a label in this script specific to my SaneBox email filters. Sanebox is a useful tool from the olden days, but if you don’t use it this label will not matter. I leave it here as a placeholder to remind that if using a different filtering system, you want to account for this so filtered mail doesn’t get swept back into the inbox.
function sweepReplies() {
const yourAddress = 'youraddress@example.com';
const labelName = 'MovedBySweep';
const label = GmailApp.getUserLabelByName(labelName) || GmailApp.createLabel(labelName);
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
const formattedDate = Utilities.formatDate(yesterday, Session.getScriptTimeZone(), 'yyyy/MM/dd');
const threads = GmailApp.search(`-in:inbox -in:drafts -in:spam -in:trash -label:${labelName} -label:@saneblackhole after:${formattedDate}`);
for (let thread of threads) {
const messages = thread.getMessages();
const latestMessage = messages[messages.length - 1];
const headers = latestMessage.getRawContent();
const toMatch = headers.match(/^To: (.*)$/m);
const ccMatch = headers.match(/^Cc: (.*)$/m);
let addressedToYou = false;
if (toMatch && toMatch[1].includes(yourAddress)) addressedToYou = true;
if (ccMatch && ccMatch[1].includes(yourAddress)) addressedToYou = true;
const isReply = headers.includes('In-Reply-To:');
if (isReply && addressedToYou) {
thread.moveToInbox();
thread.addLabel(label);
Logger.log('Moved and labeled thread: ' + thread.getFirstMessageSubject());
}
}
}