Send email to specific user based on Google Form - google-apps-script

Background: Google Script for Forms creating a phone message log that emails to a specific person as selected.
Need help with the email address portion of the code. I want to have a message sent to an email address based on the radio button with the person's name selected.
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 {
var email = HELPHELPHELP;
// Optional but change the following variable
// to have a custom subject for Google Form email notifications
var subject = "Google Docs Form 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());
}
}

Presumably the intended recipient's name comes from a question / column with a title like "Message for".
In that case, try this:
...
var email = resolveEmail( e.namedValues["Message for"] );
...
function resolveEmail( userName ) {
// List of userNames & (secret) email addresses
var userEmails = {
"Mickey" : "bigears#example.com",
"Donald" : "duckman#example.com" // etc.
};
if (userName in userEmails) {
return userEmails[userName];
}
else {
// Unknown user - send email to script owner
return Session.getEffectiveUser().getEmail();
// Alternatively, could throw an error to get notified
// throw new Error( "Could not resolve email for user: " + userName );
}
}

Related

I'm trying to set up Apps Script to send emails for an Order Form from Google Sheets

I have created an Google Form so our employees can request their needs, it's a basic Order Form. I am receiving all their request in a Google Sheet and I'm trying to send them an email responding to their request. In my spread sheet I have a column called "Approval Status" with a drop down with the options "Approved", "Denied" and "Have Questions". What I'm trying to achieve is based on my "Approval Status" the person who made the request should receive an email with the response.
I've used the link below as reference. So far so good, until I get to step 5.3. I have tried editing the rows but I get a "ReferenceError: column is not defined". The error is coming from the shouldSendEmail function.
Here's my code and a picture of my spreadsheet.
Spreadsheet
function sendEmailsAndUpdateStatus() {
//Get the rows in the spreadsheet
var dataRange = SpreadsheetApp.getActive().getDataRange();
var data = dataRange.getValues();
//Remove the header row and add it to a new array.
//We will write this array back to the spreadsheet at the end.
var updatedData = [data.shift()];
//The variable numNotification will track if notifications were sent
var numNotifications = 0;
//Process each row using a forEach loop
data.forEach(function (row) {
//Check if email notifications should be sent and send them.
//If the notification is sent, increment numNotifications and also
//update the "Email sent" column to "Y".
if(shouldSendEmail(row)) {
sendApprovalStatusEmail(row);
numNotifications++;
row[9] = "Y";
}
//Add this row to the new array that we created above
updatedData.push(row);
});
//Write the new array to the spreadsheet. This will update the
//"Email sent" columns in the spreadsheet.
dataRange.setValues(updatedData);
//Display a Toast notification to let the user know if notifications
//were sent.
if(numNotifications > 0) {
SpreadsheetApp.getActive().toast("Successfully sent " + numNotifications + " notifications.");
} else {
SpreadsheetApp.getActive().toast("No notifications were sent.");
}
}
function shouldSendEmail(row) {
//Don't send email unless the expense report has been processed
if(column[7] != "Approved" && column[7] != "Rejected" && column[7] != "Have questions")
return false;
//Don't send email if email address is empty
if(row[5] === "")
return false;
//Don't send email if already sent
if(row[9] === "Y")
return false;
return true;
}
function sendApprovalStatusEmail(row) {
//Create the body of the email based on the contents in the row.
var emailBody = `
EXPENSE REPORT: ${row[7]}
-----------------------------------------------------------------
Note: ${row[8] === "" ? "N/A" : row[8]}
-----------------------------------------------------------------
Department: ${row[1]}
Amount: ${row[2]}
Reason: ${row[4]}
Date: ${(row[3].getMonth() + 1) + "/" + row[3].getDate() + "/" + row[3].getFullYear() }
-----------------------------------------------------------------
Please contact expensereports#example.com if you have any questions about this email.
`;
//Create the email message object by setting the to, subject,
//body, replyTo and name properties.
var message = {
to: row[6],
subject: "[Expense report " + row[7] + "]: " + row[4],
body: emailBody,
replyTo: "expensereports#example.com",
name: "Expense Reports"
}
//Send the email notification using the MailApp.sendEmail() API.
MailApp.sendEmail(message);
}

How do I insert images from URLs in google sheets in an email as in line images

So I have only recently learnt what Apps Script is.
I was attempting to make a google form that takes the data from that form and puts it into a google sheet.
Then there is a Apps script that runs inside the spreadsheet that when people submit a form it sends a nicely formatted email to be printed off, but after finding some code online I was able to change to my liking I realized that the images were being inserted into the email as attachments which won't print off in one nice clean document.
So I was wondering if anyone knew how I could take the image URLs from their cells and insert them into the email as inline images.
Here is my code so far:
function Initialize() {
try {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers)
ScriptApp.deleteTrigger(triggers[i]);
ScriptApp.newTrigger("EmailGoogleFormData")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit().create();
} catch (error) {
throw new Error("Please add this code in the Google Spreadsheet");
}
}
function EmailGoogleFormData(e) {
if (!e) {
throw new Error("Please go the Run menu and choose Initialize");
}
try {
if (MailApp.getRemainingDailyQuota() > 0) {
// You may replace this with another email address
var email = "email address";
// Enter your subject for Google Form email notifications
var subject = "Form";
var key, entry,
message = "",
ss = SpreadsheetApp.getActiveSheet(),
cols = ss.getRange(1, 2, 1, ss.getLastColumn()).getValues()[0];
// Iterate through the Form Fields
for (var keys in cols) {
key = cols[keys];
entry = e.namedValues[key] ? e.namedValues[key].toString() : "";
// Only include form fields that are not blank
if ((entry !== "") && (entry.replace(/,/g, "") !== ""))
message += key + ' : ' + entry + "\n\n";
}
MailApp.sendEmail(email, subject, message);
}
} catch (error) {
Logger.log(error.toString());
}
}
Thank you for your help in advance!
I have been searching the API and google for a way to change the images into inline images, but everything I've messed with hasn't worked.
Get the image as a blob and name it, use Context-ID.
https://developers.google.com/apps-script/reference/mail/mail-app#sendemailmessage

Modifying the Google Spreadsheet script for sending values by email

This is an offshoot of a similar post here. A good answer was provided by Rivero but his code sends the values on the Google Spreadsheet's response sheet. I was wondering if instead the script would return values of the same row and column range specified by the code BUT from other sheet in the same spreadsheet. I'm really new to this and can't seem to find the right combination of codes to do so. Here is Rivero's code, I hope someone can help me accomplish this. Thanks in advance!
/* Send Confirmation Email with Google Forms */
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendConfirmationMail(e) {
try {
var ss, cc, sendername, subject, columns;
var header, message, value, textbody, sender, itemID, url;
// This is your email address and you will be in the CC
cc = "name#email.com";
// This will show up as the sender's name
sendername = "name to be displayed as sender";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
subject = "Choose an approppiate subject";
// This is the body of the auto-reply
message = "";
ss = SpreadsheetApp.getActiveSheet();
columns = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];
// This is the submitter's email address
sender = e.namedValues["Username"].toString();
// Only include form values that are not blank
for ( var keys in columns ) {
var key = columns[keys];
//Use this to look for a particular named key
if ( e.namedValues[key] ) {
if ( key == "Username" ) {
header = "The user " + e.namedValues[key] + " has submitted the form, please review the following information.<br />";
} else {
message += key + ' ::<br /> '+ e.namedValues[key] + "<br />";
}
}
}
}
textbody = header + message;
textbody = textbody.replace("<br>", "\n");
Logger.log("Sending email");
GmailApp.sendEmail(cc, subject, textbody,
{cc: cc, name: sendername, htmlBody: textbody});
} catch (e) {
Logger.log(e.toString());
}
}
It would better if you can name your sheet and use it instead of using active spreadsheet.
var sheet = SpreadsheetApp.openById('spreadsheetId').getSheetByName('name');
OR you can also use the sheet number to access it.
var sheet = SpreadsheetApp.openById('spreadsheetId').getSheets()[0];
After you have reference to the sheet, get the range for the column followed by data array:
var columnRange = sheet.getRange('a1Notation');
var dataArray = columnRange.getValues();
then iterating the data as per your convenience
for(var i=1; i<=dataArray.length; i++)
{
}

Row number of a variable in Spreadsheet (Apps Script)

In my Spreadsheet, I have taken the answers from the users and added a column to grade them. Now, I want to mail them the whole data they have entered and their respective grades. To do that, I have to know the Row number of the variable "key2" which will be changing for every response of the user. I am providing my code here. Some one please help me.
/* Send Confirmation Email with Google Forms */
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendConfirmationMail(e) {
var s1 = SpreadsheetApp.getActiveSpreadsheet();
var s2 = SpreadsheetApp.setActiveSheet(s1.getSheetByName("Sheet2"));
try {
var cc, sendername, subject, column2;
var message, value, textbody, sender;
// This is your email address and you will be in the CC
cc = Session.getActiveUser().getEmail();
// This will show up as the sender's name
sendername = "Quiz2win";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
subject = "Google Form Successfully Submitted";
// This is the body of the auto-reply
message += "We have received your details.<br />Thanks!<br /><br />";
column2 = s2.getRange(1,1,1,10).getValues()[0];
// This is the submitter's email address
sender = e.namedValues["Email Address"].toString();
// Only include form values that are not blank
for ( var keys in column2 ) {
var key2 = column2[keys];
if ( e.namedValues[key2] ) {
message += key2 + ' :: '+ e.namedValues[key2] + "<br />";
} else {
var key1 = s2.getValues();
message += key2 + ' :: ' + key1 + "<br/>";
}
}
textbody = message.replace("<br>", "\n");
GmailApp.sendEmail(sender, subject, textbody,
{cc: cc, name: sendername, htmlBody: message});
} catch (e) {
Logger.log(e.toString());
}
The range you are mentioning here s2.getRange(1,1,1,10) is basically getting only first row of data from the sheet.
Instead get all the rows and column values into a range variable and loop through the range for each row and send an email in the loop itself.
Check this documentation for more details.

How can i send confirmation mail send different from address?

I'm sending confirmation mail with following code in google docs scripts.
But It is sending from my personal gmail address. I need define different mail address. Cause I will use this for my company and mail need show like that sometest#companytsite.com
How can i do that?
My Code:
function Initialize() {
var triggers = ScriptApp.getScriptTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendConfirmationMail(e) {
try {
var ss, cc, sendername, subject, columns;
var message, value, textbody, sender;
// This is your email address and you will be in the CC
cc = Session.getActiveUser().getEmail();
// This will show up as the sender's name
sendername = "Your Name Goes Here";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
subject = "Google Form Successfully Submitted";
// This is the body of the auto-reply
message = "We have received your details.<br>Thanks!<br><br>";
ss = SpreadsheetApp.getActiveSheet();
columns = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];
// This is the submitter's email address
sender = e.namedValues["Email Address"].toString();
// Only include form values that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] ) {
message += key + ' :: '+ e.namedValues[key] + "<br />";
}
}
textbody = message.replace("<br>", "\n");
GmailApp.sendEmail(sender, subject, textbody,
{cc: cc, name: sendername, htmlBody: message});
} catch (e) {
Logger.log(e.toString());
}
}
According to the documentation: https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String,Object)
You should be able to pass in a from in the options.
GmailApp.sendEmail(sender, subject, textbody, {
from: "sometest#companytsite.com",
cc: cc,
name: sendername,
htmlBody: message
});
Nb. to avoid confusion sender should really be to
Now it also says that the email address you want to send it from must be an alias, to check you can print out getAliases() to see if it exists. If not you should be able to follow these instructions:
https://support.google.com/mail/answer/22370?hl=en