2012-08-06 178 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