Prompt
How do I send personalized emails with variables from my code?
Latest observation
You typically send personalized emails by using an email template with placeholders, then filling those placeholders with data from your code before sending.
Basic idea
-
Create a template like:
Hi {{first_name}}, Your order {{order_id}} has shipped. -
In your code, replace the variables with real values:
first_name = "Alice"order_id = "12345"
-
Send the final email content through your email provider or SMTP.
Common ways to do it
1. Simple string interpolation
Good for quick scripts.
Python
first_name = "Alice"
order_id = "12345"
subject = f"Your order {order_id} has shipped"
body = f"Hi {first_name},\n\nYour order {order_id} is on the way."
JavaScript
const firstName = "Alice";
const orderId = "12345";
const subject = `Your order ${orderId} has shipped`;
const body = `Hi ${firstName},\n\nYour order ${orderId} is on the way.`;
2. Template engines
Better for larger apps because they separate content from code.
Examples:
- Python: Jinja2
- Node.js: Handlebars, EJS, Mustache
- PHP: Twig
- Ruby: ERB
Example with Jinja2-style template
<p>Hi {{ first_name }},</p>
<p>Your order {{ order_id }} has shipped.</p>
Then render it with data from your code.
3. Email service provider templates
If you use services like SendGrid, Mailgun, Amazon SES, or Postmark, they often let you define templates with variables directly on their platform.
Example placeholders:
Hello {{name}},
Your subscription renews on {{renewal_date}}.
Then your code sends a JSON payload like:
{
"name": "Alice",
"renewal_date": "2026-01-15"
}
Example: Python with a template
from jinja2 import Template
template = Template("""
Hi {{ first_name }},
Your order {{ order_id }} has shipped.
""")
html = template.render(first_name="Alice", order_id="12345")
print(html)
Example: Node.js with template literals
function buildEmail({ firstName, orderId }) {
return `
Hi ${firstName},
Your order ${orderId} has shipped.
`;
}
const emailBody = buildEmail({
firstName: "Alice",
orderId: "12345"
});
Tips
- Always escape user-generated content to avoid HTML injection.
- Keep templates separate from application logic.
- Use a mail service for better deliverability instead of raw SMTP if possible.
- Test with sample data before sending to real users.
If you want, I can show you a complete example in Python, JavaScript, PHP, or Node.js.