使用 php 使用模板发送电子邮件

2022-08-30 10:39:09

我如何使用php发送电子邮件,然后在电子邮件中添加模板设计?我正在使用这个:

$to = "someone@example.com";  
$subject = "Test mail";  
$message = "Hello! This is a simple email message.";  
$from = "someonelse@example.com";  
$headers = "From: $from";  
mail($to,$subject,$message,$headers);  
echo "Mail Sent.";  

而且它工作正常!问题只是如何添加模板。


答案 1

为什么不试试这么简单的事情:

$variables = array();

$variables['name'] = "Robert";
$variables['age'] = "30";

$template = file_get_contents("template.html");

foreach($variables as $key => $value)
{
    $template = str_replace('{{ '.$key.' }}', $value, $template);
}

echo $template;

您的模板文件类似于:

<html>

<p>My name is {{ name }} and I am {{ age }} !</p>

</html>

答案 2

让我们在这个:)

class Emailer
{
    var $recipients = array();
    var $EmailTemplate;
    var $EmailContents;

    public function __construct($to = false)
    {
        if($to !== false)
        {
            if(is_array($to))
            {
                foreach($to as $_to){ $this->recipients[$_to] = $_to; }
            }else
            {
                $this->recipients[$to] = $to; //1 Recip
            }
        }
    }

    function SetTemplate(EmailTemplate $EmailTemplate)
    {
        $this->EmailTemplate = $EmailTemplate;            
    }

    function send() 
    {
        $this->EmailTemplate->compile();
        //your email send code.
    }
}

注意函数 ...SetTemplate()

下面是一个小模板类

class EmailTemplate
{
    var $variables = array();
    var $path_to_file= array();
    function __construct($path_to_file)
    {
         if(!file_exists($path_to_file))
         {
             trigger_error('Template File not found!',E_USER_ERROR);
             return;
         }
         $this->path_to_file = $path_to_file;
    }

    public function __set($key,$val)
    {
        $this->variables[$key] = $val;
    }


    public function compile()
    {
        ob_start();

        extract($this->variables);
        include $this->path_to_file;


        $content = ob_get_contents();
        ob_end_clean();

        return $content;
    }
}

这是一个小例子,你仍然需要做脚本的核心,但这将为您提供一个很好的布局来开始使用。

$emails = array(
    'bob@bobsite.com',
    'you@yoursite.com'
);

$Emailer = new Emailer($emails);
 //More code here

$Template = new EmailTemplate('path/to/my/email/template');
    $Template->Firstname = 'Robert';
    $Template->Lastname = 'Pitt';
    $Template->LoginUrl= 'http://stackoverflow.com/questions/3706855/send-email-with-a-template-using-php';
    //...

$Emailer->SetTemplate($Template); //Email runs the compile
$Emailer->send();

这就是它的全部内容,只需要知道如何使用对象,从那里开始它非常简单,哦,模板看起来有点像这样:

Welcome to my site,

Dear <?php echo $Firstname ?>, You have been registered on our site.

Please visit <a href="<?php echo $LoginUrl ?>">This Link</a> to view your upvotes

Regards.

推荐