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

如何使用SendGrid向邮件模板文件传递动态数据?

你目前使用file_get_contents()只会读取模板文件的原始文本内容,不会执行其中的PHP逻辑,也无法注入自定义变量,按照以下两种方案修改即可实现$details变量的传递:

方案一:使用PHP输出缓冲区渲染原生PHP模板

该方案适合模板本身包含PHP逻辑的场景,模板可直接调用$details变量:

$sendgrid = new SendGrid(getenv('SENDGRID_KEY'));
$email = new SendGrid\Email();

// 你要传递的业务数据
$details = [
    'order_id' => 1001,
    'customer_name' => '张三',
    'booking_date' => '2024-05-20'
];

// 开启输出缓冲区
ob_start();
// 引入模板文件,此时模板上下文中可直接使用$details变量
include '../templates/emails/third-party-booking.php';
// 捕获缓冲区渲染好的HTML内容并清空缓冲区
$message_body = ob_get_clean();

$email->addTo(getenv('SENDGRID_EMAIL'))
      ->setFrom("from@email.com")
      ->setSubject("Just a subject here")
      ->setHtml($message_body);

$sendgrid->send($email);

模板文件third-party-booking.php示例:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h2>预订成功通知</h2>
    <p>您好:<?php echo htmlspecialchars($details['customer_name']) ?></p>
    <p>您的订单号:<?php echo $details['order_id'] ?></p>
    <p>预订日期:<?php echo $details['booking_date'] ?></p>
</body>
</html>

方案二:占位符字符串替换

该方案更安全,模板无需编写PHP代码,适合非技术人员维护模板的场景:

  1. 先在模板文件中定义占位符(可自定义格式,比如用{{变量名}}):
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h2>预订成功通知</h2>
    <p>您好:{{customer_name}}</p>
    <p>您的订单号:{{order_id}}</p>
    <p>预订日期:{{booking_date}}</p>
</body>
</html>
  1. PHP代码中读取模板后批量替换占位符:
$sendgrid = new SendGrid(getenv('SENDGRID_KEY'));
$email = new SendGrid\Email();

$details = [
    'order_id' => 1001,
    'customer_name' => '张三',
    'booking_date' => '2024-05-20'
];

// 读取模板原始内容
$message_body = file_get_contents('../templates/emails/third-party-booking.php');
// 定义占位符和实际值的映射关系
$replaceMap = [
    '{{customer_name}}' => htmlspecialchars($details['customer_name']),
    '{{order_id}}' => $details['order_id'],
    '{{booking_date}}' => $details['booking_date']
];
// 批量替换得到最终渲染的HTML
$message_body = strtr($message_body, $replaceMap);

$email->addTo(getenv('SENDGRID_EMAIL'))
      ->setFrom("from@email.com")
      ->setSubject("Just a subject here")
      ->setHtml($message_body);

$sendgrid->send($email);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:15:03