Search code examples
google-apps-scriptgoogle-sheetsgmail

Sending Google Doc email template as html format on Email


I've google docs template with logo and some images plus some text instructions, and I want to send it over email exactly how it appear in Google Docs, I know how to send plain text from google docs but can't figure out how to send templates with images.

Here is the code I am using currently :-

      var body = doc.getBody().getText();
      var message = body;
      var subject = "subject line";
      MailApp.sendEmail (user.primaryEmail, subject, message)

Updated script as suggested by Tanaike :-

function getDocAsHtml(docId){ 
var doc = DocumentApp.getActiveDocument()
var url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=html&id=" + doc.getId();
var html = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getContentText();
var body = doc.getBody().getText();
var message = body;
var subject = "subject line";
MailApp.sendEmail('[email protected]', subject, message, { htmlBody: html });
}

Solution

  • I believe your goal is as follows.

    • You want to send an email as the HTML body of the Google Document.

    In this case, how about the following modification? From your showing script, I suppose that doc is the object of Document.

    Modified script:

    var url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=html&id=" + doc.getId();
    var html = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getContentText();
    var body = doc.getBody().getText();
    var message = body;
    var subject = "subject line";
    MailApp.sendEmail(user.primaryEmail, subject, message, { htmlBody: html });
    // DriveApp.getFiles(); // This is used for automatically detecting the scope of Drive API.
    
    • When this script is run, the Google Document of doc is sent as the HTML body.

    Note:

    • In this case, the mail client cannot show the HTML body, the text body of message is shown.

    References: