Send range via email with google script - google-apps-script

I want to send range by email
For example:
https://docs.google.com/spreadsheets/d/1GH5r0sY_Z-15M479xG12yCUZaV0NRU8jpkWAxPNBuwU/edit?usp=sharing
I tried this:
function sendInvoiceList(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Invoice").getRange("A1:B10").getValues();
var message = sheet;
var email_subj = "Invoice " + Utilities.formatDate(new Date(), "GMT+1:00", "dd.MM.yyyy");
MailApp.sendEmail({
to: "user#gmail.com",
subject: email_subj,
htmlBody: "Please send us this list:<br><br><br>" + message
});
}
The system send this:
textA1,textA2,textA3,textA4,textA5,textA6,textA7,textA8,textA9,textA10
I need value in range A1:B10 but the system only A1 separated by comma I need in column format.
How do it?
Thanks for support
Angelo

Your setting message equal to a two dimensional array you need to rethink that. I think this maybe closer to what you want. I tested it with some data of my own but don't know what you have. Share an image of your spreadsheet if you need more assistance.
function sendInvoiceList(){
var ss=SpreadsheetApp.getActive()
var sh=ss.getSheetByName("Invoice");
var rg=sh.getRange("A1:B10")
var vA=rg.getValues();
var html='<style>td,th{border:1px solid black;}</style><table>';
vA.forEach(function(r,i){
html+='<tr>';
r.forEach(function(c,j){
if(i=0) {
html+=Utilities.formatString('<th>%s</th>',c)
}else{
html+=Utilities.formatString('<td>%s</td>',c)
}
});
html+='</tr>';
});
html+='</table>';
var email_subj = "Invoice " + Utilities.formatDate(new Date(), "GMT+1:00", "dd.MM.yyyy");
MailApp.sendEmail({to: "user#gmail.com",subject: email_subj,htmlBody: "Please send us this list:<br><br><br>" + html});
//SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'Display');//Just a dialog for testing the html
}

Related

How do I change positions of charts that I have pulled from a google sheet, to position them in an email using appscript

Im currently taking charts from the 2nd tab of my google sheet to embed them into an email using appscript. I was wanting to know how can I make the position of the charts permanent within the email as the images move depending on the size of the browser window. please see my current script and associated images.
function emailChartSource(){
const sheet = SpreadsheetApp.getActiveSpreadsheet();
const sheetName = sheet.getSheetByName('At a Glance');
const charts = sheetName.getCharts();
var bodyEmail = "Hi Team,<br> Below is an overview of the testing efforts for UAT Wireless<br>"
var currentDate = Utilities.formatDate(new Date(), 'America/Denver', 'M/d/yy');
var imgcontainer = {};
var bodyCharts = "";
var chartcount = charts.length
for(var chartNo=0; chartNo <=chartcount-1;chartNo++){
var img = charts[chartNo].getAs("image/png")
imgcontainer["chart" + (chartNo+1)]=img
bodyCharts = bodyCharts + "<img src='cid:chart" + (chartNo+1)+"'>";
}
bodyEmail = bodyEmail + bodyCharts;
MailApp.sendEmail({
to: "someemail#gmail.com",
subject: "UAT Wireless Testing Status Report as of " + currentDate + " - Boost Prepaid",
htmlBody: bodyEmail,
inlineImages: imgcontainer,
});
}
Incorrect Display
How I would like it to display

Auto-direct emails to specific addresses on Google Form submit

This is my first post so apologies in advance if I am posting to the wrong place or asking a question that has been answered elsewhere - go easy on me!
In a nutshell, I have a Google Form and a connected Google Sheet. I need to automate it so that, when a new form is submitted, an email is sent to a specific colleague (the student's supervisor). I have had a good go myself but am now totally stuck!
I have created the form, linked it to a sheet, written the code, added the trigger and tested by submitting a form. Nothing happened! No error messages, just... nothing!
Any advice hugely appreciated. I am very new to this and still taking baby steps.
The code I have cobbled together (which is probably full of errors!) is as follows:
function wa132657(e) {
//setup the spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
//get the range from OnFormSubmit
var range = e.range;
Logger.log("DEBUG: the range is "+range.getA1Notation());//DEBUG
// get the data for the range
var response = row.getValues();
// get the supervisor name from the form submission
var supervisor = response[0][1];
Logger.log("DEBUG: Supervisor = "+supervisor);// DEBUG
// get the emails list
var emailSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SupEmails");
// get ALL the data from this sheet
var emaildata = emailSheet.getDataRange().getValues();
// check how many rows of data
var emailLastRow = emailSheet.getLastRow();
// start the loop through the emails data
for (var i=1; i<emailLastRow; i++){
// if the supervisor is equal to SupervisorEmail
if (supervisor == emaildata[i][0]){
// there is a match
//Next, get the email address
var emailSupervisor = emaildata[i][1];
Logger.log("DEBUG: supervisor = "+emaildata[i][0]+", email address: "+emailSupervisor);// DEBUG
// Finally, send the Email.
var theirName = e.values[2];
var theirProgramme = e.values[3];
var theAbsenceReason = e.values[8];
var theAbsenceStart = e.values[5];
var theAbsenceEnd = e.values[6];
var subject = "Student Absence Report";
var message = "New Absence Report: " + theirName + " \n Programme: " + theirProgramme; + " \n\n
Reason for Absence: \n" + theAbsenceReason + " \n Start of Absence" + theAbsenceStart + "\n End of Absence:" + theAbsenceEnd;
MailApp.sendEmail(emailSupervisor, subject, message);
}
}
}

How to add an existing chart in sheets while sending an email

I want a Line chart from my spreadsheet to appear in the email.
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Agent Report - Monthly")
var startRow = 3; // First row of data to process since there is a header row
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Agent Report - Monthly").getRange("D3");
var emailAddress = emailRange.getValues();
var chartImg = Charts.newLineChart.setRange(12, 8) //This Throws an error
var subject = "Agent Report - Monthly"; // This is the subject of the email
var greeting_text = 'Hey Please find the below Report '+'</b><br><br>';
var text = greeting_text;
text+=SheetConverter.convertRange2html(sheet.getRange(startRow, 3 ,10,8));
text+='<br>';
var options = {
htmlBody: text,
noReply:true
};
MailApp.sendEmail({
to: "xxx#der.com",
subject: subject,
htmlBody: options,
inlineImages: {
chartImg: chartImage,
}
});
}
When I try to add the chart to the variable ChartImg in line 7, it throws an exception.
If I understand correctly, you already have the chart created without issue in the spreadsheet, and you only want to get it as an image. To do this you need a reference to the chart in the sheet, and then use the getAs() method on the chart's blob, it would look something like this for you:
var chart = sheet.getCharts()[0]; // assuming you only have that chart, this is just to get the chart's reference.
var options = {
htmlBody: "<img src='cid:chart' style='width:24px; height:16px;'/>",
noReply:true
};
var chartImg = chart.getBlob().getAs('image/png').setName("areaBlob");
// Then you would add it in the body of the email as an attachment
MailApp.sendEmail({
to: "xxx#der.com",
subject: subject,
htmlBody: options,
inlineImages: {
chart: chartImg,
}
});
In the following link you can find a more in depth explanation and example: Chart image in email from Google spreadsheet with google-apps-script returns white image

cell reference out of range on Email Notifications

I have the below code for sending a email notification when a cell changes, but it is always returning Cell reference out of range(line 5, file "Missing Cuts Report"). Can anyone advise if i need to change the code or if there is a way of getting it to stop failing and still send the email notification through. The trigger i use is OnChange because when it was on OnEdit it came back with error service invoked too many times on line 17 MailApp.sendEmail(recipients, subject, msgPlain, { htmlBody: body }). Any help would really be appreciated.
function sendEnailNotification(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = ss.getActiveCell().getA1Notation();
var cellvalue = ss.getActiveCell().getValue().toString();
if(SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName() == "Missing Cuts Report") {
if(cell.indexOf('B')!=-1){
if(cellvalue > "") {
//Define Notification Details
var recipients = "email#email.co.uk;
var subject = "New Missing Cut Added";
var body = 'A new line has been added on the Missing Cuts Report on line <b>' + cell + '</b> - click here to view the update';
var msgPlain = body.replace(/(<([^>]+)>)/ig, ""); // clear html tags for plain mail
MailApp.sendEmail(recipients, subject, msgPlain, { htmlBody: body });
}
}
}
}
Hi this is a not a very good way of achieving the result you want. Not really to sure what you are after. I have however made some adjustments to your code with notes after the closing braces. This is not an answer to your original problem. Just some hints.
function sendEmailNotification() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = ss.getActiveCell().getA1Notation();
var cellvalue = ss.getActiveCell().getValue().toString();
if(sheet.getName() === "Missing Cuts Report") {
//if(cell.indexOf('B')!== -1){
if(cellvalue !== "") {
//Define Notification Details
var recipients = "email#address.org";
var subject = "New Missing Cut Added";
var body = 'A new line has been added on the Missing Cuts Report on line <b>' + cell + '</b> - click here to view the update';
var msgPlain = body.replace(/(<([^>]+)>)/ig, ""); // clear html tags for plain mail
MailApp.sendEmail(recipients, subject, msgPlain, { htmlBody: body });
} // "<" and ">" are not for comparing string values. (At least not in this case.)
//} //IndexOf will always result in -1 if you are looking for just "B" as your result will always be "B1/B2/B3/ect."
} // Already have the sheet object, no need to call again.
}

Emailing a chart from a Google spreadsheet with apps script

I've search high and low for an answer but without an y luck. Got a Google spreadsheet which uses apps script to connect to a database to pull in some raw data into a spreadsheet. I then use various spreadsheet formulas to manipulate that data and then final create a chart.
My next challenge is that I want to be able to embed that chart into an email via apps script and send it as an HTML email..
Is this at all possible or should I start looking for some other solution?
Thanks!
Mikael
Here is the code I used to email charts.
Please note that you need to give everyone with the link access to the spreadsheet. If not, you'll get an image in the email stating user is not signed in. (very annoying that there's no workaround to this)
function emailCharts(sheet,emails,emailSubject){
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++){
chartBlobs[i]= charts[i].getAs("image/png").setName("chartBlob"+i);
emailBody= emailBody + "<img src='cid:chart"+i+"'><br>";
emailImages["chart"+i]= chartBlobs[i];
}
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody,
inlineImages:emailImages});
}
Make the spreadsheet Public and run the script. Modified version of the script pasted below with comments
enter code here function
emailCharts(sheet,emails,emailSubject){
var targetspreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Active spreadsheet of the key file
var sheet = targetspreadsheet.getSheetByName('Sheet1'); // Change the sheet name
var emailSubject = 'test';
var emails = 'test#test.com'; // 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});
}
As the Charts Service appears to only be a partial implementation of EmbeddedChart used in SpreadsheetApp Service not all of the ChartTypes and options are implemented, meaning charts might render differently than they do in Google Sheets. The modified version of the previous answer below will mean charts are included in emails as images as they appear in Google Sheets. As this solution also uses an authentication token generated by the script the view permissions on the Google Sheet does not have to be changed.
// Based on https://stackoverflow.com/a/22200230/1027723
function emailChartUsingImageUrl(){
const idt = SpreadsheetApp.getActive().getId();
const sheet = SpreadsheetApp.getActiveSheet();
const charts = sheet.getCharts();
// setup some variables for our email
const chartBlobs = new Array();
const emailImages = {};
let emailBody = "Charts<br>";
// setup our call to fetch the chart image
const token = ScriptApp.getOAuthToken(); // project requires https://www.googleapis.com/auth/spreadsheets scope
const baseUrl = `https://docs.google.com/spreadsheets/d/${idt}/embed/oimg?access_token=${token}&disposition=ATTACHMENT&bo=false&filetype=png&oid=`;
// for each chart fetch the download image as a blob and appended to our email body
charts.forEach(function(chart, i){
// NEW BIT
const url = baseUrl + chart.getChartId();
chartBlobs[i] = UrlFetchApp.fetch(url).getBlob();
emailBody += "<p align='center'><img src='cid:chart"+i+"'></p>";
emailImages["chart"+i]= chartBlobs[i];
});
// Send email with inline images
MailApp.sendEmail({
to: "me#example.com",
subject: "Email Charts - get chart from image url",
htmlBody: emailBody,
inlineImages:emailImages});
}