Output google sheet via email - google-apps-script

I'm trying to output my custom google sheet to a set email address
I have tried adding into a blob before sending but every time the email is sent the excel sheet that is attached is blank. Any help would be appreciated
var file = DriveApp.getFilesByName(nSheet.getName());
var url = 'https://docs.google.com/spreadsheets/d/'+nSheet.getId()+'/export?format=xlsx';
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var fileName = (nSheet.getName()) + '.xlsx';
var blobs = [response.getBlob().setName(fileName)];
var emailAddress = "testg#gmail.com"
var subject = "PCS v5 Validated Sheet"
var emailbody = "The XLSX file is attached"
GmailApp.sendEmail(emailAddress, subject, emailbody, {attachments: blobs});

You script works fine. I tried it for simple sheet and I'm getting nice xlsx on my email.
https://docs.google.com/spreadsheets/d/1p8NzX0J1XhHFq6C1iSNWbs7h3OXzHKC7cDiQGYmuD_0/edit#gid=0
So, if your is blank it might be related to what data you have in sheet.
Are you using some =QUERY of =IMPORTXML function to get data which isn't diplayed?

Related

Sending Google Doc email template as html format on Email

I've google docs template with logo and some images plus some text instructions, and I want to send it over email exactly how it appear in Google Docs, I know how to send plain text from google docs but can't figure out how to send templates with images.
Here is the code I am using currently :-
var body = doc.getBody().getText();
var message = body;
var subject = "subject line";
MailApp.sendEmail (user.primaryEmail, subject, message)
Updated script as suggested by Tanaike :-
function getDocAsHtml(docId){
var doc = DocumentApp.getActiveDocument()
var url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=html&id=" + doc.getId();
var html = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getContentText();
var body = doc.getBody().getText();
var message = body;
var subject = "subject line";
MailApp.sendEmail('abc#xyz.com', subject, message, { htmlBody: html });
}
I believe your goal is as follows.
You want to send an email as the HTML body of the Google Document.
In this case, how about the following modification? From your showing script, I suppose that doc is the object of Document.
Modified script:
var url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=html&id=" + doc.getId();
var html = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getContentText();
var body = doc.getBody().getText();
var message = body;
var subject = "subject line";
MailApp.sendEmail(user.primaryEmail, subject, message, { htmlBody: html });
// DriveApp.getFiles(); // This is used for automatically detecting the scope of Drive API.
When this script is run, the Google Document of doc is sent as the HTML body.
Note:
In this case, the mail client cannot show the HTML body, the text body of message is shown.
References:
fetch(url, params)
sendEmail(recipient, subject, body, options)

Export Google Sheet as .xlsx and send file to server

My company manages non-confidential information in a Google Sheet. Every day, I export that sheet to .xlsx format and then upload it to various services for data syndication.
Normally, such a process could be automated using the "Publish to Web" feature. But for security reasons, that option is locked for all users.
I do have full permissions for Google Apps Script, though. So, I'd like to write a script for this. The particulars don't matter. Somehow, I need to export the sheet on a schedule and send it to an AWS server, where it can be automatically retrieved.
At the AWS side, I can easily set up an email server, FTP server, rclone, whatever. I just need to figure out what to do on the Google side first.
Can this be done?
What I have tried so far:
Export a Google Sheet to Google Drive in Excel format with Apps Script
function makeCopy() {
var formattedDate = Utilities.formatDate(new Date(), "CET", "yyyy-MM-dd' 'HH:mm");
var name = "Backup Copy " + formattedDate;
var destination = DriveApp.getFolderById("1vFL98cgKdMHLNLSc542pUt4FMRTthUvL");
// Added
var sheetId = "2SqIXLiic6-gjI2KwQ6OIgb-erbl3xqzohRgE06bfj2c";
var url = "https://docs.google.com/spreadsheets/d/" + sheetId + "/export?format=xlsx&access_token=" + ScriptApp.getOAuthToken();
var blob = UrlFetchApp.fetch(url).getBlob().setName(name + ".xlsx"); // Modified
destination.createFile(blob);
}
--- OR ---
function convertSheetToXLSX() {
var sheetId = "2SqIXLiic6-gjI2KwQ6OIgb-erbl3xqzohRgE06bfj2c";
var spreadsheetName = "My Spreadsheet";
var destination = DriveApp.getFolderById("1vFL98cgKdMHLNLSc542pUt4FMRTthUvL");
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + sheetId + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(spreadsheetName + ".xlsx");
destination.createFile(blob);
}
I have tried these scripts from the URL posted above but it results in "An unknown error has occurred, please try again later."
Take a look at this thread. It is about sending a spreadsheet in PDF format, but if you just change the ExportOptions to xlsx, you should be able to make it.

Get file from Google Drive based of Google Form info submission

I have created a Google Form containing two fields (First Name, Last Name)
I have PDF files in Google Drive/specific folder, PDF files named as "First Name"+"Last Name"
I want to get PDF file from my Google Drive based on form submission and get the URL to be sent by email.
I need the way to get PDF file based on form user submission.
I have written the below code which shall send the PDF as email attachment in place of the URL of PDF. I hope this code can help you. This code is a very basic code which can be further advanced as per your needs. Please let me know if you need any further help.
function pdfextractor() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Get active spreadsheet.
var lastrow = ss.getLastRow();
var sheetName = ss.getRange("B" + lastrow).getValue() + " " + ss.getRange("C" + lastrow).getValue(); //considering format 'FirstName LastName' stored in column B & C of spreasheet generated by submission of google forms.
var pdfName = sheetName + ".pdf";
ss.getRange("D" + lastrow).setValue(pdfName);
var files = DriveApp.getFilesByName(pdfName);
var body = "This is a test email";
var subject = "PDF File "
var email = "admin#gmail.com"
while (files.hasNext()) {
var file = files.next();
}
GmailApp.sendEmail(email, subject, body, {
attachments: [file]
});
}
You can also change the email of each mail you want to send if stored with the sheet.
One way to do it is to create trigger that fires when the form is submitted. Based on this event, you can get the responses from the form submission, use them to search the file in Drive and send it attached to an email.
Here's an example that you can adapt to build what you need:
function onSubmit(e) {
// Get submitted responses
let itemResponses = e.response.getItemResponses();
// Get form answers (assume the form has three question in this order: First Name, Last Name, Email)
let firstName = itemResponses[0].getResponse();
let lastName = itemResponses[1].getResponse();
let email = itemResponses[2].getResponse();
// Get file (first file found with specified name)
let searchResult = DriveApp.searchFiles(`title contains \'${firstName+lastName}\'`);
let respondentFile = searchResult.next();
if (!respondentFile) throw 'File not found';
// Send email with respondent's file
MailApp.sendEmail(email, 'Your PDF File', 'Your PDF file is attached.', {
name: 'Automatic Emailer Script',
attachments: [respondentFile.getAs(MimeType.PDF)]
});
}

G.A.S. code to email a google sheet as a pdf file to a person through Telegram

I use the following Google Script Code to generate a pdf of a google sheet and send it through email. Is there a way I can send the pdf through teleram to a person? How should I change the following code to send the pdf through telegram?
function emailReport() {
readyForExport();
var spreadsheet = SpreadsheetApp.getActive();
var subject = spreadsheet.getRange("U1:U1").getValues();
var emailTo = spreadsheet.getRange("V1:V1").getValues();
var message = spreadsheet.getRange("W1:W1").getValues();
var fileName = spreadsheet.getRange("X1:X1").getValues();
spreadsheet.setActiveSheet(spreadsheet.getSheetByName("Students"));
var pdf = DriveApp.getFileById(spreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:fileName[0][0],content:pdf, mimeType:'application/pdf'};
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
};

Google apps script to email google spreadsheet excel version [duplicate]

