我有以下发送电子邮件的功能:
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);
}
我想调用包含我的模板的文件 email.html
,而不是 $message
。
我添加了这个:
require 'email.html';
但是我怎样才能在文件中调用呢?
$message = [在此处调用 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,$subject,$message,$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>
所以,在你的 php 代码中你会说:
$parts_to_mod = array("PUTNAMEHERE", "PUTMESSAGEHERE", "PUTSENDERHERE");
$replace_with = array($name, $theBodyOfYourEmail, $whoYouAre);
关于php - 如何在 PHP mail() 函数中包含对文件的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22580380/