modify to email from a list contained in the sheet - email

I need to modify this code to email the people in a list held on a sheet named "Data" under column 1 (A),
Is this possible while still being able to email out the charts?
function
emailCharts(sheet,emails,emailSubject){
var targetspreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Active spreadsheet of the key file
var sheet = targetspreadsheet.getSheetByName('Overview'); // Change the sheet name
var emailSubject = 'absence review ';
var emails = ""; // your email ID
var charts = sheet.getCharts();
if(charts.length==0){
MailApp.sendEmail({
to: emails,
subject: "ERROR:"+emailSubject,
htmlBody: "No charts in the spreadsheet"});
return;
}
var chartBlobs=new Array(charts.length);
var emailBody="Charts<br>";
var emailImages={};
for(var i=0;i<charts.length;i++){
var builder = charts[i].modify();
builder.setOption('vAxis.format', '#');
var newchart = builder.build();
chartBlobs[i]= newchart.getAs('image/png');
emailBody= emailBody + "<p align='center'><img src='cid:chart"+i+"'> </p>";
emailImages["chart"+i]= chartBlobs[i];
}
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody,
inlineImages:emailImages});
}
Any help please

var email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data").getRange(1,1).getValue();

Related

Auto Email Function for Google Sheets Mobile

I am trying to run an amazing script shared by Lauren Script for Google sheets (auto email function) and have an issue. I'm fairly new on stackoverflow so let me know if i need to ask this in another way if I'm breaking any norms? I have setup and successfully edited this script to do what i need it to do. I have a team that will be using this on mobile devices. I tried it and it did not work! can you help or point me in the right direction?
This is for a task list, when someone then selects a checkbox it sends any added notes and details to team leaders (and as per the script then unchecks the box). The checkbox is great as there is one per row. But open to any suggestions
Sorry for the lack of clarity, and thanks #TheMaster for helping out here. Code is below, but sounds like i am trying to do the impossible? Thought i would be able to do this with google sheets but it seems it is not possible on sheets android ap. I am not very advanced and might need to abandon the project! Any suggestions maybe even to do this in a different method?
function EmailNotification(e) {
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Deliveries'); //source sheet
var columnb = sheet.getRange('J:J'); //Column with check boxes
var columnbvalue = columnb.getValues();
var notifysheet = ss.getSheetByName('Responses'); //destination sheet
var data = [];
var rownum =[];
//Condition check in B:B (or check box column); If true copy the same row to data array
for (i=0; i<columnbvalue.length;i++) {
if (columnbvalue[i] == 'true') {
var columnb2 = sheet.getRange('J2:J');
columnb2.setValue('false');
// What you want to say in the pop up alert
var response = ui.alert('Hold Up!\n Are you sure you want to send an email to team leaders for this delivery?', ui.ButtonSet.YES_NO);
if (response == ui.Button.YES) {
data.push.apply(data,sheet.getRange(i+1,1,1,20).getValues());
//Copy matched ROW numbers to rownum
rownum.push(i);
//Copy data array to destination sheet
notifysheet.getRange(notifysheet.getLastRow()+1,1,data.length,data[0].length).setValues(data);
var activeRow = notifysheet.getLastRow();
var suppliername = notifysheet.getRange(activeRow, 1).getDisplayValue(); // The number is the column number in the destination "responses" sheet that you want to include in the email
var owner = notifysheet.getRange(activeRow, 3).getDisplayValue();
var recievedby = notifysheet.getRange(activeRow, 8).getDisplayValue();
var instructions = notifysheet.getRange(activeRow, 5).getDisplayValue();
var status = notifysheet.getRange(activeRow, 7).getDisplayValue();
var notes = notifysheet.getRange(activeRow, 9).getDisplayValue();
var email = notifysheet.getRange(activeRow, 4).getDisplayValue();
var subject = 'Delivery completed!'
//Body of the email message, using HTML and the variables from above
var message =
'<br><br><div style="margin-left:40px;">Hello '+ owner +'</div>'
+'<br><br><div style="margin-left:40px;">A delivery you requested has been fulfilled</div>'
+'<br><br><div style="margin-left:40px;"><h3 style="text-decoration: underline;">Recieved Name: '+ recievedby +'</h3></div>'
+'<div style="margin-left:40px;">Supplier: '+ suppliername +'</div>'
+'<div style="margin-left:40px;">Special instructions you added: '+ instructions +'</div>'
+'<div style="margin-left:40px;">Status: '+ status +'</div>'
+'<div style="margin-left:40px;">Notes: '+ notes +'</div>'
+ '<br><br><div style="margin-left:40px;">ヽ(⌐■_■)ノI Did It ♪♬</div>';
MailApp.sendEmail(
email,
subject,
"",
{
htmlBody: message,
name: 'Shop Alerts', //The name you want to email coming from
});
}
}
}
}
Mobile apps don't support ui or alerts. You just need to remove them.
function EmailNotification(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Deliveries'); //source sheet
var columnb = sheet.getRange('J:J'); //Column with check boxes
var columnbvalue = columnb.getValues();
var notifysheet = ss.getSheetByName('Responses'); //destination sheet
var data = [];
var rownum = [];
//Condition check in B:B (or check box column); If true copy the same row to data array
for (let i = 0; i < columnbvalue.length; i++) {
if (columnbvalue[i][0] === true) {
//modified to strict equality
var columnb2 = sheet.getRange('J2:J');
columnb2.setValue('false');
data.push.apply(data, sheet.getRange(i + 1, 1, 1, 20).getValues());
//Copy matched ROW numbers to rownum
rownum.push(i);
//Copy data array to destination sheet
notifysheet
.getRange(notifysheet.getLastRow() + 1, 1, data.length, data[0].length)
.setValues(data);
var activeRow = notifysheet.getLastRow();
var suppliername = notifysheet.getRange(activeRow, 1).getDisplayValue(); // The number is the column number in the destination "responses" sheet that you want to include in the email
var owner = notifysheet.getRange(activeRow, 3).getDisplayValue();
var recievedby = notifysheet.getRange(activeRow, 8).getDisplayValue();
var instructions = notifysheet.getRange(activeRow, 5).getDisplayValue();
var status = notifysheet.getRange(activeRow, 7).getDisplayValue();
var notes = notifysheet.getRange(activeRow, 9).getDisplayValue();
var email = notifysheet.getRange(activeRow, 4).getDisplayValue();
var subject = 'Delivery completed!';
//Body of the email message, using HTML and the variables from above
var message =
'<br><br><div style="margin-left:40px;">Hello ' +
owner +
'</div>' +
'<br><br><div style="margin-left:40px;">A delivery you requested has been fulfilled</div>' +
'<br><br><div style="margin-left:40px;"><h3 style="text-decoration: underline;">Recieved Name: ' +
recievedby +
'</h3></div>' +
'<div style="margin-left:40px;">Supplier: ' +
suppliername +
'</div>' +
'<div style="margin-left:40px;">Special instructions you added: ' +
instructions +
'</div>' +
'<div style="margin-left:40px;">Status: ' +
status +
'</div>' +
'<div style="margin-left:40px;">Notes: ' +
notes +
'</div>' +
'<br><br><div style="margin-left:40px;">ヽ(⌐■_■)ノI Did It ♪♬</div>';
MailApp.sendEmail(email, subject, '', {
htmlBody: message,
name: 'Shop Alerts', //The name you want to email coming from
});
}
}
}

Select case to email different sheet depending on selection

I'm using the following script that converts a sheet to a .csv file and then emails it to a person.
RANGE="A1:AC20";
SHEET_NAME="Biomisters.csv";
//Types available : pdf,csv or xlsx
EXPORT_TYPE="csv";
function EmailBiomisters() {
//Assign The Spreadsheet,Sheet,Range to variables
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheet=ss.getSheetByName(SHEET_NAME);
var range=sheet.getRange(RANGE);
//Range values to export
var values=range.getValues();
//Create temporary sheet
var sheetName=Utilities.formatDate(new Date(), "GMT", "MM-dd-YYYY hh:mm:ss");
var tempSheet=ss.insertSheet(sheetName);
//Copy range onto that sheet
tempSheet.getRange(1, 1, values.length, values[0].length).setValues(values);
//Save active sheets (Unhidden)
var unhidden=[];
for(var i in ss.getSheets()){
if(ss.getSheets()[i].getName()==sheetName) continue;
if(ss.getSheets()[i].isSheetHidden()) continue;
unhidden.push(ss.getSheets()[i].getName());
ss.getSheets()[i].hideSheet();
}
//Authentification
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var url="https://docs.google.com/spreadsheets/d/"+ss.getId()+"/export?format="+EXPORT_TYPE;
//Fetch URL of active spreadsheet
var fetch=UrlFetchApp.fetch(url,params);
//Get content as blob
var blob=fetch.getBlob();
var mimetype;
if(EXPORT_TYPE=="pdf"){
mimetype="application/pdf";
}else if(EXPORT_TYPE=="csv"){
mimetype="text/csv";
}else if(EXPORT_TYPE=="xlsx"){
mimetype="application/xlsx";
}else{
return;
}
//Send Email
var sheet1 = ss.getSheetByName('data').getRange("B1").getValue();
//var mesbody = sheet1.getRange("B1");
GmailApp.sendEmail('test#test.com',
'Biomisters.csv',
sheet1,
{
attachments: [{
fileName: "Biomisters" + "."+EXPORT_TYPE,
content: blob.getBytes(),
mimeType: mimetype
}]
});
//Reshow the sheets
for(var i in unhidden){
ss.getSheetByName(unhidden[i]).showSheet();
}
//Delete the temporary sheet
ss.deleteSheet(tempSheet);
}
What i want to achieve is to be able to select a SHEET_NAME from a drop-down in cell A3.
In this instance SHEET_NAME is "Biomisters.csv", but I have ten other sheets to choose from.
I then need to change every instance in the code where "Biomisters.csv" is mentioned to the current selection in A3.
The RANGE doesn't change, the email address to send too doesn't change either.
The only things that would change on selection are:
SHEET_NAME; email subject line; email attachment
P.S. I take no credit for the above code. I found it online and edited it in the most basic form to suit my needs.
Use ss.getSheetByName("Name of the sheet with the dropdown").getRange("A3").getValue() to retrieve the chosen value of the dropdown dinamically
Use SHEET_NAME.split(".")[0] to retrieve the name of the sheet without extension - see here
Replace the hardcoded subjet with a variable
Sample:
RANGE="A1:AC20";
//Types available : pdf,csv or xlsx
EXPORT_TYPE="csv";
function EmailBiomisters() {
//Assign The Spreadsheet,Sheet,Range to variables
var ss=SpreadsheetApp.getActiveSpreadsheet();
var SHEET_NAME=ss.getSheetByName("Name of the sheet with the dropdown").getRange("A3").getValue();//"Biomisters.csv";
var sheet=ss.getSheetByName(SHEET_NAME);
var range=sheet.getRange(RANGE);
//Range values to export
var values=range.getValues();
//Create temporary sheet
var sheetName=Utilities.formatDate(new Date(), "GMT", "MM-dd-YYYY hh:mm:ss");
var tempSheet=ss.insertSheet(sheetName);
//Copy range onto that sheet
tempSheet.getRange(1, 1, values.length, values[0].length).setValues(values);
//Save active sheets (Unhidden)
var unhidden=[];
for(var i in ss.getSheets()){
if(ss.getSheets()[i].getName()==sheetName) continue;
if(ss.getSheets()[i].isSheetHidden()) continue;
unhidden.push(ss.getSheets()[i].getName());
ss.getSheets()[i].hideSheet();
}
//Authentification
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var url="https://docs.google.com/spreadsheets/d/"+ss.getId()+"/export?format="+EXPORT_TYPE;
//Fetch URL of active spreadsheet
var fetch=UrlFetchApp.fetch(url,params);
//Get content as blob
var blob=fetch.getBlob();
var mimetype;
if(EXPORT_TYPE=="pdf"){
mimetype="application/pdf";
}else if(EXPORT_TYPE=="csv"){
mimetype="text/csv";
}else if(EXPORT_TYPE=="xlsx"){
mimetype="application/xlsx";
}else{
return;
}
//Send Email
var sheet1 = ss.getSheetByName('data').getRange("B1").getValue();
//var mesbody = sheet1.getRange("B1");
var subject = SHEET_NAME;
var nameWithoutExtension = SHEET_NAME.split(".")[0];
GmailApp.sendEmail('test#test.com',
subject,
sheet1,
{
attachments: [{
fileName: nameWithoutExtension + "."+EXPORT_TYPE,
content: blob.getBytes(),
mimeType: mimetype
}]
});
//Reshow the sheets
for(var i in unhidden){
ss.getSheetByName(unhidden[i]).showSheet();
}
//Delete the temporary sheet
ss.deleteSheet(tempSheet);
}

MailApp.sendEmail function runs without errors but no emails are sent

The below script runs without any visible error, but no emails are sent. Any ideas as to why?
function sendEmailLoop() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
sheets.forEach(function(sheet) {
var range = sheet.getDataRange();
if (sheet.getName() == "Summary") //Disregard tab named 'Summary'
{
}
else {
var range = sheet.getDataRange(); //to set the range as array
var values = range.getDisplayValues(); //to get the value in the array
var lastRow = range.getLastRow();
var ss = SpreadsheetApp.getActiveSpreadsheet(); //declare the spreadsheet
var sheet = ss.getSheetByName("Sheet1");
var Title = values[0][0]; //[Title] cell A1
var URL = values[0][1]; //[URL] cell B1
var i;
var logContent = '';
for (i = 3; i < lastRow; i++) {
var Name = values[i][0]; //[Name] cell A++
var Email = values[i][1]; // [Email] cell B++
Logger.log('to: ' + Email);
Logger.log('subject: ' + Name + Title + 'Test');
Logger.log('message: ' + 'This is a test message for the training that can be found at ' + URL);
/*
MailApp.sendEmail({
to: Email,
subject: Name + Title + 'Test',
message: 'This is a test message for the training that can be found at ' + URL});
*/
}; //end for loop - email tab data
}; // end 'else'
}); // end function(sheet)
} // end SendEmailLoop()
Here is the Stackdriver log of a successful execution (success meaning no errors, but still no emails are sent):
The structure of the spreadsheet associated with the script:
Note - an earlier version of this script didn't include the sheets.forEach() method call (ie, to loop through each tab of the spreadsheet) and the emails were sent fine.
Could the lack of emails being sent or received be related to the fact that I have many sheets and this function is looping through them?
function sendEmailLoop() {
var exclA=['Summary'];
var ss=SpreadsheetApp.getActive();
var sheets=ss.getSheets();
sheets.forEach(function(sheet) {
if (exclA.indexOf(sheet.getName())==-1) {
var range=sheet.getDataRange();
var values=range.getDisplayValues();
var lastRow=range.getLastRow();
var Title=values[0][0];
var URL=values[0][1];
var logContent='';
for (var i=3; i <values.length; i++) {
var Name=values[i][0];
var Email=values[i][1];
Logger.log('to: %s\nsubject: %s %s Test\nmessage: %s This is a test message for the training that can be found at %s',Email,Name,Title,URL);
/*
MailApp.sendEmail({
to: Email,
subject: Name + Title + 'Test',
message: 'This is a test message for the training that can be found at ' + URL});
*/
}
}
});
}
Answer:
You need to uncomment your MailApp code.
Code changes:
I tested your code and it seems to run without issue for me, including the receipt of the emails, only that the code comments around your MailApp call need to be removed (the /* and the */).
I would also suggest adding a conditional line before you send the email in the event .getDataRange() obtains seemingly empty rows:
if (Email == "") {
continue;
};
MailApp.sendEmail({
to: Email,
subject: Name + Title + 'Test',
message: 'This is a test message for the training that can be found at ' + URL});
References:
JavaScript Comments

Unable to add inline image to email in google apps script

I'm new to Google Apps script and am trying to add an image inline to an automated response email.
The auto reply works perfectly, the main text of the email formats well in plain text and html.
the problem i'm facing is that the image does not appear.
my code:
// This constant is written in column Y for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Data'))
var startRow = 2; // First row of data to process
// Fetch the range
var dataRange = sheet.getRange("L2:L1000")
var dataRange2 = sheet.getRange("K2:K1000")
var dataRange3 = sheet.getRange("O2:O1000")
var dataRange4 = sheet.getRange("Y2:Y1000")
var dataRange5 = sheet.getRange("B2:B1000")
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var data2 = dataRange2.getValues();
var data3 = dataRange3.getValues();
var data4 = dataRange4.getValues();
var data5 = dataRange5.getValues();
for (var i = 0; i < data.length; ++i) {
var yesno = data2[i]
if(yesno == "Yes"){
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp
.fetch(TFlogoUrl)
.getBlob()
.setName("TFlogoBlob");
var emailAddress = data[i];
var ShipID = data3[i];
var cmdrID = data5[i];
var TFmsg = "Hi " + cmdrID + ",/n /nThank you for signing up to The Fatherhoods Lost Souls Expedition./n /nYour unique Ship ID is: " + ShipID + "/n /nWe look forward to seeing you on the expedition CMDR!/n /nFly Safe,/nThe Lost Souls Expedition team.";
var htmlTFmsg = "Hi " + cmdrID + ",<br> <br>Thank you for signing up to The Fatherhoods Lost Souls Expedition.<br> <br>Your unique Ship ID is: " + ShipID + "<br> <br>We look forward to seeing you on the expedition CMDR!<br> <br>Fly Safe,<br>The Lost Souls Expedition team.<br><img src='cid:TFlogo'>";
emailSent = data4[i]; // email sent (column Y)
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "Lost Souls Expedition Sign up confirmation";
MailApp.sendEmail(emailAddress,subject,TFmsg,{
htmlBody: htmlTFmsg,
inlineImage:
{
TFlogo:TFlogoBlob
}
});
sheet.getRange("Y" + (startRow + i)).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
}
How about this modification?
Modification points:
You cannot retrieve the file blob from this URL var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. If you want to retrieve the file blob from URL, please use var TFlogoUrl = "http://drive.google.com/uc?export=view&id=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. 1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287 is the file ID.
As an another method, from the file ID, it is found that the values of getSharingAccess() and getSharingPermission() are ANYONE_WITH_LINK and VIEW, respectively. So you can also retrieve the blob using var TFlogoBlob = DriveApp.getFileById("1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287").getBlob().setName("TFlogoBlob");. I recommend this.
When you want to use the inline image to email, please modify from inlineImage to inlineImages.
The script which reflected above points is as follows.
Modified script:
Please modify your script as follows.
From:
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp.fetch(TFlogoUrl).getBlob().setName("TFlogoBlob");
To:
var id = "1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = DriveApp.getFileById(id).getBlob().setName("TFlogoBlob");
And
From:
inlineImage: {TFlogo:TFlogoBlob}
To:
inlineImages: {TFlogo:TFlogoBlob}
References:
sendEmail(recipient, subject, body, options)
If I misunderstand your question, please tell me. I would like to modify it.

Programming google app script to trigger at a specific time by displaying spreadsheet in email body

I'm sending a spreadsheet in the body of an email everyday. I completed the email portion, but now im trying to program the trigger to set off at 1:15pm everyday. I'm not sure how to implement the code to trigger with the email?
'function nearMinute(minute) {
var sendRead = ScriptApp.newTrigger("sendRead1pm")
.timeBased()
.atHour(13)
.everyDays(1) // Frequency is required if you are using atHour() or atMinute()
.create();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Totals");
var subjecttable = UrlFetchApp.fetch("https://docs.google.com/spreadsheet/pub?
key=XXXXXXXXXXXXXXXXXXXXXXXXXXX=true&gid=1&output=html");
var htmltable = subjecttable.getContentText();
var fromName = "DoNotReply - email";
var rowData = ss.getRange("B16").getValues()[0];
var emailAddress = "emailaddress#gmail.com"; // First column
var message = {htmlBody: htmltable, name: fromName}; // Second column
var subject = "TEST $" + rowData;
MailApp.sendEmail(emailAddress, subject, "", message);
}`
You don't have to code your trigger. Make your function to do the email part and set up the trigger manually. In your script, go to Resources --> Current Project's Triggers and then add a trigger. This is the easiest.