Youngbin Lee
Youngbin Lee

Reputation: 45

How to get text with formatting from Docs and use it for body to send email

I'd like to send emails from spreadsheet using contents of google docs file for a message (E-mail body). This is what I have now, which works fine.

*Part of code

var doc = DocumentApp.openById(row[9]);
var message = doc.getText();

MailApp.sendEmail(emailAddress, subject, "Dear " + row[6] +"\n\n"+ message + "\n\n"+ row[1] + "\n" + row[2] + "\n" + row[3] + "\n" + row[4]);

It works perfectly fine but the e-mail message is plain text.

I have a little bit of formatting such as Blod/Colored/List format... and etc. How can I keep those formatting in e-mail message?

I tried getBody() or getParagraph(), but it only returned "Document" or "Paragraph, Paragraph, Paragraph".

*FYI
I tried this. How to send rich text emails with GmailApp? which worked okay, but I'm trying to find a solution to use rich text directly to email. Not work-around using html format.

Upvotes: 1

Views: 3485

Answers (1)

Adharsha Neel
Adharsha Neel

Reputation: 504

function test_mail_() {
 var id = DocumentApp.getActiveDocument().getId();
 var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + id + "&exportFormat=html";
 var param = {
    method: "get",
    headers: {
        "Authorization": "Bearer " + ScriptApp.getOAuthToken()
    },
    muteHttpExceptions: true,
 };
 var html = UrlFetchApp.fetch(url, param).getContentText();
 var raw = Utilities.base64EncodeWebSafe("Subject: Test\r\n" +
    "From: " + Session.getActiveUser().getEmail() + "\r\n" +
    "To: [email protected]\r\n" +
    "Content-Type: text/html; charset=UTF-8\r\n\r\n" +
    html + "\r\n\r\n");
 var message = Gmail.newMessage();
 message.raw = raw;
 var sentMsg = Gmail.Users.Messages.send(message, '[email protected]');
} 

This worked for me. hope this may help

Upvotes: 2

Related Questions