Bob
Bob

Reputation: 289

Trying to understand getThreads in GAS

I am new to app script and I am trying to read an email from my inbox. I thought that getThreads would do the job but I still don't fully understand how to use it. When I try to execute the code I wrote below it comes up with a null error.

Looking at the documentation of getThreads(), they use the example:

 // Log the subject lines of the threads labeled with MyLabel
 var label = GmailApp.getUserLabelByName("MyLabel");
 var threads = label.getThreads();
 for (var i = 0; i < threads.length; i++) {
   Logger.log(threads[i].getFirstMessageSubject());
 }

what does "MyLabel" stand for?

This is the code i tried that failed

function myFunction() {


   var label = GmailApp.getUserLabelByName('[email protected]');
   var threads = label.getThreads();


     for (var t in threads) {
       var thread = threads[t];

    // Gets the message body
       var message = thread.getMessages()[0].getPlainBody();
     }

  GmailApp.sendEmail('[email protected]', 'hola', message)
}

Upvotes: 0

Views: 965

Answers (1)

JScripto
JScripto

Reputation: 19

MyLabel is the label of the email. It depends whether you added a label to a specific email or not. You can use the search method instead.

function myFunction(){
   var label = 'yourLabel'; // if no label, remove the label in search
   // it would be better if you add a label to a specific email for fast and more precise searching
   var searchEmail = GmailApp.search('from:me subject:"' + subject + '" label:' + label + '');
   var threadId = searchEmail[0].getId(); // get the id of the search email
   var thread = GmailApp.getThreadById(threadId); // get email thread using the threadId
   var emailMsg = thread.getMessages()[0]; // get the content of the email
   var emailContent = emailMsg.getPlainBody(); // get the body of the email
   // check using log
   Logger.log(emailContent);
   // how to open log
   // Ctrl + Enter
   // Run this function before checking the log
}

Thanks

Upvotes: 2

Related Questions