1
votes

I'm trying to use Google Script to extract email address and name from forwarded emails that I've filed under a specific label.

The emails look like this:

From: Person A Sent: Sunday, September 22, 2019 8:00 PM To: Other, Email Subject: Forwarded Email

BODY

They have all have been forwarded to this specific inbox. Therefore the headers actually include my other email address I forwarded from.

I've sorted over 2000 emails and now for each of the labels I want to extract the name of the sender (Person A) and their email address ([email protected]) in a spreadsheet. Preferably, I can have the first and last name in separate cells (e.g. Person | A | email address)

The code I have thus far is below:

function processInboxToSheet() {

  // Have to get data separate to avoid google app script limit!

  var start = 0;
  var label = GmailApp.getUserLabelByName("LABEL");
  var threads = label.getThreads();

  var sheet = SpreadsheetApp.getActiveSheet();
  var result = [];



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

    var content = messages[0].getPlainBody();

    // implement your own parsing rule inside
    if (content) {
      var tmp;
      tmp = content.match(/From:\n([A-Za-z0-9\s]+)(\r?\n)/);
      var name = (tmp && tmp[1]) ? tmp[1].trim() : 'No name';

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

      sheet.appendRow([name, email]);

      Utilities.sleep(500);
    }
  }
};

I only get No name and No email as output so something is not quite working in the code. I would appreciate your help.

1
Welcome to Stack Overflow! Please read the help pages, take the SO tour, read about how to ask good questions, as well as this question checklist. Also please learn how to create a minimal reproducible example. Have you tried using a debugger with your code?Ross Jacobs
In addition to Michiel Leegwater's correct answer, I would like to point out that message metadat, such as To, From, Subject, Message ID etc. is not located in body, but in the header of the message. You can retrieve it manually with e.g. messages[0].getHeader("From")ziganotschka

1 Answers

0
votes

You are parsing the plain body, it doesn’t contain to and from. It only contains the message body. The API has methods getTo() and getFrom() that contains what you want to parse. See the API for GmailMessage for more details.