1

I am trying to automatically extract subject lines to a Google doc or spreadsheet. I found a basic example but don't know how to make this work.

function processInbox() {
    // get all threads in inbox
    var threads = GmailApp.getInboxThreads();
    for (var i = 0; i < threads.length; i++) {
        // get all messages in a given thread
        var messages = threads[i].getMessages();
        // iterate over each message
        for (var j = 0; j < messages.length; j++) {
            // log message subject
            Logger.log(messages[j].getSubject());
        }
    }
}
1
  • This doesn't look like Java. Isn't it JavaScript? Mar 16, 2015 at 19:23

2 Answers 2

2

This is Javascript, not Java. The script above gathers all your messages into a list, which is the right first step, but it won't write it to the sheet.

After that you'll need to add an additional function to write it out. If you're in a spreadsheet, you could use something like this. I've modified the above function to put the subjects into an array instead of logging them into the console, and having it return that array.

function processInbox() {
    var threads = GmailApp.getInboxThreads();
    var subjects = [[]];    

    for (var i = 0; i < threads.length; i++) {

        var messages = threads[i].getMessages();

        for (var j = 0; j < messages.length; j++) {

            subjects[j] = [messages[j].getSubject()];
        }
    }

    return subjects;
}

function writeOutSubjects() {

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheets()[0];

    var subjects = processInbox();
    var range = sheet.getRange(1,1,subjects.length,1);

    range.setValues(subjects);

};
0

You will need to use a method like setValue(). You need to get a reference to the spreadsheet, then the sheet to act upon, and then the range to set the value in.

Google Documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.