Google Apps Scripts - Extract data from gmail into a spreadsheet

I made a ready-to-use script, explaining how to use it (from the start) as well, for those who need more assistance.

It's on gmail-to-google-sheets-script repository. Just read the content and follow the instructions.

How to use

  • Create a new Google Sheet
  • Access menu Tools > Script Editor
  • Copy the content from gmailt-to-sheets.gs to editor, replacing the sample code there
  • Replace the value on SEARCH_QUERY to your real query (Do your search on gmail first, copy and paste the search terms there)
  • Select saveEmails on menu (near "run" and "debug" buttons)
  • Click on "Run" button
  • It will ask for authorization at first run, proceed accepting it (it's your Gmail account authorizing your Google Script account)
  • After run, the results will be applied to you sheet

Changing fields

If you want to save different message attributes, take a look at gmail-message class and change your script file the code below comments with a ✏️ (pencil).


Following is the code I wrote and tested that performs the steps 2, 3 and 4 mentioned by you perfectly well.

function myFunction() {

  var ss = SpreadsheetApp.getActiveSheet();

  var label = GmailApp.getUserLabelByName("MyLabel");
  var threads = label.getThreads();

  for (var i=0; i<threads.length; i++)
  {
    var messages = threads[i].getMessages();

    for (var j=0; j<messages.length; j++)
    {
      var msg = messages[j].getBody();
      var sub = messages[j].getSubject();
      var dat = messages[j].getDate();

      ss.appendRow([msg, sub, dat])
    }
      threads[i].removeLabel(label);
  }
}

One of the faults in your code was that the appendRow function accepts an array of elements specified within [ ] brackets.

Depending on where you're attaching this script, your line of code:

var ss = SpreadsheetApp.openById(id);

is not necessary if the script is being written in the script editor of the Spreadsheet where you want these emails to be logged. However, if there are multiple sheets in that spreadsheet, you can replace my line

var ss = SpreadsheetApp.getActiveSheet();

by

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");

Another suggestion is that the current code will give you messages in HTML format. Hence, if you want to get the message in plain text as you see it, use:

var msg = messages[i].getPlainBody();

Now you can write another function for regex and pass the message msg to that. Hope this helps!