How to Read Email from Inbox using Google App Script.

How to Read Email from Inbox using Google App Script.

First, we write a function to fetch email from our inbox. It is easy to fetch the email from the account because Google knows that you are already logged in to it and fetching data from your email account.

First, we will open the Google App script, Once you are in your Google sheet. Go to Extensions Click on Apps Scrip, it takes you to the page called Apps Script Editor where you write the function and code.

We will write the function call fetch email in the app script editor.

In the function, First, we get all Gmail Threads using the getInboxThreads function, we can also pass the start number and max value in the function. So this function returns an array. Array of Threads. Then we run the for loop function to loop each thread. In the loop, we will fetch mail subject lines using the getFirstMessageSubject Function and messages using the getMessages function. In the messages, you can get all the message details using methods like getAttachments, getBcc, getBody or plainbody, getcc, getdate, getfrom, getheader, getsubject, and getFrom.

function fetchEmail() {
  var all_threads = GmailApp.getInboxThreads(0,30);
   for(var b=0; b<all_threads.length; b++)
   {
    var this_thread = all_threads[b];
    var subject = this_thread.getFirstMessageSubject();
    var messages = this_thread.getMessages();
    for(var c=0; c<messages.length; c++)
   {
      var this_message = messages[c];
      var from = this_message.getFrom();
      var to = this_message.getTo();

      Logger.log('Message from'+from+ ' and message to ' +to);
    }
   }
}

Now I want to read or search all emails sent by a particular person. For example, I have taken this email ID from my emails called [email protected]. We will create a function to fetch all emails of this email ID based on search.

function get_all_emails_based_on_search(){
  var srch = 'from:[email protected]';
  var thr = GmailApp.search(srch);
   for(var c=0; c<thr.length; c++)
   {
        var sub = thr[c].getFirstMessageSubject();
        Logger.log(sub);
   }

}

techfixxo Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *