我有以下发送电子邮件的功能:
function send_email($email){ $subject = "TITLE"; $message = "HERE IS THE MESSAGE"; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <emaily>' . "\r\n"; mail($email,$subject,$message,$headers); }
而不是$message是一个字符串,我想调用包含我的模板的文件email.html.
我添加了这个:
require 'email.html';
解决方法
当您想要在另一个PHP文件中调用函数时,或者想要在HTTP响应中包含一些数据时,使用Require.
对于此问题,file_get_contents(’email.html’)是首选选项.这将是我将使用的方法:
function send_email($email){ $subject = "Subject of your email"; $message = ""; if(file_exists("email_template.html")){ $message = file_get_contents('email_template.html'); $parts_to_mod = array("part1","part2"); $replace_with = array($value1,$value2); for($i=0; $i<count($parts_to_mod); $i++){ $message = str_replace($parts_to_mod[$i],$replace_with[$i],$message); } }else{ $message = "Some Default Message"; /* this likely won't ever be called,but it's good to have error handling */ } // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <doNotReply@myDomain.com>' . "\r\n"; $headers .= "To: <$email>\r\n"; $header .= "Reply-To: doNotReply@myDomain.com\r\n"; mail($email,$headers); }
我稍微修改了你的代码并添加到file_get_contents和file_exists中. file_exists确认文件在那里.如果不是,它可以避免尝试读取它的潜在错误,并可以更改为使用某些默认值.我的下一个补充是for循环.在$parts_to_mod数组中,输入需要替换的模板的默认值.在$replace_with数组中,输入要替换模板部分的唯一值.
作为我使用它的一个例子,我有一个我的程序的模板URL,其中id = IDENTIFIER& hash = THEHASH所以在我的程序中,我的parts_to_mod说$parts_to_mod = array(“IDENTIFIER”,“THEHASH”);我的replace_with说$replace_with = array($theUsersIdentifier,$theUsersHash);.然后它进入for循环,并将parts_to_modify中的值替换为replace_with中的值.
简单的概念,它们使您的代码更短,更容易维护.
编辑:
以下是一些示例代码:
让我们说模板是:
<span>Dear PUTNAMEHERE,</span><br> <div>PUTMESSAGEHERE</div> <div>Sincerely,<br>PUTSENDERHERE</div>
$parts_to_mod = array("PUTNAMEHERE","PUTMESSAGEHERE","PUTSENDERHERE"); $replace_with = array($name,$theBodyOfYourEmail,$whoYouAre);