Script to automatically send a Sheet by email - google-apps-script

I am trying to automate by a script the sending of a Sheet (active or not) of a workbook and only one sheet and not the whole workbook to a list of email addresses. Furthermore, I would like the Sheet to be converted to excel format when it is attached to the email.
Thank you for your answers

Try this:
function emailSpreadsheetAsPDF() {
const sheetToPrint = 'SPREADSHEET_NAME'; // name of the sheet to print
const ss = SpreadsheetApp.getSheetByName('SHEET_NAME'); // the sheets to use
const email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEET_NAME').getRange('RANGE').getValue().toString(); // grab the email address from the specified cell
const subject = `SUBJECT - ${ss.getName()}`; // the subject of the email
const body = "BODY"; // body of the email
const shID = ss.getSheetByName(sheetToPrint).getSheetId(); // the ID of the sheet
const url = 'https://docs.google.com/spreadsheets/d/SS_ID/export?'.replace('SS_ID', ss.getId()); // url of the spreadsheet
const exportOptions =
'exportFormat=pdf&format=xlsx' + // export as pdf / csv / xls / xlsx
'&gid='+shID; // the sheet's Id
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
// generate the file
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
// send the email to the specified address with the specified body text and attached file
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments: [{
fileName: `EKOL Hungary - ${ss.getName()}` + ".xlsx",
content: response.getBytes(),
mimeType: "application/xlsx"
}]
});
}
Just substitute the SPREADSHEET_NAME, SHEET_NAME, RANGE, and BODY to what is true for your spreadsheet.
You can add a Trigger under the Triggers menu point (left side of the Script Editor) to automatically run the script whenever you want it to run.

Thanks but I failed to use it
But by combining several scripts, I found one that works:
function onSubmit(e){
Logger.log('submit ran');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Send active sheet as email attachment
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "xxx#xx";
var subject = "xxxxx";
var body = "xxxxx";
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();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".xlsx", content:contents, mimeType:"application//xlsx"}]});
};
Now what I would like is to be able to send the sheet to email addresses located on another sheet.
Also in "subject", I would like to combine "xxxx" + a date in a cell of the active sheet: "xxxx dd / mm / yyyy"
I haven't figured out how to do it yet !!!

Related

Convert Google Sheet to CSV then attach it to an email

I have a simple Apps Script need, but can't find a near enough sample from the community.
I need to convert 2 sheets from a Google Spreadsheet, individually, as CSV files then attach them in an email.
So far, I found a script to convert a sheet into a CSV format and file it in a folder.
I looked for a script to add that will instead attach the CSV file to an email, but can't find anything which I can use based on my novice level of Apps Script knowledge.
Any help will be greatly appreciated. Thank you very much.
Script:
function sheet1ToCsv()
{
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "xxxx"
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name)
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv"
var url = "https://docs.google.com/spreadsheets/d/"+ params
var result = UrlFetchApp.fetch(url, requestData);
var folderId = "yyyy";
var csvContent = {
title: sheet_Name+".csv",
mimeType: "application/vnd.csv",
parents: [{id: folderId}]
}
var fileJson = Drive.Files.insert(csvContent,result)
}
In your showing script, an email is not sent. And, only one CSV file is created to Google Drive. From I need to convert 2 sheets from a Google Spreadsheet, individually, as CSV files then attach them in an email. and your showing script, when your showing script is modified, how about the following modification?
Modified script:
function myFunction() {
var emailAddress = "###"; // Please set your email address.
var sheetNames = ["Sheet1", "Sheet2"]; // Please set your 2 sheet names you want to use.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssID = ss.getId();
var requestData = { "method": "GET", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
var blobs = sheetNames.map(s => {
var params = ssID + "/export?gid=" + ss.getSheetByName(s).getSheetId() + "&format=csv";
var url = "https://docs.google.com/spreadsheets/d/" + params;
return UrlFetchApp.fetch(url, requestData).getBlob().setName(s); // <--- Modified
});
MailApp.sendEmail({ to: emailAddress, subject: "sample subject", body: "sample body", attachments: blobs });
}
When this script is run, an email is sent by including 2 CSV files as the attachment files.
References:
map()
sendEmail(message)
function myfunk() {
const folder = DriveApp.getFolderById("folderid");
const ss = SpreadsheetApp.getActive();
const names = ["Sheet1", "Sheet2"];
const params = { "method": "GET", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
let bA = [];
names.forEach(n => {
let sh = ss.getSheetByName(n);
let url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?gid=" + sh.getSheetId() + "&format=csv";
let r = UrlFetchApp.fetch(url, params);
let csv = r.getContentText();
let file = folder.createFile(n, csv, MimeType.CSV);
bA.push(file.getBlob());
})
GmailApp.sendEmail(recipient, subject, body, { attachments: bA })
}

Saving the content being emailed as an attachment in google drive

I have written a script that attaches the content of the sheet as an attachment and emails it.
This is for invoicing. Once an invoice is generated, the invoice is sent as a PDF to the vendor. Now, i want these sent invoices documented in google drive every time they are sent
Now, i want this attachment PDF to be saved to a google drive folder every time the email is triggered
This is an invoicing sheet.
function emailSpreadsheetAsPDF() {
const sheetToPrint = "Invoice"; // name of the sheet to print
const ss = SpreadsheetApp.getActiveSpreadsheet(); // the sheets to use
const subject = `Invoice`; // the subject of the email
const shID = ss.getSheetByName(sheetToPrint).getSheetId(); // the ID of the sheet
const url = 'https://docs.google.com/spreadsheets/d/SS_ID/export?'.replace('SS_ID', ss.getId()); // url of the spreadsheet
const exportOptions =
'exportFormat=pdf&format=pdf' + // export as pdf / csv / xls / xlsx
'&size=A4'+ // size of the PDF (legal / A4 / letter)
'&portrait=true'+ // orientation of the PDF (false for landscape)
'&fitw=true'+ // fit to page width (false for actual size)
'&sheetnames=false&printtitle=false'+ // hide optional headers and footers
'&pagenumbers=false&gridlines=false'+ // hide page numbers and gridlines
'&fzr=false'+ // do not repeat row headers (frozen rows) on each page
'&gid='+shID; // the sheet's Id
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
// generate the PDF file
var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
var ui = SpreadsheetApp.getUi();
var resp = ui.alert('Are you sure?',ui.ButtonSet.YES_NO);
if(resp == ui.Button.YES)
{
var ssheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Invoice");
var tsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Invoice Archives");
var tindex = tsheet.getLastRow();
var count = tsheet.getRange(tindex,1).getValue();
tindex = Number(tindex) + 1;
var count = tsheet.getRange(tindex,1).setValue(Number(count)+1);
ssheet.getRange(22,8).copyTo(tsheet.getRange(tindex,7), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false); //Invoice Amout
ssheet.getRange(7,8).copyTo(tsheet.getRange(tindex,15), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
ssheet.getRange(21,8).copyTo(tsheet.getRange(tindex,16), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
ssheet.getRange(10,8).copyTo(tsheet.getRange(tindex,17), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false); // admin name
ssheet.getRange(11,8).copyTo(tsheet.getRange(tindex,18), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false); // admin email
ssheet.getRange(12,8).copyTo(tsheet.getRange(tindex,19), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false); // sales lead email
var invid = tsheet.getRange(tindex,2).getValue();
var invamount = tsheet.getRange(tindex,7).getValue();
var adminname = tsheet.getRange(tindex,17).getValue();
var aemail = tsheet.getRange(tindex,18).getValue();
var semail = tsheet.getRange(tindex,19).getValue();
var email = aemail + ',' + semail ;
Logger.log(email);
var body = '<p>Hello '+adminname+',</p> <p>Greetings from Begig! Hope you are doing well.</p> <p>Please find an invoice attached to this email of value ₹'+invamount+'. Request you to process the payment against it at the earliest</p> <p> </p> <p>--</p> <p>Regards</p> <p>Ops Team - Begig</p>'
// send the email to the specified address with the specified body text and attached PDF file
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments: [{
fileName: "Invoice - "+ invid+".pdf",
content: response.getBytes(),
mimeType: "application/pdf"
}]
});
raiseinvoice();
}
}
To save the pdf, you will have to add
const folder = DriveApp.getFolderById('_______if of folder______');
folder.createFile(response.setName('______name_of_file_____'));

how Send specific part of the sheet as email?

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.

how to make this template code work from sheets app

I'm trying to make this script to work on google sheets app so it sends a pdf copy to my email when I type Send in cell L6
the code work perfect on computer but not on ipads , anyway to do this from app ?
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"
}]
})
}
}
The way it worked for me by " installed Trigger "
from the script editor : Edit - current project Triggers
I added new trigger that will run the code below based on " On edit " and voila it worked , from sheets app if I typed " Send " in Cell L6 it will send a PDF copy of the active sheet to the email listed in the code.
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"
}]
})
}
}
Create a Google Script in the very same Spreadsheet or in another one (Tools / Script editor), add the script you already have, grant the authorizations required, and trigger it with a simple form (Tools / Create a form) (trigger → Edit / Current project's triggers). The long URL to view the form can be easily opened by means of a URL shortener or something by the sort. Forms work in cell phones too and without need to sign in to your account. With this method you can even add a useless conditional password to run the script.
function createPDF(e) {
var input = e.values[1];
if (input == 'my_password'){
// your scripts to create and send the PDF goes here
}
}
It's a simplistic solution, but it works.

How to send my target Sheet as a pdf to an email address

I have a Form that when submitted will trigger a function to write the values of that submittal to the proper sheet in a Spreadsheet.
I then wish to email that adjusted sheet to someone.
I searched google api for help and could not resolve or reverse engineer the proper code
function sendpdf(){ // Function trigger is on form submit
var ss = SpreadsheetApp.getActiveSheet();
var sourceSheet = ss.getSheetName();
var workingRow = ss.getLastRow();
var dataRange = ss.getRange(workingRow, 1, 1, 4);
var data = dataRange.getValues();
var row = data[0]; // entire row
var col1 = row[0]; // first column timestamp A
var col2 = row[1]; // Client B
var col3 = row[2]; // Item C
var sass = SpreadsheetApp.getActiveSpreadsheet();
var targetSheet = sass.getSheetByName(col2);
targetSheet.insertRowBefore(4);
targetSheet.getRange("A4").setValue(col1);
targetSheet.getRange("B4").setValue(col2);
targetSheet.getRange("C4").setValue(col3);
MailApp.sendEmail(to:"reciever#email.com",subject:"See Attached PDF regarding" + col2,body:col2+" submitted a new request"
// , attach:targetSheet.pdf
// need the code to turn the targetSheet into a PDF and then email the PDF
)
}
The Spreadsheet contains 12 sheets and I expect the script to email the proper sheet that was just adjusted to someone any help would be appreciated
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var folderID = "FOLDERID"; // Folder id to save pdf in a folder.
var folder = DriveApp.getFolderById(folderID);
var newSpreadsheet = SpreadsheetApp.create(pdfName); // Name new Spreadsheet
var sheet = sourcesheet.copyTo(newSpreadsheet); //copy activesheet to new spreadsheet
newSpreadsheet.getSheetByName('Sheet1').activate(); //select "sheet1"
newSpreadsheet.deleteActiveSheet(); //delete "sheet1"
var newFile = folder.createFile(newSpreadsheet);
var pdf = DriveApp.getFileById(newSpreadsheet.getId());
var theBlob = pdf.getBlob().getAs('application/pdf').setName(pdfName); //create pdf
from new sheet in folder
var url, //create variable from url of the new sheet
sheets = newSpreadsheet.getSheets()
url = Drive.Files.get(newSpreadsheet.getId())
.exportLinks['application/pdf']; //create the pdf
url = url + '&size=a4' + //paper size
'&portrait=true' + //orientation, false for landscape
'&fitw=true' + //fit to width, false for actual size
'&sheetnames=false&printtitle=false&pagenumbers=false' + //hide optional
'&gridlines=false' + //false = hide gridlines, true = show
'&fzr=false'; //do not repeat row headers (frozen rows) on each page, true = show
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
DriveApp.getFilesByName(pdfName).next().setTrashed(true); //delete newSpreadsheet
var attachmentName = pdfName + '.pdf';
var optAdvancedArgs = {name: "NAMEFROM", htmlBody: htmlBody, replyTo : from,
from:from, attachments: [response.getBlob().setName(attachmentName)], }; //attach pdf
GmailApp.sendEmail(mailTo, subject, body, optAdvancedArgs); //send email with
advanced arguments
This should get you going ...
Good luck !