Prompt
How do I set up email templates with variables for user-specific content?
Latest observation
Nov 6, 2026
OpenAI APIWeb search: off
To set up email templates with user-specific variables, you typically do three things:
- Create a template with placeholders
- Pass user data into the template when sending
- Render the final email by replacing placeholders with real values
1) Define the template
Use placeholders for fields that change per user, such as:
{{first_name}}{{last_name}}{{email}}{{reset_link}}{{company_name}}
Example email template:
<h1>Hi {{first_name}},</h1>
<p>Welcome to {{company_name}}!</p>
<p>To get started, verify your email here:</p>
<a href="{{verification_link}}">Verify Email</a>
2) Store templates separately
Common options:
- Database: good for editable templates
- File system: good for simple static templates
- Email service provider templates: SendGrid, Mailgun, AWS SES, Postmark, etc.
A template record might look like:
{
"name": "welcome_email",
"subject": "Welcome to {{company_name}}",
"body": "<p>Hi {{first_name}}, ...</p>"
}
3) Replace variables at send time
When sending an email, load the template and inject the recipient’s data.
Example data:
{
"first_name": "Alice",
"company_name": "Acme",
"verification_link": "https://example.com/verify?token=abc123"
}
Rendered result:
<h1>Hi Alice,</h1>
<p>Welcome to Acme!</p>
<a href="https://example.com/verify?token=abc123">Verify Email</a>
Example in JavaScript
Using a simple string replacement approach:
function renderTemplate(template, variables) {
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
return variables[key] ?? '';
});
}
const template = `
<h1>Hi {{first_name}},</h1>
<p>Welcome to {{company_name}}!</p>
`;
const data = {
first_name: 'Alice',
company_name: 'Acme'
};
const html = renderTemplate(template, data);
console.log(html);
Better approach: use a templating engine
For more robust templates, use a library like:
- Handlebars
- Mustache
- EJS
- Liquid
These support:
- conditionals
- loops
- escaping HTML
- partials/components
Example with Handlebars:
const Handlebars = require('handlebars');
const template = Handlebars.compile(`
<h1>Hi {{first_name}},</h1>
<p>Your order {{order_id}} is confirmed.</p>
`);
const html = template({
first_name: 'Alice',
order_id: '12345'
});
Best practices
- Escape user input to prevent HTML injection
- Provide defaults for missing variables
- Keep subject and body templated
- Test rendering with sample users
- Preview emails before sending
- Log missing variables so templates don’t fail silently
Example fallback:
variables.first_name ?? 'there'
So the email becomes:
Hi there,
Recommended workflow
- Create an email template with placeholders
- Save template in DB or email provider
- Fetch user data
- Merge template + variables
- Send rendered email
If you want, I can also show you:
- a database schema for storing templates,
- an example in Python / Node.js / PHP,
- or how to do this with SendGrid / Mailgun / AWS SES.