Google Apps Script: read text from a .txt file - email

After taking a look at the provided tutorial for sending emails from a spreadsheet with Google Apps Script, I modified the given code with aims to be able to send the set of emails out with attachments as well.
It works well enough, even with a couple quirks from the limitations of Google Apps Script (the files have to be in the Google Drive, and all files in the Google Drive with whichever name is appropriate are taken from all folders in the drive).
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 1; // Number of rows to process
// Fetch the range of cells A2:C3
var dataRange = sheet.getRange(startRow, 1, numRows, 3)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var attachment = row[2]; // File name provided.
var subject = "Mass Email";
var files = DriveApp.getFilesByName(attachment); // Get all files with name.
var blobs = []; // Array for attachment.
// Move files into blobs
while (files.hasNext()) {
var file = files.next();
blobs.push(file.getAs(MimeType.PLAIN_TEXT));
}
MailApp.sendEmail(emailAddress, subject, message, {
attachments: blobs, // add attachments
cc: "extra#email.com" // CC to employer
});
}
}
After I first used it, however, I learned that I need to send the files not as attachments, but as the message body of the emails, among some other changes (this is for work). That is, I will only ever email one 'attachment' at a time to each email, and instead of that file being an attachment, its content should be copied over to the message of the email. The attachments are currently text files, and I'd like them to stay that way, but it isn't the most vital thing.
I cannot determine a way to do this with Google Apps Script. Is this possible, or will I have to have a different way of emailing these files? (Hopefully not by hand.)

Try this. It's more faster and simpler.
var docContent = file.getBlob().getDataAsString();
Logger.log(docContent);

as mentioned in my last comment, converting your .txt files to Google documents makes it easy to achieve.
see below (suggestion)
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 1; // Number of rows to process
// Fetch the range of cells A2:C3
var dataRange = sheet.getRange(startRow, 1, numRows, 3)
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
Logger.log(row)
var emailAddress = row[0]; // First column
var message = row[1]; // Second column
var attachment = row[2]; // File name provided.
var subject = "Mass Email";
var files = DriveApp.getFilesByName(attachment); // Get all files with name.
while (files.hasNext()) {
var file = files.next();
var Id = file.getId();
var content = DocumentApp.openById(Id).getBody().getText();
Logger.log(content)
MailApp.sendEmail(emailAddress, subject, message+'\n'+content)
}
}
}

Related

onFormSubmit(e) I need to sum 4 columns and output to a PDF

This seems like a simple problem, add 4 Form Event columns(Cost 1, Cost 2, Cost 3, Cost 4) and output calculated 'Total' to a PDF via email utilizing a template. I have no problem getting the Event(e) data to the template and sent via email but cannot get the total. I've tried many different Google App Scripts from this site to no avail. Currently, I have a separate sheet called 'Total' and created an array that captures the Event data columns and displays exactly what I want but I cannot get it to the template, problem code may be on line 20. I've included links to the template as well as the Spreadsheet and the Google App Script
// Get template from Google Docs and name it
var docTemplate = "1Ti1n71wpA-U5X9yLqSIfLC9VXqcxOGGsZQhYq0ZwJX4"; // *** replace with your template ID ***
var docName = "Calculate the total";
// When Form Gets submitted
function onFormSubmit(e) {
var name = "Rick"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Total'); //Get 'Total' sheet
var row = sheet.getLastRow(); //Get 'Total' last row
//Get information from form and set as variables
var todaysDate = Utilities.formatDate(new Date(), "CST", "MM/dd/yyyy, hh:mm");
var email_address = "MyEmail address";
var cost1 = e.values[1];
var cost2 = e.values[2];
var cost3 = e.values[3];
var cost4 = e.values[4];
var total = sheet.getRange(row, [1]).getValue(); //Is this the problem?
// Logger.log(e.namedValues);
// Get document template, copy it as a new temp doc, and save the Documents ID
var copyId = DriveApp.getFileById (docTemplate)
.makeCopy(docName + ' for '+ name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the documents body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('<<name>>', name);
copyBody.replaceText('<<cost1>>', cost1);
copyBody.replaceText('<<cost2>>', cost2);
copyBody.replaceText('<<cost3>>', cost3);
copyBody.replaceText('<<cost4>>', cost4);
copyBody.replaceText('<<total>>', total);
copyBody.replaceText('<<timeStamp>>', todaysDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "Your Total Cost Project Script";
var body = name + ", here is the total cost for your project ";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DriveApp.getFileById(copyId).setTrashed(true);
}
Spreadsheet - https://docs.google.com/spreadsheets/d/144t33X98eZIAH2k5hCA--fFeUzmJCGefKI7lC1EE4Xc/edit?usp=sharing
Template - https://docs.google.com/document/d/1Ti1n71wpA-U5X9yLqSIfLC9VXqcxOGGsZQhYq0ZwJX4/edit?usp=sharing

I want to use the content of a cell in a google sheet to control whether to send an e-mail out or not

I have a spreadsheet for recording customer samples. A column [I] is used to calculate when the original entry date is over a certain period which then displays an overdue message using an if statement. I want to trigger a script to check this column daily and if 'overdue' is found to send an email to an address contained in another column [C]. I am also using another column [J] to return a message when an email has been sent. I am using the script below but am returning errors
The script marks all rows in column J with the sent email message
I appear to be collecting a bigger array of data have needed [adding two rows the the bottom]
Anyone any ideas?
//Setup the function
function autoMail () {
var ss = SpreadsheetApp.getActiveSpreadsheet(); //Get the active spreadsheet
var sheet = ss.getSheetByName( 'TS_Requests' ); //Get the active spread
var startRow = 3; // Start of row that going to be process considering row 2 is header
var lastRow = sheet.getLastRow(); // Get the last row of data to be process
var lastColumn = sheet.getLastColumn(); // Get the last column of data to be process
var range = sheet.getRange(startRow,1,lastRow,lastColumn); //Getting the specific cell to be process
var data = range.getValues(); // Get the values inside the cell
for(var i=0;i<data.length;++i){
var row = data[i];
var email = row[2]; // Grab the email column. C in this case
var customer = row[3]; // Grab data for Email body
var item = row[5]; // Grab data for Email body
var description = row[6]; // Grab data for Email body
var status = row[8]; // Grab the column containing the value needed to be checked.
var EmailSent = row[9]
if (EmailSent != 'Email_Sent') { //Prevents e-mail being sent in duplicate
if(valstatus ='Overdue'){ // Check the values, if it's what's needed, do something
MailApp.sendEmail(email, 'Your sample request is overdue', customer + ' - ' + item + ' - ' + description); // if condition is met, send email
sheet.getRange(startRow + i, 10).setValue('Email_Sent');
}
}
}
}

Reformatting row contents for an emailed Google Forms response

I have a private Google Form that I use to quote clients.
The form data is emailed after clicking on the submit button; the trigger is set up and the email successfully sends, but the rows and columns are not separate as it is in the form.
Data is sent like this (just a snap):
,Once signed, please Fax, mail or e-mail it to the provided address.,,,,,,,,,,Above information is not an invoice and only an estimate of services/goods described above.,,P
The form values should be separated row by row, is that possible?
This is my Google Apps Script:
function mail() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 1;
var numRows = 56;
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
var data = dataRange.getValues();
var row = data;
var emailAddress = '******#gmail.com';
var subject = "Subject...";
var message = row;
MailApp.sendEmail(emailAddress, subject, message)
}
//1(R1),1(C1),55(R1),11(C1

How to send e-mails automatically from a sheet as it updated?

I posted this question on Google Sheets forum and was directed here for help.
*Please note that I am not a coder, I've just started working with things like this.
I've created a workbook with 3 pages. It's connected to a form, so as people submit their reviews the answers are collected on the first sheet, calculated on the second sheet, and any submission with an overall score higher than 3.9 has the email address moved to the third sheet where it will be sent a follow-up email.
Here is a link to a copy of the sheet:
https://docs.google.com/spreadsheets/d/15p7_M4guRWCVHG-acRAheAROmh9t4wk3GWD_x0_rl90/edit?usp=sharing
It all works except the last page: I cannot figure out how to get the emails to send automatically as the sheet is updated. I've set the trigger to have it run when the sheet is updated, but to no avail - I have to manually go in and click the "Run" button to have the emails sent. (When I do, it pops up 'Failed to sent email: no recipient (line 21, file "Code")' but the emails are successfully delivered anyway.)
The formula I am using is this: (I have also tried swapping "sendEmails2" with "autoResponder" but that didn't change anything either.) Can anyone tell me what is wrong with it? Or is there a better way to automatically send the e-mails?
// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 20000; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3)
// 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 message = row[1]; // Second column
var emailSent = row[2]; // Third column
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is
interrupted
SpreadsheetApp.flush();
}
}
}
This should do it:
function sendEmails2(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Automatic Emails');
var rg=sh.getRange(2,1,sh.getLastRow(), 3);
var vA=rg.getValues();
for (var i=0;i<vA.length;i++){
var emailAddress = vA[i][0];
var message = vA[i][1];
var emailSent = vA[i][2];
var subject = "Sending emails from a Spreadsheet";
if(emailSent != 'EMAIL_SENT'){
MailApp.sendEmail(emailAddress, subject, message);
sh.getRange(2 + i,3).setValue('EMAIL_SENT');
}
}
}
Don't forget the onFormSubmit:

Send email from google spreadsheet

I found the following script to insert form submission values into a google spreadsheet.
function doPost(e) { // change to doPost(e) if you are recieving POST data
var ss = SpreadsheetApp.openById(ScriptProperties.getProperty('active'));
var sheet = ss.getSheetByName("DATA");
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; //read headers
var headers2 = sheet.getRange(2, 1, 1, sheet.getLastColumn()).getValues()[0]; //read headers
var nextRow = sheet.getLastRow(); // get next row
var cell = sheet.getRange('a1');
var col = 0;
for (i in headers2){ // loop through the headers and if a parameter name matches the header name insert the value
if (headers2[i] == "Timestamp"){
val = new Date();
} else {
val = e.parameter[headers2[i]];
}
cell.offset(nextRow, col).setValue(val);
col++;
}
//http://www.google.com/support/forum/p/apps-script/thread?tid=04d9d3d4922b8bfb&hl=en
var app = UiApp.createApplication(); // included this part for debugging so you can see what data is coming in
var panel = app.createVerticalPanel();
for( p in e.parameters){
panel.add(app.createLabel(p +" "+e.parameters[p]));
}
app.add(panel);
return app;
}
//http://www.google.sc/support/forum/p/apps-script/thread?tid=345591f349a25cb4&hl=en
function setUp() {
ScriptProperties.setProperty('active', SpreadsheetApp.getActiveSpreadsheet().getId());
}
Now I want to send a formatted email to two of my coworkers every time a row gets inserted. I tried to use:
var emailAddress = "email#gmail.com"; // First column
var message = "message"; // Second column
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
but it's not sending anything.. can anyone advise please?
I had the same trouble.
With the most recent version of Google Apps I had to save the script, create a new revision, and re-publish the script making sure to select the new revision. After this the new code was in effect. I wasted several hours in the belief that the script would be updated if I just saved it.
Somehow the new method saves the script elsewhere. It's almost impossible to tell what code is actually running unless you go through the process of saving a revision, and re-publishing.