普通网友 2019-02-27 13:51
浏览 213
已采纳

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

I'm trying to send an email through PHP. Originally my $message variable was set to html as well as PHP variables from user input. This works fine--I'm receiving the emails with the correct variables and all.

Then I tried to include some logic which checks to see which service was selected by the user from the form they filled out, and based on that, the contents of the $message variable were changed (i.e. the outputting html content was slightly different).

In order not to have a long file with bunch of html, I decided to move the html code to separate files and set the $message variable = to file_get_contents() . The email sends fine, but my variables are no longer displaying the user input data. I even tried using session_start() at the top of the file where the html template is.

<?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' . "
" .
    'Reply-To: webmaster@example.com' . "
" .

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

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

Am I missing something here? TIA!

</div>

展开全部

  • 写回答

1条回答 默认 最新

  • dongtang1997 2019-02-27 14:31
    关注

    A better approach would be to just include the file and use 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();
    

    Anything echoed between ob_start() and $message = ob_get_clean() will go into the $message variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 我在使用VS编译并执行之后,但是exe程序会报“无法定位程序输入点_kmpc_end_masked于动态链接库exe上“,请问这个问题有什么解决办法吗
  • ¥15 el-select光标位置问题
  • ¥15 单片机 TC277 PWM
  • ¥15 在更新角色衣服索引后,Sprite 并未正确显示更新的效果该如何去解决orz(标签-c#)
  • ¥15 VAE代码如何画混淆矩阵
  • ¥15 求遗传算法GAMS代码
  • ¥15 雄安新区高光谱数据集的下载网址打不开
  • ¥66 android运行时native和graphics内存详细信息获取
  • ¥15 rk3566 Android11 USB摄像头 微信
  • ¥15 torch框架下的强化学习DQN训练奖励值浮动过低,希望指导如何调整
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部