Sending a file as e-mail attachment with Google Apps Script - google-apps-script

Is there a way to use file upload class and mailApp to select a (pdf) file from your computer (like this tutorial shows) and stores it only temporarily (maybe using cache memory) to send it as an email attachment?

the sample you refer to needs very few modifications to do what you want... the variable you get in the doPost is a blob, the argument needed in the attachment is a blob too so it is quite straightforward to put both together.
I only added a text on the button and a confirmation message when the mail is sent.
note that the file type will depend only on the filetype of the file, nowhere we convert it to pdf but that was not the point of your question.
if you upload a jpeg (for example) it will be a jpeg in the attachment of course !
code below with test on line:
function doGet(e) {
var app = UiApp.createApplication().setTitle("Upload CSV to Sheet");
var formContent = app.createVerticalPanel();
formContent.add(app.createFileUpload().setName('thefile'));
formContent.add(app.createSubmitButton('send'));
var form = app.createFormPanel();
form.add(formContent);
app.add(form);
return app;
}
function doPost(e) {
// data returned is a blob for FileUpload widget
var fileBlob = e.parameter.thefile;
MailApp.sendEmail(Session.getActiveUser(),'test pdf attachment','see attachment',{attachments: [fileBlob]});
var app = UiApp.getActiveApplication();
return app.add(app.createLabel('mail sent'));
}
test (asking for authorization)

var spreadsheetFile = DriveApp.getFileById(sheetId);
var blob = spreadsheetFile.getAs('application/pdf');
//if daysleft =1 or 0 then send mail .
MailApp.sendEmail(emailAddress, subject, message, {
name: 'Welcome mail- Perch Arbor Golf Course.pdf',
attachments: [blob]
});

Related

Can I send multiple uploaded attachments from a Google Form/Google Sheet in an automated email?

I am trying to create a Google Form linked to a Google Sheet utilizing some Google App script that will take some answers from a survey, attach an uploaded file, and send an email to a specific person. I have been able to figure out the part where I collect the data in a Google Sheet and send an email, but the part where I take the uploaded file and have it as an attachment in the email is stumping me.
Currently, my code to send the email looks like this:
GmailApp.sendEmail(Recipient,subject,'',{htmlBody: htmlText},);
But looking at the documentation on sendEmail, it looks like I want to add more to that Options part, right? The so if I am defining a variable for this, I need to use getFileById, but the file ID will be different with each upload. Furthermore, I might need to attach multiple files.
I have created a test Google Form here and I have attached it to a Google Sheet here. You can see the Google App Script here. You can check the email being sent/received successfully by looking at formtesting4#mailinator.com as specified in the code.
Is that possible with what I am trying to do?
You can refer to this sample script:
function emailMe() {
const ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const info = ss.getDataRange().getValues();
info.forEach((entry,a) => {
// Identify whether notification has been sent
if (entry[4] === '') {
// Collect entries
var Recipient = "your#email.com"
var subject = 'Roster Scheduler Update';
Timestamp = entry[0];
Name = entry[1];
Roster = entry[2];
attachment = "TEST";
var attachmentBlobs = [];
//Get the blob of all attachments available
if(entry[3]){
var attachments = entry[3].split(', ');
attachments.forEach(url => {
var fileId = url.replace('https://drive.google.com/open?id=','');
Logger.log(fileId);
var file = DriveApp.getFileById(fileId);
attachmentBlobs.push(file.getBlob());
});
}
let body = '';
// Generate email
var html = HtmlService.createTemplateFromFile("email.html");
var htmlText = html.evaluate().getContent();
// Send email
GmailApp.sendEmail(Recipient, subject, body, {htmlBody: htmlText, attachments: attachmentBlobs});
// Email confidence
const check = 'Sent';
ss.getRange(a + 1,5).setValue(check);
}
});
}
Changes done:
Get the blob file of all the uploaded attachments using File.getBlob(). You can get the file id from the attachment's url link and use DriveApp.getFileById(id)
Include body in the GmailApp.sendEmail() to fix email content issue
Include attachments as an option in the GmailApp.sendEmail(recipient, subject, body, options)
Output:
Sample1: 3 attachments
Sample2: 1 attachment

Get file from Google Drive based of Google Form info submission

I have created a Google Form containing two fields (First Name, Last Name)
I have PDF files in Google Drive/specific folder, PDF files named as "First Name"+"Last Name"
I want to get PDF file from my Google Drive based on form submission and get the URL to be sent by email.
I need the way to get PDF file based on form user submission.
I have written the below code which shall send the PDF as email attachment in place of the URL of PDF. I hope this code can help you. This code is a very basic code which can be further advanced as per your needs. Please let me know if you need any further help.
function pdfextractor() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Get active spreadsheet.
var lastrow = ss.getLastRow();
var sheetName = ss.getRange("B" + lastrow).getValue() + " " + ss.getRange("C" + lastrow).getValue(); //considering format 'FirstName LastName' stored in column B & C of spreasheet generated by submission of google forms.
var pdfName = sheetName + ".pdf";
ss.getRange("D" + lastrow).setValue(pdfName);
var files = DriveApp.getFilesByName(pdfName);
var body = "This is a test email";
var subject = "PDF File "
var email = "admin#gmail.com"
while (files.hasNext()) {
var file = files.next();
}
GmailApp.sendEmail(email, subject, body, {
attachments: [file]
});
}
You can also change the email of each mail you want to send if stored with the sheet.
One way to do it is to create trigger that fires when the form is submitted. Based on this event, you can get the responses from the form submission, use them to search the file in Drive and send it attached to an email.
Here's an example that you can adapt to build what you need:
function onSubmit(e) {
// Get submitted responses
let itemResponses = e.response.getItemResponses();
// Get form answers (assume the form has three question in this order: First Name, Last Name, Email)
let firstName = itemResponses[0].getResponse();
let lastName = itemResponses[1].getResponse();
let email = itemResponses[2].getResponse();
// Get file (first file found with specified name)
let searchResult = DriveApp.searchFiles(`title contains \'${firstName+lastName}\'`);
let respondentFile = searchResult.next();
if (!respondentFile) throw 'File not found';
// Send email with respondent's file
MailApp.sendEmail(email, 'Your PDF File', 'Your PDF file is attached.', {
name: 'Automatic Emailer Script',
attachments: [respondentFile.getAs(MimeType.PDF)]
});
}

Send File by File ID in Google Apps Script

I am using Google Sheets to store the list of file names in Google Drive, their respective File ID. I am using another sheet in the same workbook to record email addresses and file names that I want to send those email addresses.
I have a Sheet named Data with the following columns
File Name - Files stored on Google Drive
File ID - File ID of the file derived from the share link
I have another Sheet named Request with the following columns
File Name
Email Address
I want to fetch the File mentioned as the File Name mentioned in the Request sheet by looking up the corresponding File ID from the Data sheet for that file name. Once the file is fetched, I want to send that file as an attachment to the email address mentioned in the Request sheet. I want to do this for each row in the Request sheet.
I have created an HTML file named DocTemplate to constitute the body of the email.
I have written the below code in the script editor of Google Sheets. On running it, a mail is triggered but it does not contain the attachment nor does it include the content of the HTML file. The body of the mail just reads [object Object]
What am I doing wrong?
function sendfile(){
var request = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Request");
var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var Avals = request.getRange("A1:A").getValues();
var requestlastrow = Avals.filter(String).length;
var Avalsu = data.getRange("A1:A").getValues();
var datalastrow = Avalsu.filter(String).length;
for (var i=2;i<= requestlastrow;i++) {
var control = request.getRange(i,6).getValue();
if(control != 1){
var FilenameRequest = request.getRange(i,1).getValue();
for (var j=2;j<= datalastrow;j++) {
var FilenameData = upload.getRange(j,1).getValue();
if(FilenameRequest == FilenameData) {
/// to get the File ID
var FileID = data.getRange(j,2).getValue();
var file = DriveApp.getFileById(FileID);
/// to form the email
var values = request.getRange(i,1,1,2).getValues();
var rec = values[0];
var client =
{
email: rec[1],
name: rec[0]
};
client.subject = 'Request Filename:' + client.name;
var template = HtmlService
.createTemplateFromFile("DocTemplate.html");
template.client = client;
var message = template.evaluate().getContent();
MailApp.sendEmail(client.email,client.subject,{
htmlBody: message,
attachments: [file.getAs(MimeType.PDF)]
});
request.getRange(i,6).setValue("1");
}
}
}
}
}
Since this is not a reproducible example I can only assume that the rest of the code works except for this :
MailApp.sendEmail(client.email,client.subject,{
htmlBody: message,
attachments: [file.getAs(MimeType.PDF)]
});
It should also contain the message argument :
MailApp.sendEmail(client.email,client.subject,message,{
htmlBody: message,
attachments: [file.getAs(MimeType.PDF)]
});

