2

I'm writing an auto-replying bot for gmail using Google Apps Script (http://script.google.com). Each time I use GmailThread's Reply to reply to message:

var htmlbody = "Hello<br>This is a <b>test</b>.<br>Bye.";
var body = "Hello,\nThis is a test.\nBye.";

thread.reply(body, {htmlBody: htmlbody, from: "Myself <hello@example.com>"});

I need to write the message both in plain text body and HTML in htmlbody.

Would there be a way to write an email only in HTML (to avoid writing every email content twice, plain and HTML!), and let reply() automatically send the email both in HTML and plaintext version?


I tried

var body = htmlbody.replace(/<br>/g,'\n').replace(/<b>/g,''); 
// we should also replace </b> by '', etc.

but this is a bit of a hack. Is there a better version?

Basj
  • 41,386
  • 99
  • 383
  • 673

1 Answers1

1

Google Scripts cannot generate the plain text portion automatically but you write a simple regex based replaces that removes all the tags from the HTML for plain text.

var body = htmlBody.replace(/<.+?>/g, "");
thread.reply(body, {htmlBody: htmlbody, from: "Myself <hello@example.com>"});

Also, if you set the body to blank, most modern email clients would still be able to render the image.

Amit Agarwal
  • 10,910
  • 1
  • 32
  • 43
  • Thanks, so this confirms we have to do it manually and `reply` cannot do it for us. Maybe `htmlbody.replace(/
    /g,'\n').replace(/<.+?>/g, "");` would be useful as well?
    – Basj Aug 25 '17 at 14:45