Skip to content

Instantly share code, notes, and snippets.

@incognitosj
Created January 8, 2017 14:16
Show Gist options
  • Save incognitosj/a6db55224ca8d72f4ea171b625a2b1d6 to your computer and use it in GitHub Desktop.
Save incognitosj/a6db55224ca8d72f4ea171b625a2b1d6 to your computer and use it in GitHub Desktop.
Read all emails from a Gmail Label, parse using Regex and store it to a Google Spreadsheet
/**
* method for parsing the data
**/
function parseEmail() {
var emails = readGmailLabel("your label here");
var parsedData = [];
var data, parsedRegex;
for (var i = 0; i < emails.length; i++) {
data = []
// extract order number
parsedRegex = extractDate(emails.body, "2Checkout.com Order Number : ([0-9]+)");
data.push(parsedRegex[1]);
// extract total payment
parsedRegex = extractDate(emails.body, "Base Price : ([(0-9)|\.]+)");
data.push(parsedRegex[1]);
// extract more data as needed
parsedData.push(data);
}
// write this data (parsedData) to the spreadsheet
}
/**
* label: gmail label to be read
**/
function readGmailLabel(label) {
var emails = [];
var label = GmailApp.getUserLabelByName(label);
var threads = label.getThreads();
for (var j = threads.length - 1; j >= 0; j--) {
emails.push({
body: threads[j].getMessages()[0].getPlainBody(),
date: threads[j].getMessages()[0].getDate()
});
}
label.removeFromThreads(threads);
return emails;
}
/**
* text: data from which data needs to be parsed
* regularExpression: Regular expression
**/
function extractData(text, regularExpression) {
var regex = new RegExp(regularExpression);
var res = body.match(regex);
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment