我有如下代码。我无法将变量传递给php文件并发送邮件。
换句话说,我需要将一些变量发送到php文件,然后在我的正文内容中包含php文件并将其作为邮件发送。
如何解决它。我遇到的问题是 - sample.php中定义的php变量没有显示在我的正文内容中。
<?php
require("class.phpmailer.php");
function get_include_contents($filename, $variablesToMakeLocal) {
extract($variablesToMakeLocal);
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->IsHTML(true);
$mail->Username = "username@gmail.com";
$mail->Password = "password";
$mail->SetFrom("from@gmail.com");
$mail->AddAddress("addaddress@gmail.com");
$mail->Subject = "Test Subject";
$variable['one'] = 'my variable one';
$variable['two'] = 'my variable two';
$mail->IsHTML(true);
$mail->Subject = "You have an event today";
$mail->Body = get_include_contents('sample.php', $variable);
$mail->Send();
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
<table width='600px' cellpadding='0' cellspacing='0'>
<tr><td bgcolor='#eeeeee'><img src='logo.png' /></td></tr>
<tr><td bgcolor='#ffffff' bordercolor='#eeeeee'>
<div style='border:1px solid #eeeeee;font-family:Segoe UI,Tahoma,Verdana,Arial,sans-serif;padding:20px 10px;'>
<p>Variable one is <?php echo $variable['one']; ?>.</p>
<p>Variable two is <?php echo $variable['two']; ?>.</p>
<p>Thanks</p>
</div>
</td></tr>
</table>
请帮帮我。
谢谢, Kimz
答案 0 :(得分:2)
您应该从sample.php
更改您的代码
<p>Variable one is <?php echo $variable['one']; ?>.</p>
<p>Variable two is <?php echo $variable['two']; ?>.</p>
到
<p>Variable one is <?php echo $one; ?>.</p>
<p>Variable two is <?php echo $two; ?>.</p>
因为你使用了extract
函数
答案 1 :(得分:1)
答案在评论中,但解决此问题的另一种方法是将代码更改为:
$mail->Body = include('sample.php');
在sample.php而不是回显所有内容,返回它。因此,您可以将ob_start()放在顶部,然后将ob_get_clean放在sample.php的底部,也可以将html存储在多行字符串中。
<?php
return <<<EOT
<table width='600px' cellpadding='0' cellspacing='0'>
<tr><td bgcolor='#eeeeee'><img src='logo.png' /></td></tr>
<tr><td bgcolor='#ffffff' bordercolor='#eeeeee'>
<div style='border:1px solid #eeeeee;font-family:Segoe UI,Tahoma,Verdana,Arial,sans-serif;padding:20px 10px;'>
<p>Variable one is $variable[one].</p>
<p>Variable two is $variable[two].</p>
<p>Thanks</p>
</div>
</td></tr>
</table>
EOT
?>
答案 2 :(得分:0)
如果使用 extract(),则数组的键将是变量名。因此,在您的示例中,您必须在模板中使用的变量是 $ one 和 $ two
查看手册以获取更多信息: http://be2.php.net/manual/en/function.extract.php