Alternative or fix for "\n" in google script - email

First time I put up a question here (been searching before posting) so please bear with possible mistakes done on my end.
To the problem:
I am currently working on a website with google sites. Made some forms there and am adding a script to those forms to get the info input there emailed away once the form is submitted and saved on the spreadsheet, which works just fine, but the message inside the email that arrives is pretty messed up.
All the "\n" expressions in the code get simply ignored.
I got the base for the code from www.labnol.org and just edited it a little.
For the start, the code:
function sendFormByEmail(e)
{
//I took the two mail addresses out here, but they are working in the original
var email = "first mail address";
var email2 = "second mail address";
var subject = "New Announce your visit form submitted";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "A new 'Announce your visit' form has been submitted on the website: \n\n" + "\n\n";
for(var i in headers) {
message = message + "\n \n";
message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n";
}
var senderEmail = e.namedValues[headers[6]].toString();
MailApp.sendEmail(email, senderEmail, subject, message);
MailApp.sendEmail(email2, senderEmail, subject, message);
}
As you can see, I have been trying around a lot to place the \n in different places as alternative, though it gets ignored no matter where I place it.
the original loop looked like this:
for(var i in headers)
message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n";
Before I did some modifications to the code it worked just fine. But even though I didn't touch these lines, nor any of the other parts of the code that contribute to getting the message, the \n stopped working.
I kept trying to fix it (as the messed up \n placing above shows), but without success.
So now I am trying to find a way to fix them, or at least a work-around and hoped that any of you might know what is going on with the \n's or how to get them working again.
Thanks in advance.
ps: if you need any more information on it, just let me know

A solution is to use the GmailApp.sendEmail method instead of the MailApp.sendEmail method. The GmailApp's sendMail handles \n correctly.

Here's an alternate solution to what you're doing: HtmlTemplate
Some sample code:
function sendEmailWithTemplateExample() {
var t = HtmlService.createTemplateFromFile("body.html");
t.someValue = "some dynamic value";
var emailBody = t.evaluate().getContent();
MailApp.sendEmail("your#email.here", "test email", emailBody);
}
And here's the corresponding template code in body.html (Click "File -> New -> Html File"):
Body goes here
<?= someValue ?>

Related

Properly attaching pictures to an email with google scripts

I'm trying to make a script with google forms and sheets to help with the automation and tracking our technicians pictures on the jobsite.
The setup is they take pictures of the jobsite and fill out a google form with the information and attach the pictures there. When the form gets submitted, it runs this script to send an email to a predetermined email that everyone in the office can see.
So far I am able to get the email to send the information from the form besides the pictures.
The information for the attached pictures come in as a drive url that is all dumped into one cell as a string.
"https://drive.google.com/open?id=xxxxxxxx, https://drive.google.com/open?id=yyyyyyyy, https://drive.google.com/open?id=zzzzzzzz"
I convert this string to an array using .split(" ,) which outputs this.
[https://drive.google.com/open?id=xxxxxxxx, https://drive.google.com/open?id=yyyyyyyy, https://drive.google.com/open?id=zzzzzzzz]
I then iterate through the array and use.slice(33) to get rid of the url so all that I'm left with is the drive id (there is probably a better way of doing this but it works for now).
[xxxxxxxx, yyyyyyyy, zzzzzzzz]
This is the part where I'm having trouble.
I then iterate agian through that array and grab the driveID and the get the file as a JPEG.
I then use .push to put it into another array that I'm using to attachment them to the email.
The issue is that I think I'm not doing this step properly by not pushing the correct thing into the array and/or assuming that MailApp.sendEmail can even take an array for attachments.
I'm also not entirely sure how [Blobs] work and how to use them properly and that's probably where I'm getting stuck.
Again, this is code is made with very little experience and could probably be optimized futher but at the moment, I just need to have it attach the pictures properly to show that it works.
function onFormSubmit(e) {
//for testing purposes
var values = e.namedValues;
//gets the form's values
var pureValues = e.values;
//sets the values
var email = pureValues[1];
var woNum = pureValues[2];
var firstN = pureValues[3];
var lastN = pureValues[4];
var desc = pureValues[5];
var superDuperRawPics = pureValues[6];
//splits the picture urls into an array
var superRawPics = superDuperRawPics.split(", ");
//slices the url part off to get the drive ID
var i, rawPics =[]
for (i = 0; i < superRawPics.length; ++i) {
rawPics.push(superRawPics[i].slice(33))
}
//takes the array of ID's and gets the drive file
var j, picAttach =[]
for (j = 0; j < rawPics.length; ++j) {
var driveID = DriveApp.getFileById(rawPics[j]);
var drivePic = driveID.getAs(MimeType.JPEG);
picAttach.push(drivePic);
}
//sets the subject of the email to be Jobsite Pictures and the work number
var subject = "Jobsite Pictures" + " " + woNum;
//sets the body of the email
var body = "Technician: " + email + " \n" +
"WO#: " + woNum + " \n" +
"Customer: " + firstN + " " + lastN + " \n" +
"Description: " + desc;
//for checking if the vars are set correctly
Logger.log(superDuperRawPics);
Logger.log(superRawPics);
Logger.log(rawPics);
Logger.log(picAttach);
Logger.log(subject);
Logger.log(body);
//sends email to me with the new info
MailApp.sendEmail('example#domian.com', subject, body, {attachments: [picAttach]});
}
If you just want to attach them then use options attachments
I was being dumb and added brackets to the attachments: when it didn't need them.
The correct way is this.
MailApp.sendEmail('example#domian.com', subject, body, {attachments: picAttach});
Changing this has the script sending emails with the pictures attached.

How to get email form submissions script to exclude blank response values from sheet?

I am editing an existing script that my team uses for a google form response sheet. The script automatically creates a message body using the headers and response cells for an order every time it is submitted, roughly like this:
Type of Order: Physical
Country: America
Digital Signature:
Favorite Color:
Favorite Food: Pasta
What I've been asked to do, is have the script read through the sheet and not include the header or response for questions that are not answered in any given submission. Like so, for the previous example:
Type of Order: Physical
Country: America
Favorite Food: Pasta
I should start by saying I have close to 0 experience in javascript or Google Apps. I have tried playing around with if clauses using both the len function and a negated isblank function to no avail. These all lead to undefined errors.
As you'll see, the original script was not created by me or the people who have been using it for the last few years.
Original script
function sendFormByEmail(e)
{
Logger.log('value of e is: ' + e);
var email = "xxx#xxx.com";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
var subject = "Type A Request: ";
// The variable e holds all the form values in an array.
// Loop through the array and append values to the body.
// Insert variables from the spreadsheet into the subject.
// In this case, I wanted the new hire's name and start date in the
// email subject. These are the 3rd and 16th columns in my form.
for(var i in headers)
message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";
subject += e.namedValues[headers[10]].toString() + " - " +
e.namedValues[headers[12]].toString();
MailApp.sendEmail(email, subject, message, {noReply:true});
// Based off of a script originally posted by Amit Agarwal - www.labnol.org
}
You can include a check for blank values inside the for loop.
if (e.namedValues[headers[i]].toString() === "") continue;

google script column change email notification

This is my first attempt at writing any kind of script, and also posting a question.
I have created a google sheet, and I would like to send an e-mail notification every time a row is added in this spreadsheet (or to keep things simple, every time a new cell is populated in column A).
I've been searching these forums for a couple of hours, and put together the following script, and tried installing both "onedit" & "onchange" triggers in google scripts but nothing working.
The following links have been helpful, but still not able to get the result I want. No notification is being triggered at all automatically upon the relevant edits.
how to attach onChange cell value event/script to google sheet
email notification if cell is changed
//Open function
function sendNotification() {
//Get spreadsheet & sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Define notification details
var recipients = "myname#email.com";
var subject = "New lead";
var body = 'A new lead has been added to Simba. For message: ' + message + '';
//Specify several sheet variables
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var message = '';
//Specify if statement
if(cell.indexOf('A')!=-1){
message = sheet.getRange('B'+ sheet.getActiveCell().getRowIndex()).getValue()
}
//Send the Email
MailApp.sendEmail(recipients, subject, body);
//Close function
};
var body = 'A new lead has been added to Simba. For message: ' + message + '';
At this line, "message" is undefined. It occurs an error. By this error, mail cannot be sent. Because the definition of "message" is below from this line. So please change this line to below
message = sheet.getRange('B'+ sheet.getActiveCell().getRowIndex()).getValue()
And please install a trigger for this function. The method of installing trigger is shown at your reference URL.

Generate and send pdf through Google Forms to my email address - doesn't send, debugging to no assitance

I'm trying to send myself a form-based report as a pdf. The problem is, I don't receive any emails. Debugging doesn't help much, since that only tells me which values are "undefined" (they are being defined the instant one fills out the form and triggers the email by clicking send; in theory). My coding experience stems from the days of TurboPascal and .bat-files, and I have lately realised I need to shape up. Trying to figure out Android, and this is a little experiment at work. But I had forgotten the lost feeling of "what now?"...
Here's the code:
// Samfunnsutvikling kursrapport
var docTemplate = "TemplateIDinGoogleDoks";
var docName = "Kursrapport";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email = "worker#work.no";
var namn = e.namedvalues.namn;
var arrangement = e.namedvalues.arrangement;
var dato = e.namedvalues.dato;
var referat = e.namedvalues.referat;
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+namn)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keynamn', namn);
copyBody.replaceText('keyarrangement', arrangement);
copyBody.replaceText('keydato', dato);
copyBody.replaceText('keyreferat', referat);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "Kursrapport";
var body = "Kursrapporten frå " + namn + "";
GmailApp.sendEmail(email, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DocsList.getFileById(copyId).setTrashed(true);
}
The script/document is authorized to send emails, but, oddly, I had to authorize it twice. It is saved.
In general, you can add Logger.log() to print variable values or just messages to see how far does it reach.
It looks as attachments parameter expects Blob[] type, however you are passing just Blob. So, it should be:
GmailApp.sendEmail(email, subject, body, {htmlBody: body, attachments: [pdf]});
You may also want to replace DocsList with DriveApp class as-is since the first one is depricated.
Update
It turned out also that getActiveSection() was renamed to getBody().

google form script not triggering

I am trying to create a workflow in google forms. Its a simple leave application form that employees submit to get approval from their managers, HR, and finally management.
The form results feed into the google sheets as intended. i have written the following script in the form and later also in the sheet and set a trigger "on form submit". It worked fine last night and was able to sent the email confirmation i programmed into the script. For whatever reason it decided not to work today. Can someone tell me what they think went wrong? also is it best to create the script in the form or in the spreadsheet. My feeling is that in the spreadsheet might be better but i could be wrong. When the script did run last night, i am not sure which one worked (the one in the sheet or the one in the form). i only got one email for each test submission i made. here is the code:
function leaveProcessInput(e) {
var username = e.values [1];
var name = e.values [2];
var department = e.values [3];
var leaveType = e.values [4];
var fromDate = e.values [5];
var toDate = e.values [6];
var reason = e.values [7];
var releiver = e.values [8];
var contactAway = e.values [9];
var subject = "Your " + leaveType + "Application Form has been submitted";
var message = "Dear " + name + ", your " + leaveType + "from " + fromDate + "to " + toDate + "Application Form has been submitted at " + timestamp + ". You will be notified of its status once we have processed it. Regards, Finance & Admin team.";
MailApp.sendEmail(username, subject, message);
}
I would really appreciate help on the above.
this script (triggered on form submission) should be bound to the spreadsheet, not in the form.
I hope that solves it.
Try removing the spacing between 'e.values' and the [].
e.g. e.values [1] should be e.values[1]
The script should not be attached to the form, but only to the spreadsheet.