加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何在PHP mail()函数中包含对文件的调用

发布时间:2020-12-13 21:51:02 所属栏目:PHP教程 来源:网络整理
导读:我有以下发送电子邮件的功能: function send_email($email){ $subject = "TITLE"; $message = "HERE IS THE MESSAGE"; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "rn"; $headers .= "Content-type:text/html
我有以下发送电子邮件的功能:

function send_email($email){
        $subject = "TITLE";

        $message = "HERE IS THE MESSAGE";

        // Always set content-type when sending HTML email
        $headers = "MIME-Version: 1.0" . "rn";
        $headers .= "Content-type:text/html;charset=UTF-8" . "rn";

        // More headers
        $headers .= 'From: <emaily>' . "rn";

        mail($email,$subject,$message,$headers);
    }

而不是$message是一个字符串,我想调用包含我的模板的文件email.html.

我添加了这个:

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" . "rn";
    $headers .= "Content-type:text/html;charset=UTF-8" . "rn";

    // More headers
    $headers .= 'From: <doNotReply@myDomain.com>' . "rn";
    $headers .= "To: <$email>rn";
    $header .= "Reply-To: doNotReply@myDomain.comrn";

    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>

所以,在你的PHP代码中你会说:

$parts_to_mod = array("PUTNAMEHERE","PUTMESSAGEHERE","PUTSENDERHERE");
$replace_with = array($name,$theBodyOfYourEmail,$whoYouAre);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读