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
});
}`
Related
I'm very new to development and was tasked with creating a confirmation email for anyone who enters their email into a waitlist form on a website. So far, I have been able to port an email address from the form to a Google Sheet but I have been unsuccessful in actually contacting said email.
My sheet format looks like this:
[Google Sheet Layout][1]
My dysfunctional code is:
function sendMail() {
var ws = SpreadsheetApp.getActiveSheet();
if (ws.getSheetName() != "Waitlist") return;
var date = 0;
var email = 1;
var emailTemp = {};
var emailTemp = HtmlService.createTemplateFromFile("email");
var data = ws.getRange("A2:C" + ws.getLastRow()).getValues();
var ranges = data.map(function (row, i) {
if (row[1] == true && row[2] != "sent") {
// emailTemp.date = row[date];
var htmlMessage = emailTemp.evaluate().getContent();
GmailApp.sendEmail(row[email],
"Failure message",
"Please submit again.",
{ name: "Fervo", htmlBody: htmlMessage }
);
return "C" + (i + 2);
}
return "";
}).filter(String);
ws.getRangeList(ranges).setValue("sent");
}
Apologies if it's completely wrong! I'd be super appreciative of some insight on how to make it spin. Thank you!
Im looking for a google apps script that can send email based on form input.
I tried this but this is not working:
for(var i in mailCreator){
if(mailCreator[i][0].match("...#abc.nl")!=null){
MailApp.sendEmail({
to: "123#def.com",
subject: ADDED_TO_GROUP_SUBJECT,
htmlBody: emailBody,
})
}
}```
It would be great if i can search for a certain value in the form input instead of an exact match.
What is mailCreator? Is it an array where is the range with the mails? or Or try to capture a field from the form?
EDIT.
Hi Johan, I think this is better for what you need. I understand that your objetive is to send an email with the data collected from the form. I use this.
This takes the range of the form sheet and sends you an email with the data of the defined variables. We can return more data from the range obtained from the form sheet.
function SendMail() {
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var listamail = spreadSheet.getSheetByName("name sheet");
var dataRange = listamail.getDataRange();
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var text = 'Text for body.';
for (var i = 1; i < data.length; i++) {
(function(val) {
var row = data[i];
var emailAddress = row[1]; //position of email header — 1
var name = row[0]; // position of name header — 1
var message = text ;
var subject = 'Write subjet or ne';
MailApp.sendEmail(emailAddress, subject, message);
})(i);
}
}```
You can call this function whenever you submit the form. But u need edit this and only use last value of range.
var ADDED_TO_GROUP_DOC_URL = 'https://docs.google.com/location of your document';
function onFormSubmit(e) {
var mailCreator = formValues['E-mailadres'][0].trim();
var subject = 'Subject title';
var addedToGroupDocId = DocumentApp.openByUrl(ADDED_TO_GROUP_DOC_URL).getId();
var emailBody = docToHtml(addedToGroupDocId);
MailApp.sendEmail({
to: mailCreator,
subject: subject,
htmlBody: emailBody,
});
}```
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()
I have a form run from SquareSpace that inputs the customer data to a Google Sheet. I'm currently running the below script, but the trigger OnFormSubmit doesn't work. I have to go in and manually run the script.
function FormConfirmationEmail() {
var sheetname = "Request Financial Assistance"
var columnnumber = 6
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetname);
if (sheet.getRange(sheet.getMaxRows(),1).getValue() != "") {
var lastrow = sheet.getMaxRows()
} else {
var count = 0
for (var i = 0; i < sheet.getMaxRows(); i++) {
if (sheet.getRange(sheet.getMaxRows()-i,1).getValue() != "") {
var lastrow = sheet.getMaxRows()-i
break;
}
}
}
var email = sheet.getRange(lastrow,columnnumber).getValue();
var emailPattern = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|aero|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|name|museum|name|net|org|pro|tel|travel)\b/;
var validEmailAddress = emailPattern.test(email);
if (validEmailAddress == true) {
var message = "<HTML><BODY>"
+ "<P>This is an automated form completion email. Thanks for submitting!"
+ "</HTML></BODY>";
MailApp.sendEmail(email, "Form Completion Email", "", {htmlBody: message});
sheet.getRange(lastrow,13,1,1).setValue("Email Sent");
} else{
sheet.getRange(lastrow,13,1,1).setValue("Email not Sent - Invalid Email Address submitted");
}
}
Can anyone see what I'm doing wrong?
You can put the trigger in the Google sheet that is collecting the responses and the Form Submit trigger should work.
ScriptApp.newTrigger("FormConfirmationEmail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
Also, instead of using getMaxRow(), you can use the e parameter that is passed to the FormSubmit function to parse and email the user submitted data.
See: Get Google Forms Data in Email
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