Skip to content

Instantly share code, notes, and snippets.

@donnfelker
Last active June 8, 2024 21:27
Show Gist options
  • Save donnfelker/be0fa5772cd0a8c6e2e763440c7a9473 to your computer and use it in GitHub Desktop.
Save donnfelker/be0fa5772cd0a8c6e2e763440c7a9473 to your computer and use it in GitHub Desktop.
Gmail Contacts from Label to Sheets
function getDailyQuota() {
var quotaRemaining = MailApp.getRemainingDailyQuota()
console.log("Daily Quota Remaining: " + quotaRemaining);
}
function getEmailsWithLabel() {
var label = GmailApp.getUserLabelByName("Recruiter");
var threads = label.getThreads();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = sheet.getLastRow();
var existingEmails = [];
// If we have existing emails in the sheet, grab those
if (lastRow > 1) {
existingEmails = sheet.getRange(2, 2, lastRow - 1).getValues().flat();
}
var newEmails = [];
sheet.clear(); // Clear existing content
sheet.appendRow(["Sender", "Email Address"]);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var from = messages[j].getFrom();
// Make sure the email matches this pattern, which is similar to <foo@bar.com>
var emailMatch = from.match(/<(.+)>/);
if (emailMatch) {
var email = emailMatch[1];
// Sometimes names have quotes in them, strip those. e.g. - Turn "Dave" into Dave
var sender = from.split("<")[0].trim().replace(/"/g, ""); // Remove quotes from sender name
// Only add unique emails to the sheet, not dupicates
if (!existingEmails.includes(email) && !newEmails.includes(email)) {
newEmails.push(email);
sheet.appendRow([sender, email]);
}
}
}
}
}
function sendContactEmails() {
var quoataRemaining = MailApp.getRemainingDailyQuota()
console.log("Remaining Daily Quota: " + quoataRemaining);
if (quoataRemaining > 0) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = sheet.getLastRow();
var data = sheet.getRange(2, 1, lastRow - 1, 2).getValues(); // Get email addresses and names
for (var i = 0; i < data.length; i++) {
var email = data[i][1];
var fullName = data[i][0];
var firstName = fullName.split(" ")[0]; // Extract first name
var personalizedName = firstName || "there";
var subject = "YOUR SUBJECT";
var body = 'Hello ' + personalizedName + ',\n\n' +
"Your engaging email contents here.\n\n" +
'Thanks,\n\n' +
'YOURNAME';
MailApp.sendEmail(email, subject, body);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment