0

So, I've been looking through StackOverlow for a while now, and the closest answer I found is this.

I have built a template for sending emails and I'd like to reuse it for other purposes, such as the description of an event. I'm struggling to get a printout of the HTML template in a readable format, exactly as you get it in the email.

Here's the HTML template:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
<p>Hi <?!= OOOCLIENTFIRSTNAME?>,</p>
  </body>
</html>

Here's the template code:

var emailtemplate  = HtmlService.createTemplateFromFile('XXXXX');
  emailtemplate.OOOCLIENTFIRSTNAME = clientfirstname;
var emailbody = emailtemplate.evaluate();

So, when I place it into the sendEmail method parameter's htmlbody property, it works perfectly and email is sent as planned. Here's the GmailApp code:

GmailApp.sendEmail(clientemail, 'TEST TITLE', '',
                      {htmlBody: emailBody.getContent()};

I want to get the result as a simple string, such as "Hi firstname". I have tried to use .getContent but this results in getting the HTML source code, and not its output. Any ideas?

1
  • Please do not use code snippets for scripts that cannot be run without external dependencies or platforms. Use proper code formatting [Ctrl+K] instead: single backticks (“`”) for one-liners, property names and methods, code fences (“````”) for code blocks. Also please avoid chit-chat in questions, SO is not a forum, it is a Q&A website. Commented Jul 10, 2020 at 21:44

1 Answer 1

1

I suggest you a different approach:

Just build your greeting in the Apps Script part before passing it to HTML.

Code:gs

function myFunction() {
  var emailtemplate  = HtmlService.createTemplateFromFile('index');
  var greeting = "Hi " + clientfirstname + ",";
  emailtemplate.OOOCLIENTFIRSTNAME = greeting;
  var emailBody = emailtemplate.evaluate();
  GmailApp.sendEmail(clienemail, 'TEST TITLE', '',{htmlBody: emailBody.getContent()});
  var reusedGreeting = greeting + " how are you?";
  Logger.log(reusedGreeting);
}

index.html:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
<p> Hi <?!= OOOCLIENTFIRSTNAME?>,</p>
  </body>
</html>

Why?

When you evaluate a template within a normal function, (opposed to building a WebApp with a doGet() function that would allow you to pass a variable to serverside with google.script.run) there is no easy way to retrieve the inner HTML. You'd need to either

  • extract the string with Regex
  • or parse the html as explained e.g. here

Both solutions would be an overkill for what you are trying to do.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.