Here is my problem: I have succesfully written a script to send a PDF attachment of a google worksheet. However, to print the file I have to open the attachment in the mail from the mailbox. I wonder whether it is possible to show the PDF directly after sending the email, so I can print is with File>Print command. Below is the part of the script that creates and sends the attachments:
var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";
var res = UrlFetchApp.fetch(url, {headers: {Authorization: auth}});
var attachments = [{fileName:"GASgenerated.pdf", content: res.getContent(), mimeType:"application/pdf"}];
MailApp.sendEmail(email, subject, body, {attachments:attachments});
So my question is: How can I open file "GASgenerated.pdf" in this script immediately after the MailApp.sendEmail command, so I can directly print the file?
GAS will let you add browser side javascript: https://developers.google.com/apps-script/html_service (This lets you create a google apps script webapp)
Example URL to download as PDF, you will need to change the spreadsheet key.
https://docs.google.com/feeds/download/spreadsheets/Export?key=0AkGlO9jJLGO8dDB6Z19oSE5JZVZNdHFUa0RXM1dzaWc&exportFormat=pdf&gid=3&gridlines=0&printtitle=0&size=7&portrait=true&fitw=true
Related
I need a script that allows me to send each document contained in a folder to a specific email address. Inside every doc there is the email address to which that document needs to be sent.
The email address is incapsulated between two tags.
Example: <<example#example.com>>
I would like the script to search for the text contained between << and >> but I don't know how.
Is anyone able to help?
Thanks a lot!
From your following reply,
Each document is a Google Docs file. I need to extract the email address which is written in the body of the document, convert the document to PDF, and send it as an attachment to the email address extracted from the original Doc.
I believe your goal is as follows.
You have a folder including Google Document files.
Each Google Document has a text like <<example#example.com>>.
You want to retrieve the email address of example#example.com from <<example#example.com>> in Google Document, and want to convert the Google Document to PDF format, and then, you want to send an email to the retrieved email address including the PDF file as an attachment file.
You want to achieve this using Google Apps Script.
In this case, how about the following sample script?
Sample script:
Please copy and paste the following script to the script editor of Google Apps Script, and set the folder ID of your folder, and save the script.
function myFunction() {
const folderId = "###"; // Please set your folder ID.
const folder = DriveApp.getFolderById(folderId);
const docs = folder.getFilesByType(MimeType.GOOGLE_DOCS);
const token = ScriptApp.getOAuthToken();
while (docs.hasNext()) {
const file = docs.next();
const id = file.getId();
const doc = DocumentApp.openById(id);
const obj = doc.getBody().getText().match(/<<(.+?)>>/);
if (obj) {
MailApp.sendEmail({ to: obj[1].trim(), subject: "sample subject", body: "sample body", attachments: [doc.getBlob()] });
} else {
console.log(`Email was not found in "${file.getName()}" document file.`);
}
}
}
When this script is run, Google Document files are retrieved from the folder, and the email address is retrieved from the document body. And, the document is converted to PDF format, and an email is sent to the retrieved email address by including the PDF data.
In this sample script, the subject and body of the email are the sample text. Please modify them for your actual situation.
Note:
I thought that in this case, const pdf = doc.getBlob(); and const pdf = UrlFetchApp.fetch(`https://docs.google.com/feeds/download/documents/export/Export?exportFormat=pdf&id=${id}`, { headers: { authorization: "Bearer " + token } }).getBlob(); might be able to be used for converting to PDF format.
References:
getFilesByType(mimeType)
sendEmail(message)
I have a scenario where I need to schedule an email at particular time every-day but the content of an email is present in some google doc and update on timely bases. So currently I am manually sending email and paste those content into my email but I want to automate the same.
So by doing search I found, it can be possible via google apps-script and I have written some script as below :
var id = '<my_Id>';
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
contentType: "text/html",
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url,param).getContentText();
MailApp.sendEmail(email, 'DSR', 'html only', {htmlBody:html});
Script is working fine and I can see the contents into email but the google doc has some formatting like back-ground, foreground color, table but in email it is shows as only plain text.
Thanks.
This works for me.
https://gist.github.com/erickoledadevrel/11143648
the problem is html has to be inline
Thanks.
I am using a Google Spreadsheet and its triggered App Script to compose and send daily status information in an html-formatted email. The email message body is composed using an html template into which token data are inserted from spreadsheet data and calculations. After insertion, the HtmlObject becomes the body of the email message using code like the following:
htmlBody = template.evaluate();
MailApp.sendEmail({
to: emailRecipients,
replyTo: emailReply,
subject: 'Today's Management Report',
htmlBody: htmlBody.getContent(),
});
I would also like to post the daily HtmlObject (Management Report) on our website but I cannot find a method to persist the object to a URL. Can anyone provide some guidance how to do this?
Thanks.
I will add to Jack Brown's comment above about deploying the HtmlObject as a Web app. Once you have deployed the HTML, you can get the URL with the ScriptApp service. The documentation provides an example close to what I think you are looking for: https://developers.google.com/apps-script/reference/script/service#getUrl()
// Mail the URL of the published web app.
MailApp.sendMail("myself#example.com", "My Snazzy App",
"My new app is now available at " + ScriptApp.getService().getUrl());
In case it helps others, here is the gs code I used to persist the blob and move it from Drive's root folder to its target destination folder:
// create pdf version of daily report
var title = "Daily Operations Summary - " + Utilities.formatDate(currStatusDate,'MST','MM/dd/yyyy') + ".pdf";
var htmlDaily = htmlBody.getContent();
var blob = Utilities.newBlob(htmlDaily, 'text/html').getAs('application/pdf').setName(title);
// save file and move to target folder
var fileID = DriveApp.createFile(blob).getId();
var destfolderID = "your Google folder GUID";
var file = DriveApp.getFileById(fileID);
file.getParents().next().removeFile(file);
DriveApp.getFolderById(destfolderID).addFile(file);
I use Google Apps script to export a Google Sheet as an Excel file to Google Drive. The Excel file then syncs with 6 others users to their local machines via the Google Drive Desktop app. Each time the Google Sheet is exported it creates a new file rather than replacing the old one albeit with the same filename and deletes the original version. This would be fine except that when it then syncs, with Google Drive Desktop, Windows deletes the original version and sends it to the recycle bin.
The file is created every 15 minutes and is 3mb in size so after a few weeks the recycle bins are full of Gigabytes of data.
Is it possible to update the contents of a file rather than create a new file?
Here's what I use at the moment:
var blob = exportAsExcel(spreadsheetId)
var file = DriveApp.createFile(blob).setName(excelFileName);
fileId = file.getId();
file.makeCopy(destinationFolder);
Drive.Files.remove(fileId);
}
function exportAsExcel(spreadsheetId) {
var file = Drive.Files.get(spreadsheetId);
var url = file.exportLinks['application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet'];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
return response.getBlob();
}
You can overwrite a file using Drive API. The detail information is https://developers.google.com/drive/v3/reference/files/update.
I prepared a method to overwrite a spreadsheet to existing excel file. This method uses your method exportAsExcel(). At first, please confirm whether Drive API is enabled at Google API console and Advanced Google services.
src_sheetId and dst_fileId are spreadsheet ID and existing excel file that you want to overwrite, respectively. By running overWrite(), the existing excel file is overwritten. So the file name and file ID of excel file are not changed.
Script :
function overWrite(src_sheetId, dst_fileId) {
UrlFetchApp.fetch(
"https://www.googleapis.com/upload/drive/v3/files/" + dst_fileId + "?uploadType=multipart",
{
method: "PATCH",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
payload: exportAsExcel(src_sheetId).getBytes()
}
);
}
By the way, does exportAsExcel() of your script work fine? When I use it, an error occurs. I removed the error by modification below.
From :
var url = file.exportLinks['application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet'];
To :
var url = file.exportLinks['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
If I misunderstand your question, I'm sorry.
I am trying to send a Google Document (nothing fancy here, just a simple, script-built text document) as a plain text email attachment with Google Apps Script. I can do this manually by going into my Drive and selecting "File>Email As Attachment...". From there, a window pops up asking for the recipients, file type (Where I can choose plain text), subject, message, etc. How can I do this through script?
I have another document using the following for PDFs (Where TimeDataId and email_address are properly defined):
//Get Data as .pdf file
var TimeData = DocsList.getFileById(TimeDataId).getAs('application/pdf');
// Attach pdf and send the email to customer
var subject = 'Time Data';
var body = 'Please see the attached Data.' + '<br/><br/>Thank you,';
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: TimeData});
And this works flawlessly for PDFs. However, I am really looking for something like this:
//Get Data as .txt file
var TimeData = DocsList.getFileById(TimeDataId).getAs(MimeType.PLAIN_TEXT);
// Attach txt and send the email to customer
var subject = 'Time Data';
var body = 'Please see the attached Data.' + '<br/><br/>Thank you,';
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: TimeData});
All I ever get with this method is a failure notice with the report of "Authorization is required to perform that action".
I know I could just paste the plain text information into the body of my email, but I would really like to have a downloadable file, as this saves a step for the user (this file will be used later for data import into another program). Has this question already been asked and answered? Does anyone have any ideas? Thanks for any input.
Here is how I would get text from a Document as a plain text file.
var txt = DocumentApp.openById(TimeDataId).getText();
var TimeData = Utilities.newBlob(txt, 'text/plain','myattachment.txt')
It takes an extra level of indirection but for now getAs is only supported for PDFs.
I believe you are getting that error message as the MimeType class for the new DriveApp but I haven't verified that.