Continuing from Google Apps Script to extract data from Gmail and fill in matching row in Google Sheets , there is another email which contains multiple tracking numbers in a single email. Example...
Your order is ready to be redeemed/ delivered.
Order No. 91401111
Tracking No. (Actual Weight/Chargeable Weight) JK5SD8F4M6 (2.1lb)
J6HDO9L665 (2.1lb)
J3SDG76435 (9.8lb)
Courier UPS
Shipment No. 23879924905
I would like to extract the data in the email and fill in the correct cells such as this...
Currently, the script is like this...
function extractDetails(message){
var emailData = {
body: "Null",
trackingno: "Null",
weight: "Null",
orderno: "Null",
courier: "Null",
shipmentno: "Null"
}
emailData.body = message.getPlainBody();
emailData.trackingno = emailData.body.match(/(?<=Tracking No. \(Actual Weight/Chargeable Weight\) ).*/).toString().trim();
emailData.weight = emailData.body.match(/????????/).toString().trim();
emailData.orderno = emailData.body.match(/(?<=Order No. ).*/).toString().trim();
emailData.courier = emailData.body.match(/(?<=Courier ).*/).toString().trim();
emailData.shipmentno = emailData.body.match(/(?<=Shipment No. ).*/).toString().trim();
var activeSheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = activeSheet.getSheetByName('Sheet1');
var range = sheet.getRange("A2:A" + sheet.getLastRow()).createTextFinder(emailData.trackingno).findNext();
if (range) {
range.offset(0, 3).setValue(emailData.weight);
range.offset(0, 4).setValue(emailData.orderno);
range.offset(0, 5).setValue(emailData.courier);
range.offset(0, 6).setValue(emailData.shipmentno);
} else {
sheet.appendRow([emailData.trackingno, '', '', emailData.weight, emailData.orderno, emailData.courier, emailData.shipmentno]);
}
}
I know there are few errors in the above script. First, I have no idea how to write the regex to find the weight. Then, I don't know how to extract all tracking numbers. I should probably store the extracted the tracking numbers in an array and then do the matching using for loop. Please help. Thanks.