Uploaad image button in google form

I created one google-form in that google-form i want user to upload their image. so i need a upload button to put their passport size image. i have written an separate code to upload image. where i can upload image the image comes and saved in drive. there are 2 pieces. i want this to merge or combine . i want to include a upload button image in the form and the uploaded image should come and save in the form spreadsheet. thanku
function doGet(e) {
var app = UiApp.createApplication().setTitle("Upload CSV to Sheet");
var form = app.createFormPanel().setId('frm').setEncoding('multipart/form-data');
var formContent = app.createVerticalPanel();
form.add(formContent);
formContent.add(app.createFileUpload().setName('thefile'));
formContent.add(app.createSubmitButton('Submit'));
app.add(form);
return app;
}
function doPost(e) {
// data returned is a blob for FileUpload widget
var fileBlob = e.parameter.thefile;
var doc = DocsList.createFile(fileBlob);
var app = UiApp.getActiveApplication();
//Display a confirmation message
var label = app.createLabel('file uploaded successfully');
app.add(label);
return app;
}
It's not possible to merge this function to a Google form.

Google Apps Script: create a pdf by editing response to google form

I'm hoping that someone can help me, What i want to do is to make a Google form create a new document and send that pdf via email when the form is edited.
I understand that when you edit a form the script inside a spreadsheet does not run, So i have put the script into a form and that is where i am having problems. I can not get the script to read the values that are been resubmitted on the form, it just keeps on coming up as "undefined" on the return
This is the script that i have got so far.
function Test(e) {
var form = FormApp.openById('****Form Key****'); //Enter Form ID here
var docTemplate = "***doc to be used***";
var docName = "***Name of document***";
var formResponse = form.getResponses();
var one = e.response; //I have tried e.value but does not pull through
var two = e.response; // Column 2
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('one', one);
copyBody.replaceText('two', two);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
//Sends the email
var email_Address = "***Email Address***"
var subject = "***Subject";
var body = "**Body***";
MailApp.sendEmail(email_Address, subject, body, {attachments: pdf});
}}
Any help will be greatly appreciated as i have been stuck on this for a while. thank you.
In a Form Response Trigger function, the event is an instance of Class FormResponse. Because of that, you don't need to open the form, or get responses... you've just had one handed to you, which you access via e.response. (See Form Response Events in Understanding Events.)
// Handle form response event
// This function must be a Form Response Trigger, attached to
// a Form (not a Spreadsheet).
function rightTest( e ) {
var formResponses = e.response.getItemResponses(); // array of responses
var one = formResponses[0];
var two = formResponses[1];
...
}
As of April 2015, DocsList is not supported, simply replace DocsList. with DriveApp. How to update DocsList to DriveApp in my code