php - 将 PHP 变量从 html 传递到 php 和电子邮件模板

标签 php html session phpmailer

我正在使用电子邮件模板进行简单的 PHP 表单验证。我有一个简单的表单,称为“index.html”,提交按钮的表单方法为“post”,操作为“sendmail.php”。在我的 sendmail.php 中,我有 smtp-mailer.php,其电子邮件模板称为“email-template.html”。我如何通过 sendmail.php 将变量从 index.html 传递到 mail-template.php ...明白我的意思了吗???我知道使用 SESSION。但我不知道我应该在哪里调用它以及如何获取它???有什么想法...???

index.html

<form method="post" action="sendemail.php">
  Email: <input name="email" id="email" type="text" /><br />
  Message:<br />
  <textarea name="message" id="message" rows="15" cols="40"></textarea><br />
  <input type="submit" value="Submit" />
</form>

发送邮件.php

<?php
include "class.smtp.php";
include "class.phpmailer.php";
session_start();
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
$_SESSION['message'] = $message;

$Body = file_get_contents('email-template.php');
...
...
?>

email-template.php(不在浏览器中发送到邮箱)

<table border="1">
     <tr>
        <td colspan="2">
          <h3>
            <?php
              session_start();
              $message = $_SESSION['message'];
              echo "Your registration is: ".$message.".";
            ?>
          </h3>
        </td>
     </tr>
   </table>

更新:我做了同样的事情......但没有回应......我是否错过了 sendmail.php 中的某些内容

最佳答案

您正在尝试将您的电子邮件放在它自己的模板文件中,这很好,但您需要实际执行其中的 PHP 代码来填充变量。

将 email-template.html 重命名为 email-template.phtml。这是 php 模板的一个相当标准的扩展。 值得注意的是,不建议在 PHP 中使用 $_REQUEST,因为它同时接受 POST 和 GET 参数,并且您已决定用户需要 POST 表单。

sendmail.php 中包含并执行模板文件:

<?php
include "class.smtp.php";
include "class.phpmailer.php";

function render_email($email, $message) {
    ob_start();
    include "email-template.phtml";
    return ob_get_contents();
}

$email = $_POST['email'] ;
$message = $_POST['message'];

$body = render_email($email, $message);
...
...

render_email 包含模板文件,将 $email 和 $message 这两个变量暴露给该模板文件,然后返回包含模板的输出。

您在 template.phtml 中使用这些变量,就像您之前尝试做的那样。 电子邮件模板.phtml:

<table border="1">
 <tr>
 <td colspan="2">
    <h3>
        Your registration is:<?= htmlspecialchars($message) ?>
</h3>
</td>
</tr>
</table>

关于php - 将 PHP 变量从 html 传递到 php 和电子邮件模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30891780/

相关文章:

css - 绝对定位按钮不会出现在固定标题上

Python - Flask 不存储 session

php - 使用 MIN() 为每个代码仅选择一条记录 (MySQL)

php - Netbeans - 虚拟主机的配置

python - bottle request.forms.get 返回 None

javascript - 反转过滤器不适用于 IE 和 safari

跨同一域的子页面的 PHP session

python - 多个子域的 Django 多 session cookie 域

PHP 简单 HTML DOM 解析器 : make it loop until no error

PHP-FPM 监听队列已满,我的配置有什么问题?