How to Use Google Apps Script to Parse Unread Gmail Threads and Push Snippets to a Webhook

While standard Gmail filters are excellent for applying labels, forwarding messages, or marking emails as read, they completely lack the ability to manipulate the actual contents of the email. If your organisation receives automated daily reports, customer inquiry forms, or system alert notifications, you often need to extract specific data snippets from the email body and push that data into an external system, such as a Slack channel, a custom CRM, or an incident management webhook. To achieve this level of programmatic email processing, administrators must leverage Google Apps Script to parse the inbox dynamically.

By writing a custom Apps Script bound to a time-driven trigger, you can create a headless automation tool that continuously monitors your Gmail inbox, extracts necessary information using regular expressions, transmits the payload to a REST API, and archives the thread to prevent duplicate processing.

Querying Unread Gmail Threads

The first step in the automation process is retrieving the relevant emails. Instead of iterating through every email in the inbox, you should utilise the GmailApp.search() method, which accepts standard Gmail search operators. This drastically reduces the script’s execution time and prevents API quota exhaustion.

Open the Google Apps Script dashboard (script.google.com) and create a new project. Begin by defining the search criteria to isolate unread messages from a specific sender or containing a specific subject line.

function processIncomingAlerts() {
  // Search for unread emails matching specific criteria
  var searchQuery = 'is:unread from:[email protected] subject:"Critical Error"';
  var threads = GmailApp.search(searchQuery, 0, 10); // Process in batches of 10
  
  if (threads.length === 0) {
    return; // Exit if no new emails are found
  }
  
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    var latestMessage = messages[messages.length - 1]; // Get the newest email in the thread
    
    // Proceed to parsing
    parseAndPush(latestMessage, threads[i]);
  }
}

Parsing the Email Body with Regular Expressions

Once you have isolated the specific GmailMessage object, you can extract the plain text body using the getPlainBody() method. If the email contains structured data, you can use Javascript Regular Expressions (Regex) to isolate the specific variables you need to extract.

For example, assume the automated email always contains a line formatted as Error Code: 503. You can write a regex pattern to extract just the numeric code.

function parseAndPush(message, thread) {
  var emailBody = message.getPlainBody();
  var emailSubject = message.getSubject();
  
  // Extract the error code using Regex
  var errorCodeMatch = emailBody.match(/Error Code:\s*(\d+)/i);
  var errorCode = errorCodeMatch ? errorCodeMatch[1] : "Unknown";
  
  // Construct the JSON payload
  var payload = {
    "subject": emailSubject,
    "error_code": errorCode,
    "timestamp": message.getDate().toISOString()
  };
  
  // Proceed to webhook execution
  sendToWebhook(payload, thread);
}

Pushing the Snippet to an External Webhook

With the extracted data structured into a clean JSON object, you can transmit it to an external service using the UrlFetchApp class. This class allows Apps Script to perform outbound HTTP POST requests. You must ensure the destination webhook URL is prepared to receive and process the JSON payload.

function sendToWebhook(payload, thread) {
  var webhookUrl = "https://hooks.your-external-service.com/endpoint";
  
  var options = {
    "method": "post",
    "contentType": "application/json",
    "payload": JSON.stringify(payload),
    "muteHttpExceptions": true // Prevents the script from crashing if the webhook fails
  };
  
  var response = UrlFetchApp.fetch(webhookUrl, options);
  
  // Only mark as read and archive if the webhook successfully accepted the payload
  if (response.getResponseCode() === 200 || response.getResponseCode() === 201) {
    thread.markRead();
    thread.moveToArchive();
  } else {
    Logger.log("Webhook failed with status: " + response.getResponseCode());
  }
}

Automating the Execution via Time-Driven Triggers

The final step is to ensure this script runs autonomously. In the Apps Script editor, click on the Triggers icon (the clock symbol) in the left-hand navigation menu. Click Add Trigger.

Select the processIncomingAlerts function, choose Time-driven as the event source, select Minutes timer, and set the interval (e.g., every 5 minutes). Save the trigger.

Google will ask you to grant authorization for the script to access your Gmail data and connect to an external service. Once authorized, the script will run silently in the background, continuously parsing inbound alerts, extracting the critical snippets, pushing them to your designated webhook, and cleaning up the inbox without any manual intervention.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.