Skip to content

Instantly share code, notes, and snippets.

@tzaffi
Last active April 6, 2016 18:26
Show Gist options
  • Save tzaffi/932b94076d8ea03242a5cff026f893d8 to your computer and use it in GitHub Desktop.
Save tzaffi/932b94076d8ea03242a5cff026f893d8 to your computer and use it in GitHub Desktop.
Add this to your sheet scripts to enable parsing through your SNS SES notifications and create a useful sheet for analyzing recipients, including bad ones.
/************
* Inspired by:
* https://ctrlq.org/code/20053-save-gmail-to-google-spreadsheet
* https://gist.github.com/oshliaer/70e04a67f1f5fd96a708
*************/
var IS_DEBUG = false;
var RUN_SIZE = 10; //this variable is ignored unless IS_DEBUG true
// Cf. https://developers.google.com/apps-script/reference/gmail/gmail-message#methods
var SEARCH_QUERY = 'from:no-reply@sns.amazonaws.com ';
function getEmails_(q) {
var runNum = 0;
var emails = [["Date", "SES Descriptive From", "Sender", "Delivery Status", "Subtype", "Recipients", "Thread labels", "SNS JSON"]];
var threads = GmailApp.search(q);
for (var i in threads) {
if(IS_DEBUG && runNum >= RUN_SIZE)
break;
var msgs = threads[i].getMessages();
var labelObjs = threads[i].getLabels();
var labels = "";
labelObjs.forEach(function(x,i){labels += (x.getName() + (i<labelObjs.length-1?',':'') )});
for (var j in msgs) {
try {
runNum++;
var msg = msgs[j];
if (msg.isInTrash())
continue;
var sesFrom = msg.getFrom();
var internalDate = msg.getDate();
var content = msg.getBody().replace(/<.*?>/g, '\n').replace(/^\s*\n/gm, '').replace(/^\s*/gm, '').replace(/\s*\n/gm, '\n').split("--")[0];
content = content.replace(/&quot;/g, '"');
var json = JSON.parse(content);
var sender = json.mail.source;
var notificationType = json.notificationType;
var recipients = JSON.stringify(json.mail.destination);
var subType;
if (notificationType === "Delivery"){
subType = "GTG"; //"good to go"
} else if (notificationType === "Bounce") {
subType = json.bounce.bounceType + ":" + json.bounce.bounceSubType;
} else { //Complaint
subType = json.complaint.complaintFeedbackType;
}
emails.push([internalDate, sesFrom, sender, notificationType, subType, recipients, labels, content]);
}
catch(err) {
Logger.log(JSON.stringify(err));
}
}
}
return emails;
}
function appendData_(sheet, array2d) {
sheet.getRange(sheet.getLastRow() + 1, 1, array2d.length, array2d[0].length).setValues(array2d);
}
function saveEmails() {
var array2d = getEmails_(SEARCH_QUERY);
if (array2d) {
appendData_(SpreadsheetApp.getActiveSheet(), array2d);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment