Skip to content

Instantly share code, notes, and snippets.

@negezor
Created March 18, 2022 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save negezor/d51133e416f8b396f8b2e680d415aebe to your computer and use it in GitHub Desktop.
Save negezor/d51133e416f8b396f8b2e680d415aebe to your computer and use it in GitHub Desktop.
Serverless email saving with Google Apps Script in Google Sheets

Setup steps

  • Create a new Google Sheets document
  • Rename the list 1 to collect (name can be changed to your own)
  • Optionally describe the first column as email and the second column as subscription date
  • Open Add-ons » Apps Script
  • Paste the extension code into the editor
  • Click deploy at the top
  • Deploy as a web application
  • Copy macro link
  • Send a POST application/x-www-form-urlencoded request with an email field
  • I'm proud of you
function doPost(e) {
try {
Logger.log(e);
const email = e.parameter.email.toLowerCase().trim();
if (email.indexOf('@') === -1) {
throw new Error('It\'s not email');
}
const doc = SpreadsheetApp.getActiveSpreadsheet();
const sheet = doc.getSheetByName("collect");
for (const values of sheet.getDataRange().getValues()) {
if (values[0] !== email) {
continue;
}
return ContentService.createTextOutput()
.setMimeType(ContentService.MimeType.JSON)
.setContent(JSON.stringify({
success: true,
code: 'DUPLICATE'
}));
}
sheet.appendRow([email, (new Date()).toISOString()]);
return ContentService.createTextOutput()
.setMimeType(ContentService.MimeType.JSON)
.setContent(JSON.stringify({
success: true
}));
} catch (error) {
Logger.log('Failed hanle post');
Logger.log(error);
return ContentService.createTextOutput()
.setMimeType(ContentService.MimeType.JSON)
.setContent(JSON.stringify({
success: false
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment