Skip to content

Instantly share code, notes, and snippets.

@emnavarro02
Created June 6, 2021 19:04
Show Gist options
  • Save emnavarro02/ea5185c4717e3413741e57302c4c8d7f to your computer and use it in GitHub Desktop.
Save emnavarro02/ea5185c4717e3413741e57302c4c8d7f to your computer and use it in GitHub Desktop.
Send a GSuite Worksheet via Email as CSV file.
// https://stackoverflow.com/questions/43216543/mailing-google-sheet-as-csv
// https://gist.github.com/mrkrndvs/a2c8ff518b16e9188338cb809e06ccf1
function mailRequestCSV() {
// Send the CSV of the spreadsheet to this email address
var recipients = "[email protected]; [email protected]"
var bcc = "[email protected]"
var sender = "[email protected]"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('WORKSHEET NAME');
var fileName = sheet.getName() + ".csv"
var csvFile = convertRangeToCsvFile_(fileName, sheet)
var subject = "SUBJECT";
var body = "****NOTE: THIS IS AN AUTO COMPUTER-GENERATED REPORT****";
var url = "spreadsheet url";
MailApp.sendEmail(recipients, subject, body, {bcc:bcc, replyTo:sender, attachments:[{fileName:fileName, content:csvFile, mimeType:"application//csv"}]});
}
// Create a CSV File
function convertRangeToCsvFile_(csvFileName, sheet) {
// get available data range in the spreadsheet
var activeRange = sheet.getDataRange();
try {
var data = activeRange.getValues();
var csvFile = undefined;
// loop through the data in the range and build a string with the csv data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// join each row's columns
// add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment