Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save danielcranney/73eff9fe5b79984718844114f63659c0 to your computer and use it in GitHub Desktop.
Save danielcranney/73eff9fe5b79984718844114f63659c0 to your computer and use it in GitHub Desktop.
newsletter unsubscription tracker / 09 - logUnsubscribes() complete code.js
// Logs emails from threads labeled "unsubscribed" to a Google Sheet
function logUnsubscribes() {
var label = GmailApp.getUserLabelByName('unsubscribed');
var threads = label.getThreads();
var sheet = SpreadsheetApp.open(DriveApp.getFileById('1v77gBSUzF7evN5Rlnvsz27LgoHgowiLivPpAGeTMgBQ'));
threads.forEach(function(thread) {
var messages = thread.getMessages();
messages.forEach(function(message) {
var body = message.getBody();
var email = extractEmail(body);
if (email && !isAlreadyLogged(email, sheet)) {
sheet.appendRow([email, new Date()]);
}
});
thread.removeLabel(label); // Remove the "Unsubscribed" label to avoid duplicates
});
}
// Helper function to extract the first email address found in a given text
function extractEmail(body) {
var emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
var match = body.match(emailPattern);
return match ? match[0] : null;
}
// Helper function to check if an email is already in the sheet
function isAlreadyLogged(email, sheet) {
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
if (data[i][0] === email) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment