Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Ethanb00/f22b23185bc9e17cfaad1391de6f85e4 to your computer and use it in GitHub Desktop.
Save Ethanb00/f22b23185bc9e17cfaad1391de6f85e4 to your computer and use it in GitHub Desktop.
Gmail/Gsuite provides no native way to filter on the basis of which user sent an email within a delegated gmail account. That filter is required to be able to automatically apply labels and organize the inbox (in order to easily and quickly see who sent which emails). This sample code block outlines how to parse through your sent box and filter …
function processInbox() {
//var threads = GmailApp.search("in:sent", 0, 500); //you can uncomment this line to run a bulk labelling the first time thru, then recomment it for the future
var threads = GmailApp.search("newer_than:2h"); //check for new messages in the past x time frame, you can adjust this as needed
for (var i = 0; i < threads.length; i++) { //interate thru all the threads we found
var sentBy = threads[i].getMessages()[0].getHeader("X-Google-Sender-Delegation") //isolate the header value "X-Google-Sender-Delegation" - This is the email header that indicates which user actually sent the email thru the delegated account
if (sentBy == "[email protected]"){ //if the message is sent by this email address - this is the unfortunate part. you have to hard code each email that you are expecting to see. so you're going to make 1 or more if statements related to each of the labels that you created in the delegated email account to capture these messages
var label = GmailApp.getUserLabelByName("Label Name"); //grab the name of the Label we want to apply from the Gmail inbox...you should have already created this label before running this script
label.addToThread(threads[i]); //apply the label
}
if (sentBy == "..."){
... // repeat the above block for each label (i.e. sender) you want to filter for
}
}
}
@lwcorp
Copy link

lwcorp commented Jun 11, 2021

Nice! Any idea how to run this script through the delegate's own account?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment