You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何添加选项将文本、用户名标题等数据传入HTML文件用于邮件发送

Hey there! Let's walk through exactly how to pass dynamic data like custom text, usernames, and email subjects into an HTML template for sending emails, plus set up flexible ways to feed that data in. I'll cover practical examples for two popular tech stacks so you can adapt this to your setup.

Passing Dynamic Data to HTML Email Templates & Adding Invocation Options

1. Use a Template Engine (The Standard, Clean Approach)

Template engines are the most reliable way to inject dynamic data into HTML. They let you add placeholder tags in your template, then populate them with real values via code—no messy string concatenation required.

Example 1: Node.js with Handlebars

First, install the necessary dependencies:

npm install handlebars nodemailer

Create your HTML template (email-template.hbs) with placeholders:

<!DOCTYPE html>
<html>
<head>
  <title>{{emailSubject}}</title>
</head>
<body>
  <h1>Hey, {{username}}!</h1>
  <p>{{emailContent}}</p>
  <p>Cheers,<br>Your Team</p>
</body>
</html>

Now write the code to load the template, inject data, and send the email:

const handlebars = require('handlebars');
const nodemailer = require('nodemailer');
const fs = require('fs');

// Read the template file
const templateSource = fs.readFileSync('./email-template.hbs', 'utf8');
const template = handlebars.compile(templateSource);

// Pull data from command line args (or API/database)
const emailData = {
  username: process.argv[2] || 'Guest',
  emailSubject: process.argv[3] || 'Default Update',
  emailContent: process.argv[4] || 'This is a default email message.'
};

// Generate the final HTML
const htmlOutput = template(emailData);

// Set up your email transporter (use your SMTP provider details)
const transporter = nodemailer.createTransport({
  service: 'Gmail',
  auth: {
    user: 'your-email@gmail.com',
    pass: 'your-app-specific-password'
  }
});

// Define email options and send
const mailOptions = {
  from: 'your-email@gmail.com',
  to: 'recipient@example.com',
  subject: emailData.emailSubject,
  html: htmlOutput
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) return console.log(`Oops, error sending: ${error}`);
  console.log(`Email sent successfully! Response: ${info.response}`);
});

Invocation via command line:

node send-email.js "Mike Taylor" "Your Monthly Report" "Hi Mike, here's your breakdown of this month's activity..."

Example 2: Python with Jinja2

Install dependencies first:

pip install jinja2 smtplib

Create your HTML template (email-template.html):

<!DOCTYPE html>
<html>
<head>
  <title>{{email_subject}}</title>
</head>
<body>
  <h1>Hello, {{username}}!</h1>
  <p>{{email_content}}</p>
  <p>Thanks,<br>The Team</p>
</body>
</html>

Write the Python code to render and send:

from jinja2 import Environment, FileSystemLoader
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import sys

# Load the template from the current directory
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('email-template.html')

# Fetch data from command line args (or other sources)
username = sys.argv[1] if len(sys.argv) > 1 else 'Guest'
email_subject = sys.argv[2] if len(sys.argv) > 2 else 'Default Subject'
email_content = sys.argv[3] if len(sys.argv) > 3 else 'This is a default email message.'

# Render the template with your data
html_output = template.render(
    username=username,
    email_subject=email_subject,
    email_content=email_content
)

# Set up the email message
msg = MIMEMultipart()
msg['From'] = 'your-email@gmail.com'
msg['To'] = 'recipient@example.com'
msg['Subject'] = email_subject

msg.attach(MIMEText(html_output, 'html'))

# Send via SMTP
with smtplib.SMTP('smtp.gmail.com', 587) as server:
    server.starttls()
    server.login('your-email@gmail.com', 'your-app-specific-password')
    server.send_message(msg)

print("Email sent successfully!")

Invocation via command line:

python send-email.py "Sarah Lee" "Important Alert" "Hi Sarah, please review the attached document by EOD today."

2. Flexible Invocation Options for Passing Data

Beyond command line arguments, here are other ways to feed data into your email script:

  • Environment Variables: Great for sensitive or global values (e.g., process.env.USERNAME in Node.js, os.getenv('USERNAME') in Python)
  • API Request Payload: If your email service is API-driven, accept JSON data via a POST request (e.g., {"username": "Bob", "emailContent": "..." })
  • Configuration Files: Store common data in a JSON/YAML file (like config.json) and load it on startup
  • Database Fetch: Pull user info and email content directly from a database (perfect for bulk email campaigns)

3. Critical Best Practices

  • Escape Dynamic Content: Most template engines auto-escape HTML special characters, but double-check to prevent XSS attacks (e.g., blocking <script> tags in user input)
  • Add Plain Text Fallback: Always include a plain text version of your email—some clients don't render HTML well
  • Test Responsiveness: Email clients have weird HTML support; use tools to test how your template looks across platforms

内容的提问来源于stack exchange,提问作者Jesper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:47:17