I've been working to automatically pull data from an automated Gmail message. There are multiple daily emails that come through with the same label, so ideally I would like to loop through each email, and extract some of the data. I've set it up to use a few regex to grab the data, and it works for the first email. However, it won't loop correctly to find the next email with the label. Here is the code I have so far:
function parseEmailMessages (start) {
var label = GmailApp.getUserLabelByName("Bounce");
var threads = label.getThreads();
var sheet = SpreadsheetApp.getActiveSheet();
var tmp = [];
var messages = GmailApp.getMessagesForThreads(threads);
var bodies = [];
for (var i =0; i < threads.length; i++) {
var bodies = [];
for(k in threads[i].getMessages()) {
bodies.push(threads[i].getMessages()[i].getPlainBody());
var content = bodies.toString();
if (content) {
tmp = content.match(/[\n\r].*First Name\s*:\s*([^\n\r]*)/);
var firstname = (tmp && tmp[1]) ? tmp[1].trim() : 'No username';
tmp = content.match(/[\n\r].*Last Name\s*:\s*([^\n\r]*)/);
var lastname = (tmp && tmp[1]) ? tmp[1].trim() : 'No Lastname';
tmp = content.match(/[\n\r].*Customer ID\s*:\s*([^\n\r]*)/);
var customerID = (tmp) ? tmp[1].trim() : 'No CustomerID';
tmp = content.match(/[\n\r].*Invoice\s*:\s*([^\n\r]*)/);
var invoice = (tmp) ? tmp[1].trim() : 'No Invoice';
sheet.appendRow([firstname, lastname, customerID, invoice]);
Logger.log([firstname,lastname, customerID, invoice]);
}
}
}
};
It loops through correctly the first time, and then gives me an error: TypeError: Cannot call method "getPlainBody" of undefined.
Any help would be greatly appreciated!