Parse Gmail Messages to Extract Data from HTML

A mailbox has 1000s of email messages sent though legacy contact forms that contain data like the name, email and address of the senders. The business owner would like to parse these email messages, extract the relevant bits and save them to a Google Spreadsheet.

The script can be run in batches of 100 thread, to avoid exceeding the time limit, and the parsing rules can be written in Regular Expressions. Snippet by @Ferrari.

The code can extended to parse emails and extract other structured data from the message body including events information, order details, travel itineraries, shipping & tracking information, customer records and more.

/* Based on https://gist.github.com/Ferrari/9678772 */

function parseEmailMessages(start) {
  start = start || 0;

  var threads = GmailApp.getInboxThreads(start, 100);
  var sheet = SpreadsheetApp.getActiveSheet();

  for (var i = 0; i < threads.length; i++) {
    // Get the first email message of a threads
    var tmp,
      message = threads[i].getMessages()[0],
      subject = message.getSubject(),
      content = message.getPlainBody();

    // Get the plain text body of the email message
    // You may also use getRawContent() for parsing HTML

    // Implement Parsing rules using regular expressions
    if (content) {
      tmp = content.match(/Name:\s*([A-Za-z0-9\s]+)(\r?\n)/);
      var username = tmp && tmp[1] ? tmp[1].trim() : 'No username';

      tmp = content.match(/Email:\s*([A-Za-z0-9@.]+)/);
      var email = tmp && tmp[1] ? tmp[1].trim() : 'No email';

      tmp = content.match(/Comments:\s*([\s\S]+)/);
      var comment = tmp && tmp[1] ? tmp[1] : 'No comment';

      sheet.appendRow([username, email, subject, comment]);
    } // End if
  } // End for loop
}

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