I get automated emails from another system (Bananatag) and am trying to create a Google Apps Script
(GAS
) to extract specific information from the email. I have started creating the following code:
function fieldExtract(){
var threads = GmailApp.search('from:noreply@bananatag.com');
for(var m in threads){
var messages = threads[m].getMessages(),
tid = threads[m].getId();
for(var b in messages){
var body = messages[b].getPlainBody(),
subj = messages[b].getSubject();
var CountryExpression = new RegExp("[\n\r].*Country:\s(.*)","g");
var RegionExpression = new RegExp("[\n\r].*Region:\s(.*)","g"),
CityExpression = new RegExp("[\n\r].*City:\s(.*)","g"),
OSExpression = new RegExp("[\n\r].*OS:\s(.*)","g"),
DeviceExpression = new RegExp("[\n\r].*Device:\s(.*)","g"),
ClientExpression = new RegExp("[\n\r].*Client:\s(.*)","g"),
subjExpression = new RegExp("'\s*(.*?)\s*'","g");
var subject = subjExpression.exec(subj);
var country = CountryExpression.exec(body)[1];
}
}
}
The email body contains information like this:
Email Open Notification
-----------------------------------------------
EMAIL DETAILS
-----------------------------------------------
Subject: Re: FW: Payment confirmation: Invoice 1540
Sent at: Tue 17 Jan 2017 03:27:27 PM MST
RECIPIENTS:
Name: {name}
Email: {email}
-----------------------------------------------
View full details at:
https://member.bananatag.com/tag/xxxxxxx
-----------------------------------------------
OPEN DETAILS
-----------------------------------------------
LOCATION:
Country: United States
Region: WA
City: Unknown
ADDITIONAL INFORMATION:
OS: Windows 8
Device: Desktop
Browser/Client: Outlook 2010
Ok
When I test my RegEx
on some testing sites like regex101, it correctly finds the text that I want. But, when I run it in GAS
it throws this error:
TypeError: Cannot read property "1" from null. (line 44, file "Email-management")
Line 44 is this line var country = CountryExpression.exec(body)[1];
.
If I leave off the [1]
it sets country
to null
. Why would GAS
fail to find the matching text when it definitely exists?
How do I make this work?
UPDATE
I changed the code to this:
var CountryExpression = /[\n\r].*Country:\s(.*)/g;
and it works now