Last active
August 24, 2022 12:32
-
-
Save alexx855/a30420897de02bb55062290b13ba1cf3 to your computer and use it in GitHub Desktop.
Google Form Script, send email with attachment from drive on submit
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
function onFormSubmit( e ) { | |
const values = e.namedValues; | |
//e.values is an array of form values | |
const fecha = e.values[ 0 ]; | |
const email = e.values[ 1 ]; | |
//file is the template file, and you get it by ID | |
const file = DriveApp.getFileById( | |
'FILE_ID' | |
); | |
//We can make a copy of the template, name it, and optionally tell it what folder to live in | |
//file.makeCopy will return a Google Drive file object | |
const folder = DriveApp.getFolderById( 'FOLDER_ID' ); | |
const copy = file.makeCopy( email + ' - ' + fecha, folder ); | |
//Once we've got the new file created, we need to open it as a document by using its ID | |
const doc = DocumentApp.openById( copy.getId() ); | |
//Since everything we need to change is in the body, we need to get that | |
const body = doc.getBody(); | |
//Then we call all of our replaceText methods | |
body.replaceText( '{{Date}}', date ); | |
let htmlBody = '<ul>'; | |
for ( const key in values ) { | |
const label = key; | |
const data = values[ key ]; | |
htmlBody += '<li><strong>' + label + '</strong>: ' + data + '</li>'; | |
body.replaceText( '{{' + label + '}}', data ); | |
} | |
htmlBody += '</ul>'; | |
//Lastly we save and close the document to persist our changes | |
doc.getAs( 'application/pdf' ).setName( doc.getName() + '.pdf' ); | |
doc.saveAndClose(); | |
const docAsPDF = DriveApp.getFileById( copy.getId() ); | |
GmailApp.sendEmail( email, 'TITLE', 'TITLE', { | |
htmlBody, | |
attachments: [ docAsPDF.getAs( MimeType.PDF ) ], | |
} ); | |
} | |
function onEdit( e ) { | |
const formID = ''; | |
const ssID = ''; | |
const wsData = SpreadsheetApp.openById( ssID ).getSheetByName( 'emails' ); | |
const form = FormApp.openById( formID ); | |
const emails = wsData | |
.getRange( 2, 1, wsData.getLastRow() ) | |
.getValues() | |
.join( '|' ) | |
.slice( 0, -1 ); | |
const items = form.getItems(); | |
const itemId = items[ 0 ].getId(); | |
const emailItem = form.getItemById( itemId ).asTextItem(); | |
// Logger.log(emailItem.getTitle(), emailItem.getType()); | |
const emailValidation = FormApp.createTextValidation() | |
.requireTextMatchesPattern( emails ) | |
.build(); | |
emailItem.setValidation( emailValidation ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment