Send active sheet as PDF to email listed in cell

16,321

Solution 1

below is a working version with a few useful parameters you may want to use.

UPDATED CODE

function sendSheetToPdfwithA1MailAdress(){ // this is the function to call
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheets()[0]; // it will send sheet 0 wich is the first sheet in the spreadsheet.
  // if you change the number, change it also in the parameters below
  var shName = sh.getName()
  sendSpreadsheetToPdf(0, shName, sh.getRange('A1').getValue(),"test email with the adress in cell A1 ", "This is it !");
}
function sendSpreadsheetToPdf(sheetNumber, pdfName, email,subject, htmlbody) {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var spreadsheetId = spreadsheet.getId()  
  var sheetId = sheetNumber ? spreadsheet.getSheets()[sheetNumber].getSheetId() : null;  
  var url_base = spreadsheet.getUrl().replace(/edit$/,'');

  var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf

      + (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId)) 
      // following parameters are optional...
      + '&size=A4'      // paper size
      + '&portrait=true'    // orientation, false for landscape
      + '&fitw=true'        // fit to width, false for actual size
      + '&sheetnames=true&printtitle=false&pagenumbers=true'  //hide optional headers and footers
      + '&gridlines=false'  // hide gridlines
      + '&fzr=false';       // do not repeat row headers (frozen rows) on each page

  var options = {
    headers: {
      'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken(),
    }
  }

  var response = UrlFetchApp.fetch(url_base + url_ext, options);
  var blob = response.getBlob().setName(pdfName + '.pdf');
  if (email) {
    var mailOptions = {
      attachments:blob, htmlBody:htmlbody
    }
MailApp.sendEmail(
      email, 
      subject+" (" + pdfName +")", 
      "html content only", 
      mailOptions);

MailApp.sendEmail(
      Session.getActiveUser().getEmail(), 
      "FRWD "+subject+" (" + pdfName +")", 
      "html content only", 
      mailOptions);
  }
}

Solution 2

Excellent answer already accepted. I had a question about emailing just to a range and took the opportunity to add a few improvements from Serge's excellent answer above.

Mail range not whole sheet - apps script

/*
shNum = 0 for whole workbook or '0', or 0,1,2,etc for specific tab/sheet
shRng = A1 address for desired range, eg 'E1:L25', ignored if not a single sheet shNum
pdfName = text on top of pdf
*/
function mailPdf(shNum,shRng,pdfName,email,subject,htmlbody) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ssId = ss.getId();
  var shId = shNum ? ss.getSheets()[shNum].getSheetId() : null;  
  var url_base = ss.getUrl().replace(/edit$/,'');
  var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf
      + (shId ? ('&gid=' + shId) : ('&id=' + ssId))
      + (shRng ? ('&range=E1:L25') : null)
      + '&format=pdf'                   //export format
      + '&size=letter'                      //A3/A4/A5/B4/B5/letter/tabloid/legal/statement/executive/folio
      //+ '&portrait=false'               //true= Potrait / false= Landscape
      //+ '&scale=1'                      //1= Normal 100% / 2= Fit to width / 3= Fit to height / 4= Fit to Page
      //+ '&top_margin=0.00'              //All four margins must be set!
      //+ '&bottom_margin=0.00'           //All four margins must be set!
      //+ '&left_margin=0.00'             //All four margins must be set!
      //+ '&right_margin=0.00'            //All four margins must be set!
      + '&gridlines=false'              //true/false
      //+ '&printnotes=false'             //true/false
      //+ '&pageorder=2'                  //1= Down, then over / 2= Over, then down
      //+ '&horizontal_alignment=CENTER'  //LEFT/CENTER/RIGHT
      + '&vertical_alignment=TOP'       //TOP/MIDDLE/BOTTOM
      //+ '&printtitle=false'             //true/false
      //+ '&sheetnames=false'             //true/false
      //+ '&fzr=false'                    //true/false frozen rows
      //+ '&fzc=false'                    //true/false frozen cols
      //+ '&attachment=false'             //true/false

  var options = {
    headers: {
      'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken(),
      'muteHttpExceptions': true
    }
  }

  var response = UrlFetchApp.fetch(url_base + url_ext, options);
  var blob = response.getBlob().setName(pdfName + '.pdf');
  if (email) {
    var mailOptions = {
      attachments:blob, htmlBody:htmlbody
    }


MailApp.sendEmail(
      // email + "," + Session.getActiveUser().getEmail() // use this to email self and others
      email,                                              // use this to only email users requested
      subject+' (' + pdfName +')', 
      'html content only', 
      mailOptions);

  }
}

Solution 3

Here I found an extremely simple way to send the spreadsheet by email as pdf

https://spreadsheet.dev/automatically-email-google-sheet-as-pdf-attachment

Problem: it is sending the whole document and I only want to send a particular sheet, the active one.

So I modified the original code from this

//===============

function sendReport() {
  var message = {
    to: "[email protected]",
    subject: "Monthly sales report",
    body: "Hi team,\n\nPlease find the monthly report attached.\n\nThank you,\nBob",
    name: "Bob",
    attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("Monthly sales report")]
  }
  MailApp.sendEmail(message);
}

//===============

To this

Note: I took some code from Google spreadsheet script export active sheet only to PDF

//===============



// Define your variables here

var recipient="[email protected]";
var subject=SpreadsheetApp.getActiveSpreadsheet().getName();
var body="Hello,\n\nPlease find attached the document.\n\nThank you,\nYOURNAME";
var nameOfSender="YOURNAME";

// End of the stuff you need to edit


// Below, the sheet is converted to pdf in a blob object and that object
// is sent by email with the email-parameters above.



// Other stuff 
var ss = SpreadsheetApp.getActiveSpreadsheet();
//var ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
//var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
//var sheetId = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();

// Base URL
var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());

/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
 */

var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
     + '&size=A4' // paper size legal / letter / A4
     + '&portrait=true' // orientation, false for landscape
     + '&fitw=true&source=labnol' // 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='; // the sheet's Id

var token = ScriptApp.getOAuthToken();

var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {                                 
        headers : {
            'Authorization' : 'Bearer ' + token
        }
    }).getBlob().setName(sheet.getName() + ".pdf");

sheet_as_pdf_blob_document=response;


// Here we send the email

function sendReport() {
 
   var message = {
    to: recipient,
    subject: subject,
    body: body,
    name: nameOfSender,
    attachments: [sheet_as_pdf_blob_document]
  }

   MailApp.sendEmail(message);
}


//===============
Share:
16,321
AlbaTroes
Author by

AlbaTroes

Updated on July 13, 2022

Comments

  • AlbaTroes
    AlbaTroes almost 2 years

    I'm trying to use the script below to send the first sheets in a Google Sheets document to an email as PDF. The email to send to, is listed in cell A1.

    However, this script send the entire spreadsheet as an PDF and not just the first sheet. I have been trying to use some of the other scripts from Stack Overflow, but this is the only one that actually sends an email.

            /* Email Google Spreadsheet as PDF */
    function emailGoogleSpreadsheetAsPDF() {
      
      // Send the PDF of the spreadsheet to this email address
      var email = "[email protected]"; 
      
      // Get the currently active spreadsheet URL (link)
      var ss = SpreadsheetApp.getActiveSpreadsheet();
    
      // Subject of email message
      var subject = "PDF generated from spreadsheet " + ss.getName(); 
    
      // Email Body can  be HTML too 
      var body = "Install the <a href='http://www.labnol.org/email-sheet'>Email Spreadsheet add-on</a> for one-click conversion.";
      
      var blob = DriveApp.getFileById(ss.getId()).getAs("application/pdf");
      
      blob.setName(ss.getName() + ".pdf");
      
      // If allowed to send emails, send the email with the PDF attachment
      if (MailApp.getRemainingDailyQuota() > 0) 
        GmailApp.sendEmail(email, subject, body, {
          htmlBody: body,
          attachments:[blob]     
        });  
    }
    
  • Metexora
    Metexora over 3 years
    I kept getting "Exception: Request failed, returned code 400." with this script