Created
June 23, 2021 13:16
-
-
Save ninokierulf/b2150db3212e5f36147bcd9f1e7ed91d to your computer and use it in GitHub Desktop.
google forms send email with codes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This function will be called everytime the form is submitted. | |
function onFormSubmit(event) { | |
sendAutomatedEmail() | |
} | |
function sendAutomatedEmail() { | |
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1").activate(); | |
var responsesheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // Get main Database Sheet | |
var emailsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2"); // Get Sheet with the Email Content | |
var promocodesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PromoCodes"); | |
var lastResponseRow = responsesheet.getLastRow(); // User which last filled the form | |
var promocodeTakenCol = getPromoCodesTakenCol() | |
var availablePromoRow = getFirstEmptyRowByColumnArray(promocodeTakenCol) | |
var name = responsesheet.getRange(lastResponseRow, 2).getValue(); | |
var email = responsesheet.getRange(lastResponseRow, 4).getValue(); | |
var subject = "Thank you!"; | |
var duplicateEmailRow = getRowMatchingText(email, promocodeTakenCol) | |
var promoRow = availablePromoRow | |
if (duplicateEmailRow >= 0) { | |
promoRow = duplicateEmailRow | |
} | |
var availablepromocode = promocodesheet.getRange(promoRow, 1).getValue(); | |
var body = emailsheet.getRange(1, 1).getValue(); | |
body = body.replace("{name}", name); | |
body = body.replace("{promo_code}", availablepromocode); | |
try { | |
MailApp.sendEmail(email, subject, body); | |
promocodesheet.getRange(promoRow, 2).setValue(email) | |
} | |
catch(e) { | |
Logger("Failed: Sending email to" + email) | |
} | |
} | |
// returns column B (email addresses) values of PromoCodes | |
function getPromoCodesTakenCol() { | |
var spr = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PromoCodes"); | |
var column = spr.getRange('B:B'); | |
var values = column.getValues(); | |
return values | |
} | |
function getRowMatchingText(text, columnValues) { | |
var values = columnValues; | |
for(var i = 0; i<values.length;i++){ | |
if((values[i][0]+"").toUpperCase() === text.toUpperCase()) { | |
return i+1; | |
} | |
} | |
return -1 | |
} | |
// Don's array approach - checks first column only | |
// With added stopping condition & correct result. | |
// From answer https://stackoverflow.com/a/9102463/1677912 | |
function getFirstEmptyRowByColumnArray(columnValues) { | |
var values = columnValues; | |
var ct = 0; | |
while ( values[ct] && values[ct][0] != "" ) { | |
ct++; | |
} | |
return (ct+1); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment