I have a script to send the active sheet of a workbook sheet in excel to a mailing list
function SendaMailOK(){
var DateName1 = SpreadsheetApp.getActiveSheet( ).getRange("B4").getValue();
var newdate = new Date(SpreadsheetApp.getActiveSheet( ).getRange("B4").getValue());
var d = Utilities.formatDate(newdate, Session.getScriptTimeZone(), "dd-MM-yyyy");
var f = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Adresses Mail');
//Send active sheet as email attachment
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getSheetName();
var token = ScriptApp.getOAuthToken();
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=false" + "&exportFormat=xlsx";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
var subject = "Rapport du " + d;
var body = "Bonjour, \n\nCi-joint le rapport, \n \nCdlt";
var n=f.getLastRow();
for (var i = 1; i < n+1 ; i++ ) {
var emailAddress = f.getRange(i,1).getValue();
MailApp.sendEmail(emailAddress,subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"application//xlsx"}]});
}
};
After modifying my file, I need to send 2 sheets of the workbook as attachments and no longer the active sheet.
Problem, I can't adapt the script.
Thanks for your help.
Sending multiple files
I played around with your code a little and found a way to do it taking from some of the work that Tanaike has done in this area. If you don't know where to look for stuff like this then always check out Tanaikes work because I've always found it to be well done.
function SendaMailOK() {
const ss = SpreadsheetApp.getActive();
let esh = ss.getSheetByName('Sheet3');
let ssID = ss.getId();
let token = ScriptApp.getOAuthToken();
let emails = esh.getRange(1, 1, esh.getLastRow()).getValues().flat().join(',');
const names = ['Sheet0', 'Sheet1'];
const shts = ss.getSheets().filter(sh => ~names.indexOf(sh.getName()));
let files = [];
shts.forEach((sh, i) => {
let d = Utilities.formatDate(new Date(sh.getRange("B4").getValue()), Session.getScriptTimeZone(), "dd-MM-yyyy");
let sheetgId = sh.getSheetId();
let url = "https://docs.google.com/spreadsheets/d/" + ssID + "/export?" + "format=xlsx" + "&gid=" + sheetgId + "&portrait=false" + "&exportFormat=xlsx";
let contents = UrlFetchApp.fetch(url, { headers: { 'Authorization': 'Bearer ' + token } }).getBlob().setName(`${sh.getName()}.xlsx`);
files.push(contents);
});
var subject = `Files: ${names.join(', ')}`;
var body = "Hello, here are your files";
MailApp.sendEmail(emails, subject, body, { attachments: files });
}
Related
Hi There I merged two of the ideologies/codes however my code keeps giving me a syntax error. I am sure that this almost correct but unable to identify the error
function myFunction() {
var message = "This is a test of HTML <br><br> Line two";
var recipientsTO = "shrikant.ravi#droom.in" + "," + "Bhavishya.saini#droom.in";
var recipientsCC = "Lipika.uniyal#droom.in";
var Subject = "Vacation Approval Request";
var html = message;
const ss = SpreadsheetApp.getActive();
const nameFile = ss.getName() + ".xlsx";
const requestData = {"method": "GET", "headers":{"Authorization":"Bearer
"+ScriptApp.getOAuthToken()}};
const url = "https://docs.google.com/spreadsheets/d/1Mytzfrl159TLMjMupziSKOrRJadsPKSLxYtaAvZTWt0/edit#gid=0"+
ss.getId() + "/export?format=xlsx";
const result = UrlFetchApp.fetch(url , requestData);
const contents = result.getContent();
MailApp.sendEmail({to: recipientsTO,
cc: recipientsCC,
subject: Subject,
htmlBody: html,};
{attachments:[{fileName:nameFile, content:contents, mimeType:"MICROSOFT_EXCEL"}]};
})
Try this:
function sendAttachment() {
var message = "This is a test of HTML <br><br> Line two";
var recipientsTO = "foo#bar.baz";
var recipientsCC = "baz#bat.cat";
var subject = "Vacation Approval Request";
var html = message;
const ss = SpreadsheetApp.getActiveSpreadsheet();
const nameFile = ss.getName() + ".xlsx";
const requestData = {
"method": "GET",
"headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}
};
const url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?format=xlsx";
const result = UrlFetchApp.fetch(url ,requestData);
const contents = result.getBlob();
MailApp.sendEmail(
recipientsTO,
subject,
html,
{
cc: recipientsCC,
name: nameFile,
attachments: [contents]
}
);
}
I have this script to export three separate sheets as PDF's using Google Apps Script which works fine except for the fact that the PDF's are exported with the file name of export.pdf in each case. I would like to rename them to 'Yesterday', 'Last 7 Days' and 'Last 30 Days' respectively, can anyone help me to achieve this, please?
//Menu in Google Sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Dashboard')
.addItem('Email Dashboard','emailDashboard')
.addToUi();
}
//Convert dashboard to PDF and email a copy to user
function emailDashboard() {
// get sheet id
var ss = SpreadsheetApp.getActiveSpreadsheet();
var id = ss.getId();
// setup sheets
var yesterdaySheet = ss.getSheetByName('Yesterday');
var last7DaysSheet = ss.getSheetByName('Last 7 Days');
var last30DaysSheet = ss.getSheetByName('Last 30 Days');
var settingsSheet = ss.getSheetByName('Settings');
var dashboardURL = ss.getUrl() + "?usp=sharing";
// Send the PDF of the spreadsheet to this email address
// get this from the settings sheet
var email = settingsSheet.getRange(8,2).getValue();
var cc_email = settingsSheet.getRange(9,2).getValue();
var bcc_email = settingsSheet.getRange(10,2).getValue();
// Subject of email message
var subject = "Dashboard PDF generated from " + ss.getName() + " - " + new Date().toLocaleString();
// Email Body
var body = `A pdf copy of your dashboard is attached.<br><br>
To access this Google Sheet,;
<a href="` + dashboardURL + `" >click here</a>`;
// Base URL
var url = "https://docs.google.com/spreadsheets/d/" + id + "/export?";
var url_ext = 'exportFormat=pdf&format=pdf&size=A4&portrait=false&fitw=true&gid=';
// Auth value
var token = ScriptApp.getOAuthToken();
var options = {
headers: { 'Authorization': 'Bearer ' + token }
}
// helps initialize first time using the script
var driveCall = DriveApp.getRootFolder();
// create the pdf
var responseYesterday = UrlFetchApp.fetch(url + url_ext + yesterdaySheet.getSheetId(), options);
var response7Days = UrlFetchApp.fetch(url + url_ext + last7DaysSheet.getSheetId(), options);
var response30Days = UrlFetchApp.fetch(url + url_ext + last30DaysSheet.getSheetId(), options);
// send the email with the PDF attachment
GmailApp.sendEmail(email, subject, body, {
cc: cc_email,
bcc: bcc_email,
htmlBody: body,
attachments:[responseYesterday,response7Days, response30Days]
});
}
Explanation:
Just add these three lines after the pdf creation part:
var blob_Y = responseYesterday.getBlob().setName('Yesterday' + '.pdf');
var blob_L7D = response7Days.getBlob().setName('Last 7 Days' + '.pdf');
var blob_L30D = response30Days.getBlob().setName('Last 30 Days' + '.pdf');
and then change this part:
GmailApp.sendEmail(email, subject, body, {
cc: cc_email,
bcc: bcc_email,
htmlBody: body,
attachments:[blob_Y, blob_L7D, blob_L30D ]
});
Solution:
//Menu in Google Sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Dashboard')
.addItem('Email Dashboard','emailDashboard')
.addToUi();
}
//Convert dashboard to PDF and email a copy to user
function emailDashboard() {
// get sheet id
var ss = SpreadsheetApp.getActiveSpreadsheet();
var id = ss.getId();
// setup sheets
var yesterdaySheet = ss.getSheetByName('Yesterday');
var last7DaysSheet = ss.getSheetByName('Last 7 Days');
var last30DaysSheet = ss.getSheetByName('Last 30 Days');
var settingsSheet = ss.getSheetByName('Settings');
var dashboardURL = ss.getUrl() + "?usp=sharing";
// Send the PDF of the spreadsheet to this email address
// get this from the settings sheet
var email = settingsSheet.getRange(8,2).getValue();
var cc_email = settingsSheet.getRange(9,2).getValue();
var bcc_email = settingsSheet.getRange(10,2).getValue();
// Subject of email message
var subject = "Dashboard PDF generated from " + ss.getName() + " - " + new Date().toLocaleString();
// Email Body
var body = `A pdf copy of your dashboard is attached.<br><br>
To access this Google Sheet,;
<a href="` + dashboardURL + `" >click here</a>`;
// Base URL
var url = "https://docs.google.com/spreadsheets/d/" + id + "/export?";
var url_ext = 'exportFormat=pdf&format=pdf&size=A4&portrait=false&fitw=true&gid=';
// Auth value
var token = ScriptApp.getOAuthToken();
var options = {
headers: { 'Authorization': 'Bearer ' + token }
}
// helps initialize first time using the script
var driveCall = DriveApp.getRootFolder();
// create the pdf
var responseYesterday = UrlFetchApp.fetch(url + url_ext + yesterdaySheet.getSheetId(), options);
var response7Days = UrlFetchApp.fetch(url + url_ext + last7DaysSheet.getSheetId(), options);
var response30Days = UrlFetchApp.fetch(url + url_ext + last30DaysSheet.getSheetId(), options);
var blob_Y = responseYesterday.getBlob().setName('Yesterday' + '.pdf');
var blob_L7D = response7Days.getBlob().setName('Last 7 Days' + '.pdf');
var blob_L30D = response30Days.getBlob().setName('Last 30 Days' + '.pdf');
GmailApp.sendEmail(email, subject, body, {
cc: cc_email,
bcc: bcc_email,
htmlBody: body,
attachments:[blob_Y, blob_L7D, blob_L30D ]
});
}
I have a spreadsheet with multiple sheets and I have another sheet with column A containing mail ids
and column B containing sheet names.
Whenever a sheet comes I will check with relevant mail ids to where the sheets have to be attached
For eg for sheetname 10001515ADC I have to attach the sheet to mail id guru3291#gmail.com and mail it.
Similarly for 10003810ADC the mail id is kumaraguru#aai.aero
The Code I worked on
function email(){
var heet= SpreadsheetApp.openById('1mbFTGxhvSbbttfkaezJpfU1TXNtJUPBvujREPi3yVwo');
var mid = heet.getSheetByName('Sheet1');
var getNames = mid.getDataRange().getValues();
getNames.shift();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheetsObj = {};
for (var i = 1; i < sheets.length; i++) {
sheetsObj[sheets[i].getSheetName()] = sheets[i];
}
Logger.log(sheetsObj);
for (var i = 0; i < getNames.length; i++) {
var r = getNames[i];
if (r[1] in sheetsObj) {
var ssID = ss.getId();
Logger.log(ssID);
var c =r[1];
var p =ss.getSheetByName(c);
p.activate;
Logger.log(p);
var sheetgId = ss.getActiveSheet().getSheetId();
Logger.log(sheetgId);
var sheetName = ss.getName();
Logger.log(sheetName);
}
var token = ScriptApp.getOAuthToken();
var email = r[0];
var subject = "Important Info!";
var body = "Latest Recency Report \n\nRegards,\n VOTV-ATM-OPS";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" +
"&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: { 'Authorization': 'Bearer ' + token}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".pdf", content:contents,
mimeType:"application//pdf"}]});
}
}
Your script is sending the wrong sheet because your activate request is not going through
This is due to the fact that you are referring to the method activate without calling it
To call a method, you need to reference it including the () brackets
So, modify p.activate; to p.activate();
See also Fucniton invoacation in Javascript.
SIDE NOTE
You do not need to activate a sheet to work with it.
The lines
var p =ss.getSheetByName(c);
p.activate();
var sheetgId = ss.getActiveSheet().getSheetId();
can be replaced by
var p =ss.getSheetByName(c);
var sheetgId = p.getSheetId();
my google sheet will email a PDF copy of the sheet to a list of 4 emails ( in cells L5:L8 )
but it seems that the email in cell L8 never picked , logger shows it in the array ! .
see my code and help figuring the problem !? I'm suspecting something wrong in my FOREACH loop .
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L11').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheet = ss.getActiveSheet();
var sheetName = ss.getName();
var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var token = ScriptApp.getOAuthToken();
var setcolor= SpreadsheetApp.getActiveSheet().setTabColor("#0000A0");
var emails= sheet.getRange("L5:L8").getValues();
var subject = "Daily report ";
var body = "Please find the attached" +" "+ key ;
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var tempSheet = ss.insertSheet("tempSheet"); // Added
sheet.getRange("A1:J27").copyTo(tempSheet.getRange(1, 1)); // Added
SpreadsheetApp.flush(); // Added
var sheetgId = tempSheet.getSheetId(); // Added
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {headers: {'Authorization': 'Bearer ' + token}});
var contents = result.getContent();
emails.forEach(function(email){
MailApp.sendEmail(email.toString(),sheetName ,body, {attachments: [{fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf"}]});
ss.deleteSheet(tempSheet); // Added
})
}
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for ( var i = 0 ; i<sheets.length ; i++) {
var sheet1 = sheets[i];
sheet1.getRangeList(['L3','L11']).clearContent();
}
}
this script sends a pdf copy to my email when I type Send in cell L6 , this code send the whole sheet and I need to send as only A1:J22 , any Ideas ?
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
+ "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" +
"&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {
attachments: [{
fileName: sheetName + ".pdf",
content: contents,
mimeType: "application//pdf"
}]
})
}
}
You want to retrieve the cells of A1:J22 and want to create them to PDF data.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In this modification, create a temporal sheet and copy the values of the cells of A1:J22 to it. Then, the temporal sheet is converted to PDF file. And, the temporal sheet is deleted.
Modified script:
When your script is modified, please modify as follows.
function onEdit2(e) {
var sheet = SpreadsheetApp.getActiveSheet();
var r = sheet.getRange('L6').getValue();
if (r == "Send") {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheet = ss.getActiveSheet(); // Added
// var sheetgId = ss.getActiveSheet().getSheetId(); // removed
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "EMAIL HERE";
var subject = "Daily report ";
var body = "Please find the attached Daily report";
var tempSheet = ss.insertSheet("tempSheet"); // Added
sheet.getRange("A1:J22").copyTo(tempSheet.getRange(1, 1)); // Added
SpreadsheetApp.flush(); // Added
var sheetgId = tempSheet.getSheetId(); // Added
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {headers: {'Authorization': 'Bearer ' + token}});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments: [{fileName: sheetName + ".pdf", content: contents, mimeType: "application//pdf"}]});
ss.deleteSheet(tempSheet); // Added
}
}
References:
insertSheet(sheetName)
copyTo(destination)
deleteSheet(sheet)
If I misunderstood your question and this was not the direction you want, I apologize.