Create Dynamic HTML Email Templates with Apps Script
Hardcoding HTML strings in your script is messy and hard to maintain. Apps Script's HtmlService supports proper HTML template files — keeping your markup clean and your code readable.
Method 1: Simple string interpolation
For quick, one-off emails, build HTML strings directly:
functionsendSimpleTemplate(name, product, amount){const html =` <div style="font-family:sans-serif;max-width:600px;margin:0 auto;">
<h2 style="color:#1a73e8;">Order Confirmation</h2>
<p>Hi ${name},</p>
<p>Thank you for your order of <strong>${product}</strong>.</p>
<p>Total: <strong>$${amount}</strong></p>
<a href="#" style="display:inline-block;padding:12px 24px;background:#1a73e8;color:#fff;text-decoration:none;border-radius:4px;">
View Order
</a>
</div>
`;GmailApp.sendEmail('[email protected]','Your Order Confirmation','',{htmlBody: html });}
Method 2: HtmlService template files
For complex, reusable templates, use .html files in your Apps Script project.
Create an HTML template file
In the script editor, click + > HTML file and name it EmailTemplate.
functionsendTemplateEmail(){const template =HtmlService.createTemplateFromFile('EmailTemplate');// Inject data template.title='Your Invoice is Ready'; template.name='Alice Smith'; template.message='Here is a summary of your recent purchase:'; template.items=[{name:'Apps Script Course',amount:'49.00'},{name:'Template Pack',amount:'19.00'},];const htmlBody = template.evaluate().getContent();GmailApp.sendEmail('[email protected]','Your Invoice — March 2025','Please view this email in an HTML-compatible client.',{ htmlBody });Logger.log('Template email sent.');}
Send personalised emails to everyone in a Sheet
functionsendBulkTemplateEmails(){const sheet =SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();const data = sheet.getDataRange().getValues().slice(1); data.forEach(([name, email, product, amount, sent])=>{if(sent ==='Yes'||!email)return;const template =HtmlService.createTemplateFromFile('EmailTemplate'); template.title='Your Order Confirmation'; template.name= name; template.message=`Your order has been received and is being processed.`; template.items=[{name: product,amount: amount }];const htmlBody = template.evaluate().getContent();GmailApp.sendEmail(email,'Order Confirmation','',{ htmlBody });// Mark as sentconst rowIndex = data.indexOf([name, email, product, amount, sent])+2; sheet.getRange(rowIndex,5).setValue('Yes');});}