Google Apps Script sendEmail: multiple recipients string? - google-apps-script

Using sendEmail, how can I send an email to multiple comma-separated recipients by combining two form fields? It seems to work when (lastrow,4) has only one value (abc#domain.com) but not for more than one (abc#domain.com, xyz#domain.com). Current code is below, and the variable in question is recipientsTo.
function FormEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetform = ss.getSheetByName("Sheet1"); // Name of the sheet which contains the results
var lastrow = sheetform.getLastRow();
var recipientsTO = sheetform.getRange(lastrow,3).getValue() + "#domain.com";
var recipientsCC = ""
var team = sheetform.getRange(lastrow,5).getValue();
var datestamp = Utilities.formatDate(sheetform.getRange(lastrow,1).getValue(), "GMT - 5", "yyyy-MM-dd");
var html = "Intro text;
//The questions order in the email will be the order of the column in the sheet
for (var i = 2; i < 11; ++i) {
html = html + "<b>" + sheetform.getRange(1,i).getValue() + "</b><br>";
html = html + sheetform.getRange(lastrow,i).getValue() + "</p><br>";
}
//Add additional emails if entered in form field
if (sheetform.getRange(lastrow,4).getValue() !== "") {
recipientsTO = recipientsTO + "," + sheetform.getRange(lastrow,4).getValue()
}
//CC if response to a question is "Yes"
if (sheetform.getRange(lastrow,10).getValue() == "Yes") {
recipientsCC = "ccEmaIL#gmail.com"
}
MailApp.sendEmail({
to: recipientsTO,
cc: recipientsCC,
subject: "Subject",
htmlBody: html,
});
}

According to the sendEmail(message) documentation, the TO field only has one recipient.
Whereas the CC field can have multiple recipients separated by comma.
http://goo.gl/CGjiJ
`to - String - the address of the recipient.
cc -String - a comma separated list of email addresses to CC`
Another option would be to use sendEmail(String,String,String,Object) in that function "recipient String the addresses of the recipients, separated by commas".
Hope this helps.

Here is code from my production script:
//check quota and log
const emailsLeft = MailApp.getRemainingDailyQuota();
console.log( emailsLeft + " emails left in quota");
//get list of emails from spreadsheet itself
//filter out empty rows
const emails = getTab("Config").getRange("D2:D").getValues().map(function(el){ return el[0]; }).filter(function(el){ return el != '' });
//send emails from NO_REPLY email, subject and HTML body
MailApp.sendEmail({
to: emails.join(","),
subject: subject,
htmlBody: html,
noReply: true
});
function getTab(name) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
return sheet.getSheetByName(name);
}
getTab() and other helper functions can be found here
https://github.com/tim-kozak/google-spreadsheet-helpers

Related

"Email_Sent" message not updating to the spreadsheet as it should

I'm having trouble with the "Email _Sent" text. It is supposed to appear next to the recipient who received the email from my spreadsheet. However, when I select certain emails to send the message to, the text "Email _Sent" starts filling out the first empty rows in my spreadsheet. In this way, the text appears beside some recipients who didn't receive the message.
I'll post the script that I'm using:
function sendGeneralEmail() {
var Email = 4;
var Name = 3;
var emailSent = 6;
var subject = "Sample Analysis Service"
var html = HtmlService.createTemplateFromFile("SUM.1");
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test");
var data = ws.getRange("A5:G" + ws.getLastRow()).getValues();
data = data.filter(function(r){ return r[5] == true});
var Email_Sent = 'Email_Sent';
var sheet = SpreadsheetApp.getActiveSheet();
var notBlank = sheet.getRange("D5:G5");
var lastRow = notBlank.getLastRow();
data.forEach(function(row){
html.en = row[Name];
var htmlMessage = html.evaluate().getContent();
if(emailSent !=Email_Sent) {
GmailApp.sendEmail(
row[Email],
subject, "Your Email doesn't support HTML", {
name: "MASAR Team",
htmlBody: htmlMessage},
);
sheet.getRange(lastRow, 7, data.length, 1).setValue(Email_Sent);
SpreadsheetApp.flush();
}
});
}
Can someone help me to fix that?
The second issue is that, if I run the script and then stopped and came back and run it again on the same day, the text "Email_sent" stops updating to the spreadsheet. It only appears the first I run the script during the day.
Screenshot
Hope to have a solution to this
I tried to replicate your code and found some issues:
using setValue on range with multiple cells will copy the value to all cells within the range. In your example, all cells in getRange(lastRow, 7, data.length, 1) will have the value "Email_Sent". This causes the unwanted write of "Email_Sent" in your spreadsheet.
if(emailSent !=Email_Sent) will always true because '6' is not always equal to 'Email_Sent'
Based on your example, your goal is to send an email and write "Email_Sent" to the Email Status column of the recipient.
Here, I fixed some part of your code and added features.
Code:
function sendGeneralEmail() {
var subject = "Sample Analysis Service"
// var html = HtmlService.createTemplateFromFile("SUM.1");
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test");
var data = ws.getRange("A5:G" + ws.getLastRow()).getValues();
var sheet = SpreadsheetApp.getActiveSheet();
for(var i=0; i<data.length; i++){
var selected = data[i][5];
var emailStatus = data[i][6];
if(selected && emailStatus != "Email_Sent"){
var email = data[i][4];
// html.en = row[Name];
// var htmlMessage = html.evaluate().getContent();
GmailApp.sendEmail(
email,
subject, "Your Email doesn't support HTML", {
name: "MASAR Team",
message: "ABCD",
// htmlBody: htmlMessage},
}
);
sheet.getRange(i+5, 7, 1, 1).setValue("Email_Sent");
}
}
}
Note: I commented the html parsing since I don't have the sample html and replaced the email message with a string.
Before running the script:
After running the script:
Reference:
setValue()

Auto Email google sheet response

Can anyone help with a google app script to trigger an auto email to applicants that failed the quiz - scoring lower than 130 on column A on google sheets?
Thanks in advance for the help!
Quiz Results Response
Do you want the mail to go automatically as soon as the form is filled? In that case, you can use the onFormSubmit trigger to send the mail to him automatically.
If you are processing the answers and then creating the result sheet, you can send the mail from the result sheet by processing each row in the sheet. You can easily find many examples how to send a mail from a sheet based on value in a column.
I am enclosing a similar code which sends the response to a user automatically as soon as he submits a form. I am storing his email ID (based on employee number) and sending him some data (based on his employee number) as soon as requests it. It works as a "employee self help portal".
function onFormSumbit(e) {
var emp = e.source.getActiveSheet().getRange(e.range.rowStart,2).getValue();
var lvss = SpreadsheetApp.openById("xxxx"); // blanks https://docs.google.com/spreadsheets/d/1kjOjhH0dvz4j3FsB_1UR5astpy8-ZxszNI4BZo4XJP0/edit#gid=0
SpreadsheetApp.setActiveSpreadsheet(lvss);
var lvsht = lvss.getSheetByName("Blanks");
var lvlr = lvsht.getLastRow();
var vA =lvsht.getRange("A:L").getValues();
var html="<style>th,td{border:1px solid black;}</style><table>";
html+='<tr>';
for(var i=0;i< 4 ;i++) {//make title
html+=Utilities.formatString('<th>%s</th>',vA[0][i]);
}
html+='</tr>';
for (i=1;i<lvlr;i++){
if (vA[i][0]==emp){
html+='<tr>';
for (j=0;j<4;j++) {
if ( j==2 ){
vA[i][j]=Utilities.formatDate(vA[i][j],"GMT+05:30", "dd-MM-yy");
}//if date
html+=Utilities.formatString('<td>%s</td>',vA[i][j]);
}//for emp
html+='</tr>';
}//if
}//for
html+='</table><br>';
var empss = SpreadsheetApp.openById("xxxx"); // emp master
SpreadsheetApp.setActiveSpreadsheet(empss);
var empsht = empss.getSheetByName("Emp");
var emplr = empsht.getLastRow();
var empvals =empsht.getRange("A:H").getValues();
for (i=1;i<emplr;i++){
if (empvals[i][0]==emp){
var em1=empvals[i][7];
var name=empvals[i][1]
break;
}//if
}//for
var subject="Your punch blanks "+name;
if (em1=="") {} else {
//MailApp.sendEmail(em1, subject, html);}
MailApp.sendEmail({
to: em1,
subject: subject,
htmlBody: html
});
}
}
//
//
Hope it helps !!
This function processes the full spreadsheet data from first row to last row and sends failure notification emails where the score is less than 130 ...
function notifyFailedCandidates ()
{
//Get the active sheet from the current spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Get all the rows from the spreadsheet
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2,1, lastRow-1, lastColumn);
var rows = searchRange.getValues();
//loop through each of the rows
for (var rowNumber in rows)
{
//Get each of the values from the row
var quizScore = rows[rowNumber][0];
var firstName = rows[rowNumber][1];
var lastName = rows[rowNumber][2];
var email = rows[rowNumber][3];
//Send a failure notification if the score is less than 130
if (parseInt (quizScore) < 130)
{
MailApp.sendEmail
(
email, //candidate email address
'Notification of test failure', //Subject of failure notification email
//Contents of failure notification email
'Hi ' + firstName + "\n\n" +
'This email is to let you know that unfortunately you failed the test, with a score of ' + quizScore + ' / 170' + "\n\n" +
'Better luck next time'
);
}
}
}

