Can you please help me, How to send dynamic mail every latest entry in google sheet?
function CustomEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A2:C4");
var UserData = range.getValues();
for (i in UserData) {
var row = UserData[i];
var name = row[0];
var email = row[1];
var score = row[2];
MailApp.sendEmail(row[1], "Custom mail", "Hello " + name + ", This is an email report of your score. Your score is " + score);
}
}
Setup a trigger in your project: Trigger for "form submission". Whenever someone submits the form, script will send out the email to those whom the email wasn't sent. Also have a helper column in the sheet to update status for the script to filter out the people who already received the email, else others will keep receiving their scores everytime there's a form submission.
Related
I am trying to send conditional emails to people who submit a google form based on their responses.
Essentially, I need a code that reads one column and then sends an email message to the email address they supply. I need it to do this every time the form is submitted.
Here is what the sheet looks like: four column google sheet with timestamp, name, email address, and state fields
This is my first script so I've figured out how to send an email by pointing to a specific cell, but am having trouble figuring out how to have it trigger each time the form is submitted and how to point it to a full column rather than a specific cell.
Here is some code I've written that does not work. I'm really new to this so I'm sure there are plenty of beginner mistakes. :
var sheet = SpreadsheetApp.getActive();
ScriptApp.newTrigger("myFunction")
.forSpreadsheet(sheet)
.onFormSubmit()
.create();
if (lastRow.getvalues() == "NY") {
function SendEmail() {
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1").getRange("C2");
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'This is your NY Alert email!'; // Second column
var subject = 'Your NY Google Spreadsheet Alert';
MailApp.sendEmail(emailAddress, subject, message);
} }
else (lastRow.getvalues() == "MA") {
function SendEmail() {
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1").getRange("C2");
var emailAddress = emailRange.getValue();
// Send Alert Email.
var message = 'This is your MA Alert email!'; // Second column
var subject = 'Your MA Google Spreadsheet Alert';
MailApp.sendEmail(emailAddress, subject, message);
}
Thank you for any help, insight, or resources!
Try this:
function createTrigger() {
var sheet = SpreadsheetApp.getActive();
ScriptApp.newTrigger("myFunction")
.forSpreadsheet(sheet)
.onFormSubmit()
.create();
}
function myFunction(e) {
const list = ["NY", "MA"];
if (~list.indexOf(e.values[3]) {
MailApp.sendEmail(e.values[2], 'Your NY Google Spreadsheet Alert', 'This is your NY Alert email!');
}
}
Spreadsheet onFormSubmit Event Object
I'm trying to send an email with inline images to a series of users with myself in cc (myself#hotmail.com). I am trying to do this with the code written bellow. Everything seemed to work, but as soon as I added cc: 'myself#hotmail.com' it broke. My email gets send to the recipient 1x, but also to 'myself#hotmail.com' 8x. I cannot figure out what I am doing wrong, any help is much appreciated.
function sendEmails() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Emails").activate(); //makes sure your google sheets has the correct sheet open where you specify the emails and names
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); //defines spreadsheet to use
var lr = ss.getLastRow(); //gets last row on which there is data
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Template').getRange(1, 1).getValue() //gets email body from sheet 'template' which is defined in cell 1,1 -- make sure your sheet has same name else it won't work
var quotaLeft = MailApp.getRemainingDailyQuota(); //gets number of emails that you can still send
// Image URLs
var img1Url = "https://i.imgur.com/PRIVATE.png"; //CHANGE PRIVATE TAG
var img2Url = "https://i.imgur.com/PRIVATE.png"; //CHANGE PRIVATE TAG
// Fetch images as blobs, set names for attachments
var img1Blob = UrlFetchApp
.fetch(img1Url)
.getBlob()
.setName("img1Blob");
var img2Blob = UrlFetchApp
.fetch(img2Url)
.getBlob()
.setName("img2Blob");
//embeded image tags for email
var bodyImg1 = "<img src='cid:img1' style='width:1000px; height:1500px;'/>"; //specify img size here
var bodyImg2 = "<img src='cid:img2' style='width:1000px; height:1500px;'/>"; //specify img size here
if((lr-1) > quotaLeft){
Browser.msgBox("You have " + quotaLeft + " left and you're trying to send " + (lr-1) + " emails. Emails were not send"); //gives standard warning message if number of emails to be send exceeds limit
} else {
for (var i = 2; i<=lr;i++){
var currentEmail = ss.getRange(i, 1).getValue(); //gets email in excel sheet
var currentName = ss.getRange(i, 2).getValue(); //gets name in excel sheet
var subjectLine = "Invitation"; //title of email
var messageBody = templateText.replace("{name}", currentName); //replaces name in template with name of current cell, see templateText var
MailApp.sendEmail(currentEmail, subjectLine, subjectLine, {htmlBody: messageBody + bodyImg1 + bodyImg2, inlineImages:{img1: img1Blob,img2: img2Blob}, cc: 'myself#hotmail.com'});
} //close for loop
} //close else statement
} //close function
Solution:
MailApp.sendEmail({ to: currentEmail, subject: subjectLine, cc: 'myself#hotmail.com', htmlBody: messageBody + bodyImg1 + bodyImg2, inlineImages:{img1: img1Blob,img2: img2Blob}});
Currently, my script is updating all cells within the selected range with "YES" but I only want it to update cells that meet the if conditions. Any help would be much appreciated.
//Active spreadsheet var that can be used anywhere in the programme
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Get and check if there is an email address
function checkSendEmailAdd () {
//Getting the array of values
var activeSheet = ss.getActiveSheet();
var emailCol = activeSheet.getRange(2, 9, activeSheet.getLastRow() - 1, 2).getValues();
//Looping over the array of values
emailCol.forEach(function(val){
var email = val[0].toLowerCase();
var sentEmail = val[1];
//If the send date column is empty and the email column has a # within the string an email will be sent
if (email.indexOf("#") !== -1 && sentEmail == ""){
//Email contents
var subject = "Survey";
var body = "Hi" + "<br><br>" +
"Testing 123";
GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
//Update and set a new value in the sent email column
var newSetValue = "YES";
var updateSentEmail = activeSheet.getRange(2, 10, activeSheet.getLastRow() - 1, 1).setValue(newSetValue);
} else {
}
});
The problem I'm facing is that the sent column is updating every cell but I only want it to update the cells that have an email in the email column.
Image of what is being executed currently
Try it this way:
I tried to determine the columns from your question. I believe email was column one and sentMail was column two but if I'm wrong you can change them to whatever you need.
function sendEmail() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet0');
var vA=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn()).getValues();
var sentA=sh.getRange(2,2,sh.getLastRow()-1,1).getValues();
var html='';
for(var i=0;i<vA.length;i++) {
var email=vA[i][0].toString().trim().toLowerCase();
var sentEmail=vA[i][1];
if(email && email.indexOf("#")>-1 && !sentEmail){
var subject = "Survey";
var body = "Hi<br><br>Testing 123";
//GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
html+=Utilities.formatString('<br />%s -<br />Email: %s<br />Subject: %s<br />Body: %s<br /><hr/>', Number(i+1),email,subject,body);
sentA[i][0]="Yes";
}
}
sh.getRange(2,2,sh.getLastRow()-1,1).setValues(sentA);
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Emails Sent');
}
Spreadsheet before sending:
Spreadsheet after sending:
I removed the Gmail line and used a dialog to display the emails:
I am new to Google Scripts but am getting the gist of it pretty quickly. I am trying to automate ordering of toner for our commercial printer. I set up a Google Form with 4 scale questions, one for each color (CMYK), with multiple choices from 1 through 5 toner cartridges.
Then, in the Google Spreadsheet that records responses, I created a script (mainly from internet examples) that gets the last entry of the spreadsheet (bottom row) and sends an email with the amount of toner cartridges needed, with a trigger onFormSubmit().
When I use the form and hit the submit button, nothing happens. There seems to be a disconnect between the form and the spreadsheet? Maybe some triggers are not working? I tried using the triggers from the script editor and also the programmable triggers and it still does not work from the form submission.
The "ScriptApp" part of the script's trigger doesn't seem to be recognized by the Google Scripts editor, as it's not in a particular color, different from the other code, which makes me wonder if I have to write some form of #include statement or something? All the internet examples show ScriptApp in color.
No bugs are found when "compiling"...
function sendFormByEmail(e)
{
ScriptApp.newTrigger("sendFormByEmail").forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet()).onFormSubmit().create();
var email = "example#email.com";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,2,1,s.getLastColumn()-1).getValues()[0];
var colors = s.getRange(s.getLastRow(),2,s.getLastRow(),s.getLastColumn()-1).getValues()[0];
var message = "";
var subject = "Toner order";
for(var i in headers)
message += headers[i] + ': ' + colors[i] + "\n\n";
MailApp.sendEmail(email, subject, message);
}
This is the answer that definitely works. Had to clear past triggers first, else it would send multiple emails because it was creating a new trigger with each submission:
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("sendFormByEmail").forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet()).onFormSubmit().create();
function sendFormByEmail(e)
{
var email = "example#email.com";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,2,1,s.getLastColumn()-1).getValues()[0];
var colors = s.getRange(s.getLastRow(),2,s.getLastRow(),s.getLastColumn()-1).getValues()[0];
var message = "";
var subject = "toner order";
for(var i in headers) {
message += headers[i] + ': ' + colors[i] + "\n\n";
}
MailApp.sendEmail(email, subject, message);
}
I have a Google form which submits to a spreadsheet. I then have written this code which sends an email with the results. Can anyone tell me how I make the email be submitted by the person who submitted the form?
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, subject, columns;
var message, value, textbody, sendername, sender;
// This is my email address and I will be in the CC
cc = e.namedValues["Username"].toString();
// This will show up as the sender's name
sendername = e.namedValues["Name"].toString();
subject = "Ticket Submitted";
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["Username"].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());
}
}
This is not possible, nor it should be. You want to impersonate someone else without their consent.
The archaic email system unfortunately allows that, therefore making easier the life of spammers and phishing scams. But Google and other Internet companies work hard to prevent and filter this kind of emails.
Bottom line, you will not be able to send an email as somebody else from a Google app unless it's an authorized account in your Gmail.
The best you can do is set the reply-to address.