使用变量和外部 HTML 模板通过 PHP 发送 HTML 电子邮件

Sending HTML Email via PHP with Variables and External HTML Template

我正在尝试通过 PHP 发送电子邮件。最初我的 $message 变量被设置为 html 以及来自用户输入的 PHP 变量。这很好用——我收到了包含正确变量和所有变量的电子邮件。

然后我尝试包含一些逻辑来检查用户从他们填写的表单中选择了哪个服务,并基于此更改了 $message 变量的内容(即输出 html 内容略有不同)。

为了不让 html 文件太长,我决定将 html 代码移动到单独的文件中,并将 $message 变量 = 设置为 file_get_contents( ) 。电子邮件发送正常,但我的变量不再显示用户输入数据。我什至尝试在 html 模板所在的文件顶部使用 session_start()。

<?php
session_start();

$_SESSION["service"] = $_POST['service'];

if (isset($_POST['submit'])){
  $service = $_POST['service'];
  
  if($_POST['service']=="Service 1"){$message = 'email_template-service-1.php';}
    else $message = file_get_contents("email_template-service-2.php");

    $to = 'email@example.com';
    $subject = 'Subject';
    $headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .

    mail($to, $subject, $message, $headers);
    header('Location: /confirmation.php');
}

else {header('Location: /index.php');}
?>

我是不是漏掉了什么? TIA!

更好的方法是只包含文件并使用 ob_get_clean():

ob_start();
if($_POST['service']=="Service 1") {include 'email_template-service-1.php';}
else include 'email_template-service-2.php';
$message = ob_get_clean();

ob_start()$message = ob_get_clean() 之间回显的任何内容都将进入 $message 变量。