Iterate through column, find match and send email based on cell value

I have a spreadsheet (here -> https://docs.google.com/spreadsheets/d/1U0A8PmKYxkXn8SrfKOo6XsJb-XxkJNYZqd0QIKkFsP4/edit?usp=sharing) that collects data from forms and perform several if functions to categorize answers.
What I need to do is to send follow up emails (reminders) based on cell value (sheet "Code extension data + Minimum desc. fill", last column "Reminder Minimum descriptions"). In order to do that, I suppose I must loop through the column, find a match ("Keep sending reminder", "Stop sending reminder") and send mail.
But what ends up happening is that the code shoots 73 follow up messages. I don't know 73, if I have only 2 rows with "Keep sending email".
function sendEmail() {
var ss = SpreadsheetApp.openById("1lzc7-WRxEBQc5D_SR0F-d-
9PhQjmVk37UOgBQTGw3_Q");
var sh = ss.getSheetByName('Code extension data + Minimum desc. fill');
var lastRow = sh.getLastRow();
var data = sh.getRange(1,28,lastRow,28).getValues();
for (i=0; i < data.length;i++){
var num = parseInt(data[i]);
if (num = "Keep sending reminder") {
var emailAddress = "email#email.com";
var message = "test body";
var subject = "test subject";
MailApp.sendEmail({
name: "Your Name",
to: emailAddress,
subject: subject,
htmlBody: message
});
}
}
}
Your if statement is comparing a number to a string ("Keep sending reminder") which will never evaluate as true. There is no need to use parseInt for what you are trying to do. Also, you are looping over string[][], so you have to use data[i][columnIndex] to access the column you expect to find "keep sending reminder" in.
function sendEmail() {
var ss = SpreadsheetApp.openById("1lzc7-WRxEBQc5D_SR0F-d-9PhQjmVk37UOgBQTGw3_Q");
var sh = ss.getSheetByName('Code extension data + Minimum desc. fill');
var lastRow = sh.getLastRow();
var data = sh.getRange(1,28,lastRow,28).getValues();
for (var i=0; i < data.length; i++) {
//var num = parseInt(data[i]);
if (data[i][27] === "Keep sending reminder") {
var emailAddress = "email#email.com";
var message = "test body";
var subject = "test subject";
MailApp.sendEmail({
name: "Your Name",
to: emailAddress,
subject: subject,
htmlBody: message
});
}
}
}
Your if statement only has a single equal sign, use == or === even better.

Apps Script - Send Email - Make content in email bold - Format result of Array.toString in bold

My code sends email notifications every time a Google Form is submitted. It works, but I want the collected form data as bold in the email.
for(var i in headers)
message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";
function sendFormByEmail(e)
{
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
var message = "";
var data = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
var subject = "";
//Get active Spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//Get Sheet called 'Form responses 1'
var fr1 = ss.getSheetByName("Form responses 1");
//Get all emails from 'Emails' tab
var emails = ss.getSheetByName("Emails");
var numRows = emails.getLastRow();
var emailTo = emails.getRange(2, 2, numRows, 1).getValues();
// The variable e holds all the form values in an array.
// Loop through the array and append values to the body.
for(var i in headers)
message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";
// Insert variables from the spreadsheet into the subject.
// In this case, I wanted the part number as part of the
// email subject. These are the 3rd and 16th columns in my form.
// This creates an email subject like "Parts Inquiry Submission: 729302"
subject += e.namedValues[headers[1]].toString();
// Send the email
MailApp.sendEmail(emailTo, subject, message);
// Based off of a script originally posted by Amit Agarwal - www.labnol.org
// Credit to Henrique Abreu for fixing the sort order
}
First of all, you must use the advanced parameter htmlBody in the 4th parameter of sendEmail() and you need to make the body parameter and empty string.
sendEmail(recipient, subject, body, options)
Code:
message = "<strong>" + message + "</strong>";//Wrap message in bold tags
var options = {
"htmlBody":message
}
// Send the email
MailApp.sendEmail(emailTo, subject, "",options);//Make email body empty string
Thank you all for your help. I ended up changing it up a bit. Here is what I ended up using.
function sendFormByEmail(e)
{
var message = "";
var subject = "";
var emailTo = "";
//Gets the active Spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//Get Sheet called 'Form responses 1'
var fr1 = ss.getSheetByName("Form responses 1");
var headers = fr1.getRange(1,1,1,fr1.getLastColumn()).getValues()[0];
//Get all emails from 'Emails' tab
var emails = ss.getSheetByName("Emails");
var emailTo = emails.getRange(2, 2, emails.getLastRow()-1, 1).getValues().toString();
// For each column in the spreadsheet, add the column name and it's new entry as a line in the email
message = "<html>";
for(var i in headers)
message += headers[i] + ': <b>'+ e.namedValues[headers[i]].toString() + "</b><br><br>";
message += "</html>";
// Set the subject as the Item Number
subject = e.namedValues[headers[1]].toString();
// Send the email
MailApp.sendEmail({
to: emailTo,
subject: subject,
htmlBody: message
});
}

Get cell value from Google sheet for sending form results.

I am attempting to extract a value from a sheet field. The sheet is being populated by a form. I am using it to differentiate an email address to send the form results to. The script works, but the way I'm trying to extract the value of the field is not working.
var s = SpreadsheetApp.getActiveSheet();
var branch = s.getRange(s.getLastRow(),s.getLastColumn(),1,1).getValue();
if (branch == 'Albany') {
var email = "EMAIL ADDRESS"
} else {
var email = "OTHER EMAIL ADDRESS"
}
Any thoughts would be appreciated.
Try use trigger "onFormSubmit" with e parameter.
Link to article: https://developers.google.com/apps-script/guides/triggers/events
I'm using this triggers every day.
My sample code:
`function sendNotyfication(e) {
var HTMLMessage = "my html message to send; var mail_adres;
if(e['values'] != undefined){
var items = e['namedValues'];
var items_sort = [];
for(var i in items) {
var item = [i, items[i]]
items_sort.push(item);
}
items_sort.sort();
for(var j=0;j<items_sort.length;j++){
HTMLMessage += '<p><b>'+items_sort[j][0]+'</b>: '+ items_sort[j][1]+'</p>'
}
//i have mail in my form
if(items['your question in form'][0] == 'xxxx'){
mail_adres = "xxxx#domain.com"
}
}catch(e){}
HTMLMessage += "Hellol"
if(mail_adres!=null){
MailApp.sendEmail({
to: mail_adres,
bcc: bcc,
noReply: true,
subject: "New subject",
htmlBody: HTMLMessage
});
}`