I put together a Google Apps Script to pull some data from my emails and insert it into a spreadsheet. The script is actually running great and inserting the data fine, but I keep getting the following error in my log:
TypeError: Cannot read property 1 from null. (line 46, file Code)
According to MDN, the exec
method returns an array with the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured. Since I want the value within the parenthesis of my regex, rather than the entire matched text, I'm using [1]
.
Here's the function in question:
function getEmails() {
var label = GmailApp.getUserLabelByName(CapitalOne Transaction);
var threads = label.getThreads(); // Get threads of label above
for (var i in threads) {
var messages = threads[i].getMessages();
for (var j in messages) {
if ( messages[j].isUnread() ) {
var emailBody = messages[j].getPlainBody();
Logger.log(Email body: + emailBody);
// Get account number
const regExpAcct = /Account ending in (d{4})/g;
var message_account = regExpAcct.exec(emailBody);
if(message_account){ Logger.log(Email message accnt: + message_account[1]); }
// Get date of transaction
var regExpDate = /we're notifying you that on (...+), at/g;
var message_date = regExpDate.exec(emailBody);
if(message_date){ Logger.log(Email message date: + message_date[1]); }
// Get vendor name
var regExpVendor = /, at (...+),/g;
var message_vendor = regExpVendor.exec(emailBody);
if(message_vendor){ Logger.log(Email message vendor: + message_vendor[1]); }
// Get transaction amount
const regExpAmount = /purchase in the amount of $(S+) was/g;
var message_amount = regExpAmount.exec(emailBody);
if(message_amount){ Logger.log(Email message amount: + message_amount[1]); }
addDataToSpreadsheet( message_date[1], message_account[1], message_vendor[1], message_amount[1] );
messages[j].markRead();
}
}
}
}
The line(46) in question is this one: addDataToSpreadsheet( message_date[1], message_account[1], message_vendor[1], message_amount[1] );
Which calls this function:
function addDataToSpreadsheet( date, account, vendor, amount ) {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow( [date, account, vendor, amount] );
}
My Logger.log
s after each regex all output the variables fine, and like I said, the data is being input into the spreadsheet perfectly with the function above, but I still get the error every time the getEmails()
function runs.
Any ideas why?