Skip to content

Instantly share code, notes, and snippets.

@queerviolet
Created April 5, 2017 02:22
Show Gist options
  • Save queerviolet/4c6c47451baf938a35fa605b0f576814 to your computer and use it in GitHub Desktop.
Save queerviolet/4c6c47451baf938a35fa605b0f576814 to your computer and use it in GitHub Desktop.
Send sheet as email
// Load a menu item called "Project Admin" with a submenu item called "Send Status"
// Running this, sends the currently open sheet, as a PDF attachment
function onOpen() {
SpreadsheetApp.getActiveSpreadsheet().addMenu('Send sheet', [
{name: 'As email', functionName: 'send'}
]);
}
function getSheetAs(sheet, format) {
format = format || 'xlsx'
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" +
sheet.getId() + '&exportFormat=' + format
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true,
};
return UrlFetchApp.fetch(url, params).getBlob().setName(sheet.getName() + '.' + format)
}
function send() {
// Set the Active Spreadsheet so we don't forget
const spread = SpreadsheetApp.getActive()
, sheet = spread.getActiveSheet()
, to = sheet.getRange('B1').getValue()
, subject = sheet.getRange('B2').getValue()
, colMax = sheet.getMaxColumns(), rowMax = sheet.getMaxRows()
, values = sheet.getRange(1, 1, rowMax, colMax).getValues()
, message = values
.map(function(row) {
return row.join(' ')
}).join('\n')
, html = '<table>' + values.map(function(row) {
const cols = row.map(function(col) {
return col && ('<td>' + col + '</td>')
}).join('')
return cols && ('<tr>' + cols + '</tr>')
}).join('') + '</table>'
MailApp.sendEmail(to, subject, message + '<b>hi!</b>', {
attachments: [
spread.getAs('application/pdf').setName(sheet.getName() + '.pdf'),
getSheetAs(spread, 'xlsx'),
],
htmlBody: html,
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment