- go to https://script.google.com and create a new Google Apps Script
select the "Create script for Gmail" option
- this will create a script project
- this will create a script called
Code.gs
- this will create sample functions, one them named
processInbox
save the project
- customize the script and test it until you are satisfied
find the "custom project's triggers" button
- this will let you run the script on a timer (e.g. daily, or every minute)
Example:
processInbox
This function will iterate over all messages in the Inbox.
function processInbox() {
// process all recent threads in the Inbox (see comment to this answer)
var threads = GmailApp.search("newer_than:1h");
for (var i = 0; i < threads.length; i++) {
// get all messages in a given thread
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var message = messages[j];
processMessage(message);
}
}
}
Go one step further and call GmailApp.search()
if you want to do something fancy instead of GmailApp.getInboxThreads()
.
processMessage
This function will take care of processing a single message; you get the raw content with getRawContent()
and try to find your header in there, if it is in there, tag the message.
function processMessage(message) {
var body = message.getRawContent();
if (body.indexOf("X-Custom-Header: some-custom-value") > -1) {
// do stuff with message (e.g. add label)
}
}