Google Apps Script Gmail getPlainBody Line Breaks - google-apps-script

With the Google Apps Script Gmail library, when I use the function GmailMessage.getPlainBody(), the API seems to take what used to be one paragraph and break it up into multiple, potentially by using a character limit. For instance, a paragraph of my email reads:
From the link you sent me, I gleaned that Gmail refers to their secure email as confidential.
But when I call this function on the email, it becomes:
From the link you sent me, I gleaned that Gmail refers to their
secure email as confidential.
And, when I split the email text on a new line delimitor and do a bit of cleanup to create an array with my output, I end up with:
['From the link you sent me, I gleaned that Gmail refers to their', 'secure email as confidential.']
I viewed this Reddit post, which seemed to deal with the similar problem. But, I tried the resolution suggested by the person who posed the question:
body = message.getPlainBody().replace(/\r\n\r\n/gm,'aaaLINEBREAKERaaa').replace(/\r\n/gm,' ').replace(/aaaLINEBREAKERaaa/gm, '\r\r').replace(/ /gm,' ')
And it didn't quite give me what I need. Has anyone else encountered this problem, and if so, do you have a suggested workaround? Thanks!

I had the same issue. In that case, I used a workaround.
When I checked the email, I noticed that the HTML body is included in the message body and the HTML body has the original paragraph, and I used this situation. So, in this workaround, the original text is retrieved from the HTML body and the HTML is converted to a text. By this, the original paragraph is obtained. The sample script is as follows.
Sample script:
This script uses Drive API for converting HTML to text. So pelase enable Drive API at Advanced Google services.
var message = // Here, please use your "message".
var html = message.getBody();
var id = Drive.Files.insert({title: "temp", mimeType: MimeType.GOOGLE_DOCS}, Utilities.newBlob(html, MimeType.HTML)).id;
var text = DocumentApp.openById(id).getBody().getText(); // or DocumentApp.openById(id).getBody().getText().trim();
DriveApp.getFileById(id).setTrashed(true);
console.log(text)
References:
getBody()
Files: insert

Related

Google Script doc.getBody() returns plain text

Just a quick question, is there anyway that I can get the body of my google doc to be as exact as it is? For example, I have a bold sentence in my google doc, but whenever i'm trying to send it using via sendEmail in google script, it's being sent as plaint text, the bold letters an other formatted texts are being converted into plain, please see my code:
var body_hw1 = doc_hw1.getBody().getText();
MailApp.sendEmail(email, subject_hw1, body_hw1);
The method getBody() returns an object that is not usable outside of Google Docs. The method getText() returns plain text.
In order for use bold fonts, etc, in an email, it has to be formatted as HTML. So you need to convert Google document to HTML. There is no built-in function for this, but a third-party solution is available: it does not support full range of Docs format but certainly supports bold and italic fonts, and similar. See this answer.
Another solution would be to extract the plain text and format it into html yourself and send that. For example:
var myText = {header:'Dear sir,',message:'We are writing to inform you...'}
var message = ("<h3>"+ myText.header +"</h3>" +
"<p>"+ myText.message +"</p>")
MailApp.sendEmail(email, 'Important Message', message);

Sending HTML emails using google ap script

I'm trying to send HTML emails using Google aps script. I've got the HTML on a google doc which i'm trying to send using the code below. But when I send it I receive it as unformatted text with all the HTML tags displayed. Can anyone tell me how to do this? I'd rather not include the HTML in the script, because there will eventually be an awful lot of it.
var html = UrlFetchApp.fetch('https://docs.google.com/document/d/documentID/export?format=html');
MailApp.sendEmail('emailaddress', subject, null , {htmlBody: html});
Thanks, Bryan
Here's an example of doing the same thing with a row of spreadsheet data. Link. Don't use css between <style></style> tags. Use inline style="" instead. That seems to work better.
Google Script Mail App
The format of your code seems not well-structured,
Make sure all the data passed to the:
.sendEmail() method is in Curly braces {}.
Please reference the code below to see how it works.:
MailApp.sendEmail({
to: "me#myservice.com",
subject: "Testing",
htmlBody:"<h1>Hello there</h1><p>Your HTML Here</p>"});
That's it. You can also send this HTML from external file as:
HTMLService.createTemplateFromFile("fileName")

email google spreadsheet as html

I am trying to create a google script that emails out a spreadsheet as html. I am trying to convert the spreadsheet to html using the export url, but currently google docs only lets you export it out as a zip. Is there a way to get the html representation of a spreadsheet worksheet?
function getDocAsHtml(docId){
var url="https://docs.google.com/spreadsheets/d/" + docId + "/exportFormat?format=html";
var fetch=UrlFetchApp.fetch(url+docId).get
return fetch;
}
Publish the sheet that you want to get the HTML out of:
File Menu, PUBLISH TO WEB
Make sure that: "Automatically Republish When Changes Are Made" is checked.
Get the URL of the published page. Use that URL in a UrlFetchApp.fetch() request.
Use UrlFetchApp to get the content of that published sheet.
function fncSheetToHTML() {
var theSheetContents = UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/YourID_Here/pubhtml?gid=123abc&single=true");
Logger.log("theSheetContents: " + theSheetContents);
}
The returned contents is a string. If you view the LOGS of what is returned from the above code, you'll see HTML tags in the content.
The published sheet is visible to anyone who uses that URL. So, if you don't want people to see the contents, this method might not be what you want. If you don't share that published URL, I don't know how likely it is that anyone will ever find it.

How can I create superscript/subscript characters in a document?

I'm working on a script to convert some documents in a proprietary format over to google docs. I've been able to handle most of the various formatting options (fonts, point sizes, bold, etc.) but I'm stuck on subscript and superscript.
I've tried creating a new google doc with a paragraph in subscript. I then wrote a script to look at the paragraphs and children and in both cases didn't see an attribute that was set as I could for underline.
I've tried wrapping the text in st but that only added that exact text to the document. Here is a bit of the code I'm currently using:
if (superscript == true ) {
paragraph.appendText(txt.sup()).setAttributes(style);
} else if (subscript == true) {
paragraph.appendText(txt.sub()).setAttributes(style);
} else {
paragraph.appendText(txt).setAttributes(style);
}
Anything else to try?
There's currently no way to do this — it would exist somewhere in the Text class API (https://developers.google.com/apps-script/reference/document/text) if it were possible.
I filed a feature request for superscript / subscript here https://code.google.com/p/google-apps-script-issues/issues/detail?id=2885 . Feel free to star the issue to register your support.
For the benefit of anyone looking for this, it's been implemented since this question was asked as a TextAlignment class - it's not explicit in the documentation*, but thankfully these create indices on text elements observed with the getTextAttributeIndices method.
* as in, it's not an attribute listed by getAttributes but is indexed with getTextAttributeIndices()
I've just modified a Docs-to-markdown processing script I'm working on to incorporate sub- and superscript alignment handling which may be useful as an example (see commit diff).
Note that if applied across paragraphs the getTextAlignment method returns null.
You want to put the superscript and subscript characters to Google Document using Google Apps Script.
If my understanding is correct, how about this sample script? Unfortunately, even in the current stage, there are still no methods for putting the superscript and subscript characters using Document Service.
But when Google Docs API which was added at early 2019 is used, those can be achieved. Such function might be added to Document Service in the future. So as a current workaround, I would like to propose the method using Docs API. The sample script is as follows.
Before you use this script, please enable Google Docs API at Advanced Google services.
Sample script:
function myFunction() {
var documentId = "###"; // Please set document ID here.
var resource = {requests: [
{insertText: {text: "SampleSuperscriptSubscript", location: {index: 1}}},
{updateTextStyle: {range: {startIndex: 7, endIndex: 18}, textStyle: {baselineOffset: "SUPERSCRIPT"}, fields: "baselineOffset"}},
{updateTextStyle: {range: {startIndex: 18, endIndex: 27}, textStyle: {baselineOffset: "SUBSCRIPT"}, fields: "baselineOffset"}}
]};
Docs.Documents.batchUpdate(resource, documentId);
}
Result:
When above script is run for new Google Document, the following result is obtained. At first, a text of SampleSuperscriptSubscript is put. Then, the text style is modified. These are run using the batchUpdate method. If you want to put those values for the existing Document, please modify above object of resource.
References:
Document Service
Google Docs API
Advanced Google services
Method: documents.batchUpdate
TextStyle
BaselineOffset
If this was not the direction you want, I apologize.

How to access or call "Send this form to others"?

I have a form attached to a Google Apps spreadsheet. It's a form to let my coworkers submit agenda items to our weekly review meeting. I'm writing a script to automatically email a reminder to the relevant people.
To make it less annoying & tedious for them, I'd like to actually embed the form within the email. Google Docs provides a way to manually send a form: Spreadsheet > Form > Send form. However, I can't find any way in the Google Apps Scripts documentation that lets me trigger this functionality, e.g.
A method like sendFormInEmail
Access to the email-friendly form HTML, which I could assign to the htmlBody argument of the sendEmail method.
Trigger an arbitrary menu item in Google Apps
Something else?
I could do a workaround by extracting the generated HTML from an email and assigning it as the htmlBody argument, but then I'd have to manually update the html every time we want to make a change to the form -- not what I want to happen.
Any suggestions?
Joris, you're right. You can use the method fetch() to send the form's html to the user's mailbox:
var form = FormApp.create('New Form');
....
var url = form.getPublishedUrl();
var response = UrlFetchApp.fetch(url);
var htmlBody = HtmlService.createHtmlOutput(response).getContent();
MailApp.sendEmail({
to: email,
subject: subject,
htmlBody: htmlBody,
});
...
I have the exact same requirement as you do, but unfortunately there doesn't seem to be an API call that does this.
What I think might work (though I have yet to actually try this) is to use the Spreadsheet.getFormUrl method to get the form URL, then use UrlFetchAp.fetch to obtain the HTML for the spreadsheet form, and then use that HTML as the e-mail body.
Like I said, I don't know if this will work (though on paper it should!), but I'd be very interested to know if it did!