2012-07-24 90 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。

也就是说,如果我正确地理解了这个问题。