微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有以下发送电子邮件功能

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';

但是我怎么能在文件调用呢?

$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,$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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