2012-08-06 179 views
1

我有以下代码向用户发送验证邮件,其中包含用于验证目的的一些变量,如用户名和标记。该变量明显地以个人为基础变化。但是,我想单独将此消息存储在PHP include_path中,以便在需要时可以在其他位置重新使用它。我不想硬编码它喜欢它现在是:如何在PHP中存储电子邮件模板?

$to = $username; 
$subject = 'Account Verification'; 
$now = date('Y-m-d H:i:s',time()); 
$message = " 
Date sent:$now 

Thanks for signing up! 

Your account has been created, however we need to verify that this is your email address. Here is your verification token which you should copy and paste on the verification page: 

<strong>$token</strong> 

Alternatively, click the below link to activate your account: 

http://localhost/login/verification.php?username=$username&token=$token 

If you did not register with us. You <a href='http://localhost/login/'>can click</a> here to report this to us, or ignore this email. 

Thanks, 

The LocalHost Team 
"; 
mail($to, $subject, $message); 

所以三个问题:

  1. 我如何保存这条消息是像这样的模板中的变量仍然可以访问?
  2. 如何使用html标记将此消息转换为HTML格式良好的消息?
  3. 我可以这样做:

    $ to = $ username; $ subject ='账户验证'; $ now = date('Y-m-d H:i:s',time()); $ message = include“verification_template.php”; 邮件($ to,$ subject,$ message);

+0

不,你不能。包括()不返回的代码。你想要的是'eval()'的一些变体,这通常是一个坏主意。不要用php的mail()函数做HTML邮件。实际上,根本不要使用PHP的mail()。 。使用PHPmailer或Swiftmailer(谷歌它们)代替 – 2012-08-06 03:00:32

回答

2

我解决列入这样的:

ob_start(); 
include $filename; 
$message = ob_get_clean(); 
+0

如果你发送HTML邮件,在你的邮件头中包含一行'Content-type:text/html; charset = iso-8859-1'。 – mariusnn 2012-08-06 03:36:37

0

或者到PHP,你可以用模板引擎,如Smarty生成需要为您的电子邮件的HTML /文本。

使用模板引擎的好处是,你的模板可以包含简单的逻辑(如条件,循环处理动态数据。

+0

Trying现在学习如何使用Smarty,我对SMARTY_DIR常量感到困惑,我不明白它的目的是什么?它看起来像是另一个常量,因为你需要d来定义它,然后用它来查找库。但是,如果您使用绝对路径或相对于include_path的路径来查找库,那么这为您节省了额外的一行,您需要先定义SMARTY_DIR?...... confused ...您能否解释它的用法?谢谢 – chaser 2012-08-06 11:09:05