Reputation: 123
I am trying to change text in the html that is sent via email to a JS variable that I have defined. It is important that I am doing this in Google Scripts and have 2 files Code.gs & Email.html.
It seems like my html is not able to access the JS variable but I am not sure where I am going wrong here. I have referenced somewhat similar posts and tried a could different ways but cant get it to work. If anyone ha suggestions, that would be fantastic.
Code.gs
var JSname;
function Email() {
JSname = 'It works!'
var theEmail = '[email protected]';
var theSubject = 'Email subject line';
var template = HtmlService.createTemplateFromFile('Email');
var message = template.evaluate().getContent();
MailApp.sendEmail({ to: theEmail, subject: theSubject, htmlBody: message });
return
}
Email.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<span id="HTMLname">[Text here]</span>
<script type="text/javascript" src="Code.gs">
document.getElementById("HTMLname").innerHTML = JSname;
</script>
</body>
</html>
Upvotes: 2
Views: 140
Reputation: 8921
You're using a variable out of scope, simple as that
Use template vars:
code.gs
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index'); // Or whatever you have
var JSname = 'It works!' // Ideally var names should start with lowercase
template.JSname = JSname // This is the IMPORTANT change
// Build and return HTML in IFRAME sandbox mode. (Copied from GS directly)
return template.evaluate()
.setTitle('Web App Window Title')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function Email() {
var theEmail = '[email protected]';
var theSubject = 'Email subject line';
var template = HtmlService.createTemplateFromFile('Email');
var message = template.evaluate().getContent();
MailApp.sendEmail({
to: theEmail,
subject: theSubject,
htmlBody: message
});
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<span id="HTMLname"><?= JSname ?></span>
</body>
</html>
Upvotes: 1