2012-07-24 89 views
0

我在html文件裏實現了一個html郵件。我有一個使用PHPMailer類發送電子郵件的PHP文件。 我想實現的是,我應該改變的HTML內的一些文本取決於我發送電子郵件的人。在php中加載html郵件文件

這是PHP文件,發送電子郵件

<?php 
    // get variables 
    $contact_name = addslashes($_GET['contact_name']); 
    $contact_phone = addslashes($_GET['contact_phone']); 
    $contact_email = addslashes($_GET['contact_email']); 
    $contact_message = addslashes($_GET['contact_message']); 

    // send mail 
    require("class.phpmailer.php"); 
    $mailer = new PHPMailer(); 
    $mailer->IsSMTP(); 
    $mailer->Host = 'ssl://smtp.gmail.com:465'; 
    $mailer->SMTPAuth = TRUE; 
    $mailer->Username = '[email protected]'; 
    $mailer->Password = 'mypass'; 
    $mailer->From = 'contact_email'; 
    $mailer->FromName = 'PS Contact'; 
    $mailer->Subject = $contact_name; 
    $mailer->AddAddress('[email protected]'); 
    $mailer->Body = $contact_message; 
    if($mailer->Send()) 
     echo 'ok'; 
?> 

和包含有桌子和所有標準的它需要實現一個簡單的HTML郵件的HTML文件。

我想問勇敢的頭腦比我這是實現這一目標的最佳途徑。 :)

謝謝你在前進, 牛!

編輯:現在,在$ mailer->身體我有$ contact_message變量作爲文本電子郵件..但我想在該機構加載一個HTML文件包含一個HTML電子郵件,我想以某種方式更改這個$ contact_message變量中的文本的html電子郵件正文。

+0

澄清你的問題。 – 2012-07-24 18:42:41

回答

1

一個簡單的方法去是在你的HTML文件特殊標記將被調用者所取代。例如假設你有兩個變量可能會動態地更改內容,namesurname然後把你的HTML是這樣的:%%NAME%%%%SURNAME%%,然後簡單地調用腳本:

$html = str_replace("%%NAME%%", $name, $html); 
$html = str_replace("%%SURNAME%%", $surname, $html); 

或通過嵌套上述兩個:

$html = str_replace("%%NAME%%", $name, str_replace("%%SURNAME%%", $surname, $html)); 



編輯 的情況下,更優雅的解決方案,您有很多的變量:定義關聯陣列,將保留您替代他們:

$myReplacements = array ("%%NAME%%" => $name, 
          "%%SURNAME%%" => $surname 
); 

,並使用一個循環來做到這一點:

foreach ($myReplacements as $needle => $replacement) 
    $html = str_replace($needle, $replacement, $html); 
+0

我非常喜歡你的方法:)現在只有一個步驟來實現它:D如何將html文件的內容加載到php – 2012-07-24 19:16:21

+0

再次通過$ html = file_get_contents(「/ path/to/myHtmlFile.html」 ); – pankar 2012-07-24 19:19:32

+1

如果你使用這種方法,至少這樣做:http://codepad.org/4xbLFXIB,而不是爲每個「替換」調用str_replace。 – tigrang 2012-07-24 19:35:33

0

創建基於你想看到的電子郵件條件語句。 然後在tempalted php html電子郵件文本中加入。

您也可以通過改變價值觀,這將實現上述功能。

0

如果我建立一個網站,我通常使用一個模板引擎,像Smarty的......你可以寫你的HTML郵件中一個智者模板文件。然後,您可以自動添加基於標準的想要的文本。只需將正確的值分配給模板引擎即可。

0

爲了回答您的編輯:

function renderHtmlEmail($body) { 
    ob_start(); 
    include ('my_html_email.php'); 
    return ob_get_clean(); 
} 

在你的my_html_email.php文件中,你會有這樣的東西:

<html> 
    <body> 
     <p>....<p> 
     <!-- the body --> 
     <?php echo $body; ?> 
    </body> 
</html> 

而且

$mailer->Body = renderHtmlEmail($contact_message); 

如果需要其他變量傳遞到佈局/模板文件,添加PARAMS該方法,或通過關聯數組像這樣function renderHtmlEmail($viewVars)和函數內部extract($viewVars);

然後,您將能夠在模板中使用這些變量,例如。 Dear <?php echo $to; ?>,

如果還沒有,您可能必須將.html文件從.html更改爲.php。

也就是說,如果我正確地理解了這個問題。