How to Retrieve Replied Emails for Gmail

Gists

Description :

This sample script is for retrieving emails which replied for received mails. Because there are no samples which confirm whether the owner (me) replied to the received mails, I created this. The point is as follows.

  • When there are more than 2 messages in a thread, there might be a possibility to have replied.
  • For more than 2 messages in a thread
    • The email address of “from” for the 1st message is the sender’s address.
    • When the email address of “to” of after 2nd messages is the same to that of “from” of 1st one, it is indicates that the thread was replied by owner.

This sample script is made of Google Apps Script (GAS). But also this can be applied to other languages.

Note :

  • The mails that it was replied to the mails that owner sent cannot be retrieved.
  • If you use this sample script, please test using for example var th = GmailApp.getInboxThreads(0, 50);, and understand the flow.

Sample 1

function main() {
  var threadId = "";
  var thread = GmailApp.getInboxThreads();
  thread.forEach(function(th) {
    th.getMessages().forEach(function(msg) {
      var mm = msg.getThread().getMessages();
      if (mm.length > 0) {
        var temp = [];
        mm.forEach(function(m) {
          var re = /<(\w.+)>/g;
          var from  = m.getFrom();
          var to = m.getTo();
          temp.push({
            from: from.match(re) ? re.exec(from)[1] : from,
            to: to.match(re) ? re.exec(to)[1] : to
          });
        });
        if (temp.length > 1 && threadId != th.getId()) {
          if (temp.filter(function(e){return temp[0].from == e.to}).length > 0) {
            Logger.log("threadId: %s", th.getId())

            // do something

          }
         threadId = th.getId();
        }
      }
    });
  });
}

 Share!