Skip to content

Instantly share code, notes, and snippets.

@sony-mathew
Last active May 21, 2020 17:31
Show Gist options
  • Save sony-mathew/dadbec41733a0169068132a6761b5bbe to your computer and use it in GitHub Desktop.
Save sony-mathew/dadbec41733a0169068132a6761b5bbe to your computer and use it in GitHub Desktop.
Google app script function to send emails from a spreadsheet.
/*
Structure of the spreadsheet
Email Name Sending Status Email Send Date Source Lead Created Date Current Status
memev20935@aprimail.com Sony Mathew EMAIL_SENT Thu, 21 May 2020 08:20:37 GMT EMAIL_SENT
*/
// All Contants here
var SPREADSHEET_URL = 'https://docs.google.com/spreadsheets/d/some-random-long-id/edit#gid=0';
var EMAIL_SENT = 'EMAIL_SENT';
var DO_NOT_SEND = 'DO_NOT_SEND';
var MAIL_SUBJECT = "{{firstName}}, Hi from Company";
var MAIL_TEMPLATE = "<b>Hello</b> {{firstName}}";
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmailsFromSpreadSheet() {
var spreadSheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
Logger.log(spreadSheet.getName());
var sheet = spreadSheet.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 5000; // Number of rows to process
// Fetch the range
var dataRange = sheet.getRange(startRow, 1, numRows, 7);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0]; // First column
var fullName = row[1]; // Second column
var sendStatus = row[2]; // Third column
// Prevents sending duplicates
if (sendStatus !== EMAIL_SENT && sendStatus !== DO_NOT_SEND && !!emailAddress) {
var person = personObject(emailAddress, fullName);
var mail = mailObject(person);
MailApp.sendEmail({
to: person.email,
subject: mail.subject,
htmlBody: mail.content
});
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
sheet.getRange(startRow + i, 7).setValue(EMAIL_SENT);
sheet.getRange(startRow + i, 4).setValue((new Date).toGMTString());
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
function personObject(email, fullName) {
return {
email: email,
firstName: fullName.split(' ').slice(0, -1).join(' '),
lastName: fullName.split(' ').slice(-1).join(' ')
};
}
function mailObject(person) {
return {
subject: MAIL_SUBJECT.replace("{{firstName}}", person.firstName).replace("{{lastName}}", person.lastName),
content: MAIL_TEMPLATE.replace("{{firstName}}", person.firstName).replace("{{lastName}}", person.lastName),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment