问题
I need to take the contents of a Google Doc and turn it into the HTML code equivalent (for sending as an HTML email), via Google Apps Script.
I can read the file and get the text by cycling thru the elements in the body, but how would one get the formatting (bold, italic) into HTML? Via isBold(offset) and isItalic(offset) and cycling thru each character?
Thanks for any help. ~
回答1:
This is perfectly doable using a document to compose your message, converting it to html format and using that as an html body in the message.
the code goes like this :
function sendAsHtmlBody(){
var id = DocumentApp.getActiveDocument().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();
MailApp.sendEmail(Session.getEffectiveUser().getEmail(),'testHTML Body','html content',{'htmlBody':doc});
}
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"};
}
This code will ask for authorization in 2 steps, one for "normal" services (mail, documentApp, ..) and a second for the Oauth function, this latter must be triggered by calling the function from the script editor (if you make a menu and let a new user call that menu it won't work..., you have to use the script editor, see issue 677 here).
And here is a shared document( read only, make a copy to use) to test the code with different fonts, an image and some text.(almost every feature available in Google docs are translated in html... only a few alignment are missing sometimes. I use that very often without noticeable issue)
回答2:
Is the default sharing option not enough? I know you can select the option to display in email. Just a thought.

回答3:
You may want to look for another solution, as I am as well. When I go to use this I hget a message stating:
OAuthConfig API is deprecated
Method UrlFetchApp.addOAuthService is deprecated
来源:https://stackoverflow.com/questions/25948900/how-to-convert-a-simple-google-text-only-document-to-html-via-google-apps-script