This question already has answers here:
Google app scripts: email a spreadsheet as excel
(2 answers)
Closed 2 years ago.
I would like to write an apps script to email an excel version of my Google Spreadsheet. I know I can save the spreadsheet as an Excel file. I am not sure if I can use the script to email the excel version out as an attachment. How can this be done?
After an answer on another recent post (Thomas van Latum), I tried the suggested doc api and get an interesting result... here is the test code I used and that is working nicely except the file is in xlsx format, not in xls but this is not necessarily an issue these days :
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey('anonymous');
oAuthConfig.setConsumerSecret('anonymous');
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
function test(){
var id = 'spreadsheet_ID'
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/spreadsheets/Export?key='+id+'&exportFormat=xls',
googleOAuth_('docs',url)).getBlob()
DocsList.createFile(doc).rename('newfile.xls')
}
note : if you don't rename it, its default name is Export.xlsx , it might be more usefull to get its ID to use it later...
so the last line could be like this instead :
var xlsfileID = DocsList.createFile(doc).getId()
EDIT : to trigger the authorization process, try a small function like this, run it from the script editor
function autorise(){
// function to call to authorize googleOauth
var id=SpreadsheetApp.getActiveSpreadsheet().getId();
var url = 'https://docs.google.com/feeds/';
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id,
googleOAuth_('docs',url)).getContentText();
}
As I spent about four hours of playing Rumpelstiltskin because none of the typically very old code snippets for the old Spreadsheet versions and the old OAUTH you can find when googling "google docs script send excel attachment" or similar (i.e. you want to take an existing Spreadsheet, convert it to Excel format and send it as email attachment) actually worked, I finally found the solution.
To create the actual attachment content, neither the supposed res.getContent() nor res.getBlob() nor res.getBytes alone worked. These hints are misleading!
The only thing that works for me is response.getBlob().getContent()!
Whole code :
function sendCurrentDocAsEmail() {
var driveService = getDriveService();
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getName();
var email = "recipient#demo.com"
var subject = "Here be Subjects";
var body = "Don't even think about learning how to code. It's wasted time.";
var file = Drive.Files.get(ssID );
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + driveService.getAccessToken()
}
});
var attachments = [{
fileName:sheetName+".xlsx",
content: response.getBlob().getBytes(), // this single line has cost me hours!
mimeType:"application//xls",
headers: {
Authorization: 'Bearer ' + driveService.getAccessToken()
}
}];
MailApp.sendEmail(email,subject ,body, {attachments:attachments});
}
Where getDriveService() is a function from Google's "OAuth2 for Apps Script" readme on https://github.com/googlesamples/apps-script-oauth2
The latest working version is below. Based on this example, i.e. similar as in previous answer but uses Google Service Account which does not require a human going by link to receive a token. You have to install Oath library from Google, the instructions are pretty clear.
var PRIVATE_KEY = 'xxx'
var CLIENT_EMAIL = 'xxx';
var USER_EMAIL=Session.getActiveUser().getEmail()
function getOathService() {
return OAuth2.createService('GoogleDrive:' + USER_EMAIL)
// Set the endpoint URL.
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the private key and issuer.
.setPrivateKey(PRIVATE_KEY)
.setIssuer(CLIENT_EMAIL)
// Set the name of the user to impersonate. This will only work for
// Google Apps for Work/EDU accounts whose admin has setup domain-wide
// delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
.setSubject(USER_EMAIL)
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope. This must match one of the scopes configured during the
// setup of domain-wide delegation.
.setScope('https://www.googleapis.com/auth/drive');
}
function sendEmail() {
var oathService = getOathService();
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var file = Drive.Files.get(ssID );
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var file = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + oathService.getAccessToken()
}
});
var attachments = [{
fileName:'xxx.xls',//TODO DATE
content: file.getBlob().getBytes(),
mimeType:"application//xls",
headers: {
Authorization: 'Bearer ' + oathService.getAccessToken()
}
}];
MailApp.sendEmail('email#domain.com', 'xxx', 'Hi,\n\nPlease see the last data in attachment',{attachments:attachments});
}
The one that worked for me:
var AUTH_TOKEN = "Enter your OAuth_Token";
ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var url = "http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="+ ssID + "&exportFormat=xls";
//Add &gid=x at the end of above url if you only want a particular sheet
var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";
var res = UrlFetchApp.fetch(url, {headers: {Authorization: auth}});
var attachments = [{fileName:"<Filename>.xls", content: res.getContent(),mimeType:"application/vnd.ms-excel"}];
MailApp.sendEmail("<recipient's email id>", "<email subject>", "<email body>", {attachments: attachments});
Get OAuth documentation & you token from here https://developers.google.com/accounts/docs/OAuth2
Use the following snippet of code after modifying it to suit your needs
var file = DocsList.getFileById(FILE_ID);
var attachment = file.getAs('application/vnd.ms-excel');
MailApp.sendEmail("abcd#example.com", "Subject", " Body" , {"fileName": "Your_file_name" , "mimeType" : "application/vnd.ms-excel" , "content":attachment.getBytes() } );
Note that this code is not tested, so please feel free to fix an error or two that might pop up