Error while trying to use the "reply-to" in google apps script - forms

I'm using google apps script to get the responses of a specific form in an specific e-mail,
What I'm trying to do is use a google form to open support tickets, so people need fill some fields like, title, description and e-mail,
And when they submit the form, it will automatically open a ticket, but the e-mail will be always from the owner of the form, and this was a problem because we want that the person who opened the ticket receives email updates, so what I'm trying to do is this:
I put a field in the form asking the persons email, and I'm trying to put that e-mail into the reply-to...
And apparently I'm in the right way to catch that e-mail but the reply-to don't show the email that the persons filled the box, it appears an error: [Ljava.lang.Object;#34dfe075
Does any one can help me?
Here is my script:
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
var email = "support#email.com";
var form = e.namedValues;
var subject = form["Title"];
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] && (e.namedValues[key] != "") ) {
message += key + ' :: '+ e.namedValues[key] + "\n\n";
}
}
GmailApp.sendEmail(email, subject, message, {replyTo: form["E-mail"], from: "support#email.com"});
} catch (e) {
Logger.log(e.toString());
}
}
And here is the output of this:
from: support#email.com
reply-to: [Ljava.lang.Object;#34dfe075
to: support#email.com
date: Fri, Oct 17, 2014 at 10:55 AM
subject: New Test
The reply to, is broken :(

The values returned in the e.namedValues property are arrays, so you must access them as such.
Modify your sendEmail line as follows:
GmailApp.sendEmail(email, subject, message, {replyTo: form["E-mail"][0], from: "support#email.com"});
Note the [0] array index on the form["E-Mail"] field, indicating you want the first value in that array, which will be the email address entered.
See the example next to "e.namedValues" here: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events

Related

Send email to the new google form submission only

I'm new to the Google apps script. I wrote a script to send emails when there is a new submission from google forms using data and template from a spreadsheet. However, it sends an email to not just the new submission but also to all of the previous submissions. The whole script is quite long, so I only copy a short part of it. Is there any way to fix it?
Here is the link to the spreadsheet https://docs.google.com/spreadsheets/d/1fhuwEndIS3khg3W19jpQnBAaCp_MMrD_bfATrdf2-4I/edit?usp=sharing
Thank you.
function sendEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Calculation");
var lr = ss.getLastRow();
for (var i = 3; i<=lr;i++){
var currentEmail = ss.getRange(i, 1).getValue();
var currentName = ss.getRange(i, 3).getValue();
var currentScore1 = ss.getRange(i, 4).getValue();
MailApp.sendEmail(
currentEmail,
subjectline,
"HTML",
{ htmlBody: messageBody }
);
}
}
Instead of reading the values from the spreadsheet take advantage of the form submit event object. This event object has two properties including the form submission values, one is an Array of form submission values in the same order than the sheet columns, the other is an object having a property for each question each of them having an Array of values. Ref. https://developers.google.com/apps-script/guides/triggers/events
This shows the changes that need to done to your script:
function sendEmail(e) {
var currentEmail = e.values[0];
var currentName = e.values[2];
var currentScore1 = e.values[3];
MailApp.sendEmail(
currentEmail,
subjectline,
"HTML",
{ htmlBody: messageBody }
);
}
Note: In order to make the event object work, the function should be called by a Google Sheets form submit trigger.
Related
Event values and offset in Google spreadsheet
How to send an email only to the last Google form submission?

Send an email using email addresses from a column in Google sheets

I'm trying to create code that will send an email using addresses from a specific column in google sheets. I want the code to send an email after the sheet is edited by other users. For example, someone enters a request on a row in the sheet - then an email is sent to the manager of the request. Here's what I have so far...
function SendEmail(){
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("HLP REQUESTS").getRange("K:K");
var emailAddress = emailRange.getValues()[0][0];
// Send Alert Email.
var message = 'A request has been submitted for professional learning related to an HLP you champion. Please check the Design Team Notes document in case follow-up is required.'; // Second column
var subject = 'HLP Request for Professional Learning';
MailApp.sendEmail(emailAddress, subject, message);
}
When I run the code above I get an error - Exception: Failed to send email: no recipient. There is a valid email address in column K, so I'm a little confused.
If you want get email address from the last cell of the column K it can be done this way:
function SendEmail(){
var emailRange = SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName("HLP REQUESTS").getRange("K:K");
var emailAddress = emailRange.getValues()
.flat() // convert a 2d array into a flat array
.filter(String) // remove empty elements from the array
.pop(); // get the last element from the array
var message = 'A request has been submitted for professional learning related to an HLP you champion. Please check the Design Team Notes document in case follow-up is required.';
var subject = 'HLP Request for Professional Learning';
MailApp.sendEmail(emailAddress, subject, message);
}
Update
Here is the full implementation with installable trigger onEdit that sends email as soon as the checkbox (in column L) was checked in:
// global variables
var SS = SpreadsheetApp.getActiveSpreadsheet(); // get the srpreadsheet
var checkbox_col = 12; // column with checkboxes (L in this case)
// the main function
function sendEmail(e) {
try {
var {rowStart, columnStart} = e.range; // get row and column of the cell that was edited
if (columnStart != checkbox_col) return; // do nothing if it was not column with checkboxes
if (e.value != 'TRUE') return; // do nothing if the checkboxs was unchecked
e.range.setValue(false); // else uncheck the chekbox
var sheet = SS.getSheetByName('HLP REQUESTS'); // get the sheet
var emailAddress = sheet.getRange('K' + rowStart).getValue(); // get email addres from current row, column K
var message = 'A request has been submitted for professional learning related to an HLP you champion. Please check the Design Team Notes document in case follow-up is required.';
var subject = 'HLP Request for Professional Learning';
MailApp.sendEmail(emailAddress, subject, message); // send the message
SS.toast('Email to ' + emailAddress + ' has been sent');
}
catch(e) { SpreadsheetApp.getUi().alert(e) }
}
// additional functions -------------------------------------------------------------------------
// insatll the trigger
function install_onEidt_trigger() {
ScriptApp.newTrigger('sendEmail').forSpreadsheet(SS).onEdit().create();
SS.toast('Trigger was installed');
}
// remove all triggers
function remove_all_triggers() {
ScriptApp.getProjectTriggers().forEach(t => ScriptApp.deleteTrigger(t));
SS.toast('All triggers were remoded');
}
// custom menu to install and remove triggers
function onOpen() {
SpreadsheetApp.getUi().createMenu('⚙️ Scripts')
.addItem('Install trigger', 'install_onEidt_trigger')
.addItem('Remove all triggers', 'remove_all_triggers')
.addToUi();
}
To make it work you have:
to reload the spreadsheet (or to run the function onEdit() manually) to get the custom menu Scripts
in the custom menu run the item Install trigger
after that it will try to send the message to the address from column K of current row whenever user clicks on checkbox in column L
My test sheet looks like this:
Sending Emails
function SendEmail() {
const ss = SpreadsheetApp.getActive();
const rsh = ss.getSheetByName("HLP REQUESTS");
const emails = rsh.getRange("K1:K" + rsh.getLastRow()).getDisplayValues().flat();
var message = 'A request has been submitted for professional learning related to an HLP you champion. Please check the Design Team Notes document in case follow-up is required.';
var subject = 'HLP Request for Professional Learning';
emails.forEach(e => {
MailApp.sendEmail(e, subject, message);
});
}
If you wish to attach this to an onEdit you will have to rethink the process because the onEdit trigger fires on every edit to any sheet and most likely you will be require to use an installable onEdit so that you can perform operations that require permission. I'd recommend you play around with the onEdit simple trigger for a while. Look at the event object and see what's available at low overhead cost.

Google Form mail notification script. Emails always have "me" as sender

I have tried to use the search function, but did not find a solution for my problem, or I do not understand enough yet.
I have written a script for google forms, that sends an automatic email to two email addresses, when an user submits the form. I have build in some information that should show in the email subject and puts the input from the forms into the email, with some simple HTML formatting.
My problem is, that the emails always have my Email address as the sender (the account I used for creating the form)
I would like to have the senders email, the one that is submitting the form.
How is that possible?
Here is the code:
function sendFormByEmail(e)
{
// Sent to Email address
var email1 = "123#abc.com";
var email2 = "345#abc.com";
// Variables
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var txt = "";
var subject = "Example text: ";
// Var e = form input as array.
// Loop through the array.
for(var i in headers){
txt += "<b>" + headers[i] + '</b>' + ': '+
e.namedValues[headers[i]].toString() + '<br><br>';
}
// Insert variables from the spreadsheet into the subject.
// Create email subject
subject += "Example text " + e.namedValues[headers[2]].toString();
// Send the email
MailApp.sendEmail(email1, subject, "", {htmlBody:txt});
MailApp.sendEmail(email2, subject, "", {htmlBody:txt});
}
It is not possible to send the mail as the user who submitted the form as the script is running from the user account and the mailapp will send the mail from that account only. you can change the display name according to the user name who submiited the form by the parameter name. Also you can change the email to noreply#domainName.com by adding the parameter noReply in mailApp syntax. However you cannot change it to the user who submitted the form
You can refer this documentation for the above parameters : https://developers.google.com/apps-script/reference/mail/mail-app
Hope this could help

Google Form Email Notification On Submission

I'm trying to update this script to allow me to update the "Sender's" or "Reply To" email address. I'm unsure how to do this as I'm using the script listed here - http://www.labnol.org/?p=20884
I've emailed the developer of this script but have yet to receive a response. Any advice on adding a field to overwrite the default "Reply To" or sender email address?
Thanks for your help!
/* Send Google Form by Email v2.0 */
/* For customization, contact the developer at amit#labnol.org */
/* Tutorial: http://www.labnol.org/?p=20884 */
function Initialize() {
var triggers = ScriptApp.getScriptTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
// You may replace this with another email address
var email = "CLIENT EMAIL ADDRESS";
// Optional but change the following variable
// to have a custom subject for Google Form email notifications
var subject = "Form Application Submitted";
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
// Only include form fields that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] && (e.namedValues[key] != "") ) {
message += key + ' :: '+ e.namedValues[key] + "\n\n";
}
}
// This is the MailApp service of Google Apps Script
// that sends the email. You can also use GmailApp for HTML Mail.
MailApp.sendEmail(email, subject, message);
} catch (e) {
Logger.log(e.toString());
}
}
Replace
MailApp.sendEmail(email, subject, message);
with
GmailApp.sendEmail(email, subject, message, {replyTo: "abc#example.com", from: "xyz#example.com"});
The from address has to be an alias though.

setting up script to include google docs form data in email notification

I've setup a form using googledocs. I just want to have the actual data entered into the form emailed to me, as opposed to the generic response advising that the form has been completed.
I have no skill or experience with code etc, but was sure i could get this sorted. I've spent hours+hours and haven't had any luck.
My form is really basic.it has 5 fields. 4 of which are just text responses, and one multiple choice.
I found this tute online (http://www.labnol.org/internet/google-docs-email-form/20884/) which i think sums up what i'm trying to do, but have not been able to get it to work.
from this site i entered the following code:
function sendFormByEmail(e)
{
var email = "reports.mckeir#gmail.com";
var subject = "Google Docs Form Submitted";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
for(var i in headers)
message += headers[i] + ' = '+ e.namedValues[headers[i]].toString() + "\n\n";
MailApp.sendEmail(email, subject, message);
}
To this, i get the following response: ->
Your script, Contact Us Form Mailer, has recently failed to finish successfully. A summary of the failure(s) is shown below. To configure the triggers for this script, or change your setting for receiving future failure notifications, click here.
The script is used by the document 100% Club.
Details:
Start Function Error Message Trigger End
12/3/12 11:06 PM sendFormByEmail TypeError: Cannot call method "toString" of undefined. (line 12) formSubmit 12/3/12 11:06 PM
Is anyone able to help shed some light on this for me? I'm guessing i'm not including some data neeeded, but i honestly have no clue.
Workaround http://www.labnol.org/internet/google-docs-email-form/20884/
You have to setup app script to forward the data as email.
I'll point to the comment above that solved it for me: https://stackoverflow.com/a/14576983/134335
I took that post a step further:
I removed the normal notification. The app script makes that generic text redundant and useless now
I modified the script to actually parse the results and build the response accordingly.
function sendFormByEmail(e)
{
var toEmail = "changeme";
var name = "";
var email = "";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
var subject = "Google Docs Form Submitted";
var message = "";
// The variable e holds all the form values in an array.
// Loop through the array and append values to the body.
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
// Credit to Henrique Abreu for fixing the sort order
for(var i in headers) {
if (headers[i] = "Name") {
name = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Email") {
email = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Subject") {
subject = e.namedValues[headers[i]].toString();
}
if (headers[i] = "Message") {
message = e.namedValues[headers[i]].toString();
}
}
// See https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)
var mailOptions = {
name: name,
replyTo: email,
};
// This is the MailApp service of Google Apps Script
// that sends the email. You can also use GmailApp here.
MailApp.sendEmail(toEmail, subject, message, mailOptions);
// Watch the following video for details
// http://youtu.be/z6klwUxRwQI
// By Amit Agarwal - www.labnol.org
}
The script utilized in the example is extremely generic but very resilient to change because the message is built as a key/value pair of the form fields submitted.
If you use my script you'll have to tweak the for loop if statements to match your fields verbatim. You'll also want to edit the toEmail variable.
Thanks again for the question and answers. I was about to ditch Google Forms as the generic response was never enough for what I was trying to do.
Lastly, in response to the actual problem above "toString of undefined" specifically means one of the form fields was submitted as blank. If I had to guess, I would say the author only used this for forms where all the fields were required or a quick undefined check would've been put in place.
Something like the following would work:
for(var i in headers) {
var formValue = e.namedValues[headers[i]];
var formValueText = "";
if (typeof(formValue) != "undefined") {
formValueText = formValue.toString();
}
message += headers[i] + ' = '+ formvalueText + "\n\n";
}
I haven't tested this precisely but it's a pretty standard way of making sure the object is defined before trying methods like toString() that clearly won't work.
This would also explain Jon Fila's answer. The script blindly assumes all of the header rows in the response are sent by the form. If any of the fields aren't required or the spreadsheet has fields that are no longer in the form, you'll get a lot of undefined objects.
The script could've been coded better but I won't fault the author as it was clearly meant to be a proof of concept only. The fact that they mention the replyTo correction but don't give any examples on implementing it made it perfectly clear.
If this is a Google Form, do you have any extra columns in your spreadsheet that are not on the form? If you delete those extra columns then it started working for me.
You don't need to use a script. Simply go to Tools >> Notification Rules on your Google Spreadsheet. There you can change the settings to receive an email with your desired information every time the document is changed.