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.
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 Google Form which I would like to automatically email someone when a new response is submitted. So far, I have just a simple HTML page with text in the body, however I would like the email content to include the form data as well.
Currently, this is what I have written:
function sendEmail(e) {
//response
var html = HtmlService.createTemplateFromFile("email.html");
var htmlText = html.evaluate().getContent();
var emailTo = "jeffreyabr#gmail.com"
var subject = "New SAP Role Request"
var textBody = "This email requires HTML support. Please make sure you open it with an email client that supports HTML"
var options = {htmlBody: htmlText};
GmailApp.sendEmail(emailTo, subject, textBody, options);
This came from following this basic YouTube tutorial.
Is there more Google Apps Script that I can add to accomplish this? Can I do this from Forms or must I do it from within Sheets?
The e.response object also contains the form data, which can be accessed by using e.response.getItemResponses().
Then to get the question, use getItem().getTitle(). To get the answer, use getResponse().
If you do not need the HTML response, then you can append the questions and answers to the textBody to display them on the email. Otherwise, you would have to add a script in your email.html using HTML scripts or google.script.run.
References:
Event Objects | onFormSubmit(e)
Class FormResponse
I have quite a long email template I want to automatically send to welcome new users.
The script copies the body of a Google Doc and uses that as the body of the email using MailApp.sendEmail.
The issue is that the email that arrives is very narrow and doesn't copy exactly what is in the template. Is there any way of formatting this to make it the same as the Google Doc template?
Any help much appreciated
var doc = DocumentApp.openByUrl("https://docs.google.com/document/d/"doc id"/edit");
var body = doc.getBody().getText();
var message = body;
var subject = "subject line";
MailApp.sendEmail (user.primaryEmail, subject, message)
I learned something new with this:
When you send an email as a plain text email it won't let you control where the line breaks are
It actually adds line breaks when you call the .getText() method, as well as part of the .sendEmail method when you are sending it just as plain text.
The easiest solution is to send it as an HTML message. I experimented with this and have what I believe the easiest solution for it below:
//this will replace the line breaks with html line breaks
var htmlBody = doc.getBody().getText().replace(/\n/g,'<br/>');
var message =
{
to: user.primaryEmail,
subject: 'subject line',
htmlBody: htmlBody
}
MailApp.sendEmail ({message})
I've tested this and this should fix your problem.
The following code isn't working, giving the following error:
TypeError: Cannot find function getFileByID in object Drive.
I'm trying to first test by directly providing ID in the script:
var atta = DriveApp.getFileByID('1XD...c'); //ID is Folder and Google Doc ID I want to attach
MailApp.sendEmail(emailto, subject, message, {
cc: emailcc,
attachments:[atta]
});
Ultimately, I want to read in the link from a Google Spreadsheet:
var range = active_actions.getRange(i+1,16) //active_actions is the spreadsheet and i+1,16 is the cell with the link
var link = range.getFormula();
var atta = DriveApp.getFileByID(link);
MailApp.sendEmail(emailto, subject, message, {
cc: emailcc,
attachments:[atta]
});
This isn't too difficult. Google Docs/Spreadsheets/etc. CANNOT be placed as an attachment in an E-mail. This is because it isn't actually a 'physical document'. It only exists on the cloud. Instead, put the URL in the email, and it will give the receiver a little box at the bottom with the Doc looking like an attachment.
It's not perfect, but it is good enough. For more details, you can see this issue request or Google's App Script Issue page:
https://code.google.com/p/google-apps-script-issues/issues/detail?id=585&q=attachment%20types&sort=-stars&colspec=Stars%20Opened%20ID%20Type%20Status%20Summary%20Component%20Owner
EDIT (To explain data fetching in SS):
To get data out of a range object, (text, number, etc.), you should use this format.
var range = getRange();
var rangeData;
var cellValue;
while (range.hasNext()) {
rangeData = range.next();
cellValue = rangeData.getValue();
}
If you an accumulator variable, you can get every bit of data in one list/string/etc.
Now that you have your data, you can E-mail it, or do anything else with it.
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